Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add cookie authentication #45

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ JOBS_RETENTION_HOURS=24

OTP_EXPIRATION_MINUTES=15
ENABLE_RATE_LIMIT='true'
COOKIE_SECRET="secret"
COOKIE_EXPIRATION_SECONDS=86400 # 24 hours
2 changes: 2 additions & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ env:
JOBS_RETENTION_HOURS: '24'
OTP_EXPIRATION_MINUTES: '15'
ENABLE_RATE_LIMIT: 'true'
COOKIE_SECRET: 'secret'
COOKIE_EXPIRATION_SECONDS: '3600'

jobs:
build:
Expand Down
2 changes: 2 additions & 0 deletions .woodpecker/.backend-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ x-common: &common
- JOBS_RETENTION_HOURS=24
- OTP_EXPIRATION_MINUTES=15
- ENABLE_RATE_LIMIT=true
- COOKIE_SECRET=secret
- COOKIE_EXPIRATION_SECONDS=3600

pipeline:
setup:
Expand Down
56 changes: 56 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@types/bcryptjs": "^2.4.2",
"@types/body-parser": "^1.19.2",
"@types/compression": "^1.7.2",
"@types/cookie-parser": "^1.4.6",
"@types/cors": "^2.8.12",
"@types/cross-spawn": "^6.0.6",
"@types/express": "^4.17.13",
Expand Down Expand Up @@ -68,6 +69,7 @@
"bullmq": "^4.13.2",
"compression": "^1.7.4",
"concurrently": "^8.2.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"cross-spawn": "^7.0.3",
"date-fns": "^2.30.0",
Expand Down
10 changes: 10 additions & 0 deletions src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ const envVarsSchema = z
'OTP EXPIRATION TIME must be a number',
),
ENABLE_RATE_LIMIT: z.string(),
COOKIE_SECRET: z.string(),
COOKIE_EXPIRATION_SECONDS: z
.string()
.transform((val) => Number(val))
.refine(
(val) => !Number.isNaN(val),
'COOKIE EXPIRATION SECONDS must be a number',
),
})
.passthrough();

Expand Down Expand Up @@ -87,4 +95,6 @@ export const config: Config = {
redisUsername: envVars.REDIS_USERNAME,
jobsRetentionHours: envVars.JOBS_RETENTION_HOURS,
otpExpirationMinutes: envVars.OTP_EXPIRATION_MINUTES,
cookieSecret: envVars.COOKIE_SECRET,
cookieExpirationSeconds: envVars.COOKIE_EXPIRATION_SECONDS,
};
25 changes: 21 additions & 4 deletions src/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import httpStatus from 'http-status';
import { Body, Controller, Post, Request, Route, Security } from 'tsoa';

import { AuthService } from 'services/auth';
import {
CreateUserParams,
Expand All @@ -8,27 +9,43 @@ import {
AuthenticatedRequest,
LoginParams,
} from 'types';
import { COOKIE_NAME, cookieConfig } from 'utils/auth';

@Route('v1/auth')
export class AuthControllerV1 extends Controller {
@Post('/register')
public async register(@Body() user: CreateUserParams): Promise<ReturnAuth> {
const authReturn = await AuthService.register(user);
public async register(
@Body() user: CreateUserParams,
@Request() req: AuthenticatedRequest,
): Promise<ReturnAuth | null> {
const { sessionId, ...authReturn } = await AuthService.register(user);

const { res } = req;
res?.cookie(COOKIE_NAME, sessionId, cookieConfig);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this only be done if the authentication scheme is cookies?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to differentiate between cases for settings and clearing cookies, I'd rather have different endpoints for cookies and tokens than having the user tell me what method it's using, what do you think about it?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't you know what method the client is using? Meaning there is either a token or a cookie.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the case of a register or login endpoint we don't know what method will be used, in other cases we might me able to deduce it based on the authentication method, but in this case we don't know , maybe I'm overlooking something. @chaba11 do you have any idea regarding this?


this.setStatus(httpStatus.CREATED);
return authReturn;
}

@Post('/login')
public async login(@Body() loginParams: LoginParams): Promise<ReturnAuth> {
const authReturn = await AuthService.login(loginParams);
public async login(
@Body() loginParams: LoginParams,
@Request() req: AuthenticatedRequest,
): Promise<ReturnAuth | null> {
const { sessionId, ...authReturn } = await AuthService.login(loginParams);
const { res } = req;
res?.cookie(COOKIE_NAME, sessionId, cookieConfig);
this.setStatus(httpStatus.OK);
return authReturn;
}

@Post('/logout')
@Security('cookie')
@Security('jwt')
public async logout(@Request() req: AuthenticatedRequest): Promise<void> {
await AuthService.logout(req.user.token);
const { res } = req;
res?.clearCookie(COOKIE_NAME);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment

this.setStatus(httpStatus.OK);
}

Expand Down
13 changes: 12 additions & 1 deletion src/controllers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ import {
PasswordResetCodeRequest,
ResetPassword,
} from 'types';
import { COOKIE_NAME } from 'utils/auth';

@Route('v1/users')
export class UsersControllerV1 extends Controller {
@Get()
@Security('jwt')
@Security('cookie')
public async index(): Promise<ReturnUser[]> {
const users = await UserService.all();
this.setStatus(httpStatus.OK);
Expand All @@ -32,6 +34,7 @@ export class UsersControllerV1 extends Controller {

@Get('/me')
@Security('jwt')
@Security('cookie')
public async getMe(
@Request() req: AuthenticatedRequest,
): Promise<ReturnUser | null> {
Expand All @@ -42,6 +45,7 @@ export class UsersControllerV1 extends Controller {

@Get('{id}')
@Security('jwt')
@Security('cookie')
public async find(@Path() id: string): Promise<ReturnUser | null> {
const user = await UserService.find(id);
this.setStatus(httpStatus.OK);
Expand All @@ -50,6 +54,7 @@ export class UsersControllerV1 extends Controller {

@Put('{id}')
@Security('jwt')
@Security('cookie')
public async update(
@Path() id: string,
@Body() requestBody: UpdateUserParams,
Expand All @@ -61,8 +66,14 @@ export class UsersControllerV1 extends Controller {

@Delete('{id}')
@Security('jwt')
public async destroy(@Path() id: string): Promise<void> {
@Security('cookie')
public async destroy(
@Path() id: string,
@Request() req: AuthenticatedRequest,
): Promise<void> {
const { user, res } = req;
await UserService.destroy(id);
if (user.id === id) res?.clearCookie(COOKIE_NAME);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this line is needed. You might want to destroy all sessions of the user though.

this.setStatus(httpStatus.NO_CONTENT);
}

Expand Down
6 changes: 6 additions & 0 deletions src/middlewares/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import jwt from 'jsonwebtoken';
import { config } from 'config/config';
import { ApiError } from 'utils/apiError';
import { errors } from 'config/errors';
import { verifyCookie } from 'utils/auth';

export function expressAuthentication(
request: Request,
Expand Down Expand Up @@ -32,5 +33,10 @@ export function expressAuthentication(
});
});
}
if (securityName === 'cookie') {
const { signedCookies } = request;

return verifyCookie(signedCookies);
}
return Promise.resolve(null);
}
5 changes: 5 additions & 0 deletions src/middlewares/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import express, { Application } from 'express';
import helmet from 'helmet';
import compression from 'compression';
import cors from 'cors';
import cookieParser from 'cookie-parser';

import { applyRateLimit } from 'middlewares/rateLimiter';
import { morganHandlers } from 'config/morgan';
import { errorConverter, errorHandler } from 'middlewares/error';
import { Wrapper } from 'types';
import { config } from 'config/config';

export const preRoutesMiddleware = (app: Application) => {
// Set security HTTP headers
Expand All @@ -30,6 +33,8 @@ export const preRoutesMiddleware = (app: Application) => {
app.use(morganHandlers.successHandler);
app.use(morganHandlers.errorHandler);
app.use(morganHandlers.debugHandler);

app.use(cookieParser(config.cookieSecret));
};

// Middleware separated to use our error handler when a route is not found
Expand Down
22 changes: 15 additions & 7 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as bcrypt from 'bcryptjs';
import {
ReturnAuth,
ReturnAuthService,
CreateUserParams,
LoginParams,
RefreshTokenParams,
Expand All @@ -12,7 +12,9 @@ import { generateAccessToken, generateRefreshToken } from 'utils/token';
import { UserService } from '.';

export class AuthService {
static register = async (userBody: CreateUserParams): Promise<ReturnAuth> => {
static register = async (
userBody: CreateUserParams,
): Promise<ReturnAuthService> => {
const user = await UserService.create(userBody);
const accessToken = await generateAccessToken(user);
const refreshToken = await generateRefreshToken(user);
Expand All @@ -21,14 +23,17 @@ export class AuthService {
accessToken,
refreshToken,
};
await prisma.session.create({ data: sessionData });
const session = await prisma.session.create({ data: sessionData });
return {
sessionId: session.id,
accessToken,
refreshToken,
};
};

static login = async (loginParams: LoginParams): Promise<ReturnAuth> => {
static login = async (
loginParams: LoginParams,
): Promise<ReturnAuthService> => {
const { email, password } = loginParams;
const user = await prisma.user.findUnique({ where: { email } });
if (!user) {
Expand All @@ -39,7 +44,7 @@ export class AuthService {
if (!isPasswordValid) {
throw new ApiError(errors.INVALID_CREDENTIALS);
}
const session = await prisma.session.findUnique({
let session = await prisma.session.findUnique({
where: { userId: user.id },
});
const accessToken = await generateAccessToken(user);
Expand All @@ -49,6 +54,7 @@ export class AuthService {
data: { accessToken },
});
return {
sessionId: session.id,
accessToken,
refreshToken: session.refreshToken,
};
Expand All @@ -60,8 +66,9 @@ export class AuthService {
accessToken,
refreshToken,
};
await prisma.session.create({ data: sessionData });
session = await prisma.session.create({ data: sessionData });
return {
sessionId: session.id,
accessToken,
refreshToken,
};
Expand All @@ -73,7 +80,7 @@ export class AuthService {

static refresh = async (
refreshTokenParams: RefreshTokenParams,
): Promise<ReturnAuth> => {
): Promise<ReturnAuthService> => {
const { refreshToken } = refreshTokenParams;
const session = await prisma.session.findUnique({
where: { refreshToken },
Expand All @@ -94,6 +101,7 @@ export class AuthService {
data: { accessToken },
});
return {
sessionId: session.id,
accessToken,
refreshToken,
};
Expand Down
Loading