Skip to content

Commit

Permalink
fix(auth): use constants to name the token's cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
leosuncin committed Sep 5, 2022
1 parent 0fb2001 commit e6b60ba
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 14 deletions.
11 changes: 7 additions & 4 deletions src/auth/auth.module.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import request, { agent } from 'supertest';
import { runSeeders } from 'typeorm-extension';

import { AuthModule } from '~auth/auth.module';
import { TOKEN_COOKIE_NAME } from '~auth/constants';
import type { User } from '~auth/entities/user.entity';
import { loginUserFactory } from '~auth/factories/login-user.factory';
import { registerUserFactory } from '~auth/factories/register-user.factory';
Expand All @@ -21,6 +22,8 @@ const unprocessableError = {
message: expect.arrayContaining([expect.any(String)]),
statusCode: HttpStatus.UNPROCESSABLE_ENTITY,
};
// eslint-disable-next-line security/detect-non-literal-regexp
const cookieRegex = new RegExp(`${TOKEN_COOKIE_NAME}=`, 'iu');

describe('Auth module', () => {
const password = credentials.password;
Expand All @@ -47,7 +50,7 @@ describe('Auth module', () => {
.post('/auth/register')
.send(data)
.expect(HttpStatus.CREATED)
.expect('set-cookie', /token=/)
.expect('set-cookie', cookieRegex)
.expect(({ body }) => {
expect(body).toMatchObject({
email: data.email,
Expand Down Expand Up @@ -105,7 +108,7 @@ describe('Auth module', () => {
.post('/auth/login')
.send(data)
.expect(HttpStatus.OK)
.expect('set-cookie', /token=/)
.expect('set-cookie', cookieRegex)
.expect(({ body }) => {
expect(body).toMatchObject({
email: user.email,
Expand Down Expand Up @@ -150,7 +153,7 @@ describe('Auth module', () => {
.post('/auth/login')
.send({ username: user.username, password })
.expect(HttpStatus.OK)
.expect('set-cookie', /token=/);
.expect('set-cookie', cookieRegex);

await client
.get('/auth/me')
Expand Down Expand Up @@ -267,7 +270,7 @@ describe('Auth module', () => {
.post('/auth/login')
.send({ username: user.username, password })
.expect(HttpStatus.OK)
.expect('set-cookie', /token=/);
.expect('set-cookie', cookieRegex);

await client
.patch('/auth/me')
Expand Down
3 changes: 3 additions & 0 deletions src/auth/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const JWT_STRATEGY_NAME = 'jwt';

export const TOKEN_COOKIE_NAME = 'token';
4 changes: 2 additions & 2 deletions src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

import { JWT } from '~auth/strategies/jwt.strategy';
import { JWT_STRATEGY_NAME } from '~app/auth/constants';

@Injectable()
export class JWTAuthGuard extends AuthGuard(JWT) {}
export class JWTAuthGuard extends AuthGuard(JWT_STRATEGY_NAME) {}
3 changes: 2 additions & 1 deletion src/auth/interceptors/token.interceptor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { lastValueFrom, of } from 'rxjs';
import { createMock } from 'ts-auto-mock';

import { type AuthConfig, auth } from '~auth/config/auth';
import { TOKEN_COOKIE_NAME } from '~auth/constants';
import type { User } from '~auth/entities/user.entity';
import { john as user } from '~auth/fixtures/users';
import { TokenInterceptor } from '~auth/interceptors/token.interceptor';
Expand Down Expand Up @@ -58,6 +59,6 @@ describe('TokenInterceptor', () => {
await expect(
lastValueFrom(interceptor.intercept(testContext, nextSpy)),
).resolves.toEqual(user);
expect(res.cookies).toHaveProperty('token');
expect(res.cookies).toHaveProperty(TOKEN_COOKIE_NAME);
});
});
3 changes: 2 additions & 1 deletion src/auth/interceptors/token.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import type { AuthConfig } from '~auth/config/auth';
import { TOKEN_COOKIE_NAME } from '~auth/constants/index';
import type { User } from '~auth/entities/user.entity';

@Injectable()
Expand All @@ -34,7 +35,7 @@ export class TokenInterceptor implements NestInterceptor {
map((user) => {
const token = this.generateToken(user);

response.cookie('token', token, this.options);
response.cookie(TOKEN_COOKIE_NAME, token, this.options);

return user;
}),
Expand Down
8 changes: 4 additions & 4 deletions src/auth/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, JwtFromRequestFunction, Strategy } from 'passport-jwt';

import { JWT_STRATEGY_NAME,TOKEN_COOKIE_NAME } from '~auth/constants';
import type { User } from '~auth/entities/user.entity';
import type { JwtPayload } from '~auth/interfaces/jwt-payload.interface';
import { AuthenticationService } from '~auth/services/authentication.service';
Expand All @@ -13,14 +14,13 @@ declare module 'express' {
}
}

export const JWT = 'jwt' as const;

const extractJwtFromCookie: JwtFromRequestFunction = (request) => {
return request.signedCookies['token']!;
// eslint-disable-next-line security/detect-object-injection, @typescript-eslint/no-non-null-assertion
return request.signedCookies[TOKEN_COOKIE_NAME]!;
};

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, JWT) {
export class JwtStrategy extends PassportStrategy(Strategy, JWT_STRATEGY_NAME) {
constructor(private readonly authenticationService: AuthenticationService) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
Expand Down
5 changes: 3 additions & 2 deletions test/auth.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { HttpStatus } from '@nestjs/common';
import { request, spec } from 'pactum';

import { TOKEN_COOKIE_NAME } from '~auth/constants';
import { loginUserFactory } from '~auth/factories/login-user.factory';
import { registerUserFactory } from '~auth/factories/register-user.factory';
import { updateUserFactory } from '~auth/factories/update-user.factory';
Expand Down Expand Up @@ -30,7 +31,7 @@ describe('AuthController (e2e)', () => {
.withBody(data)
.expectStatus(HttpStatus.CREATED)
.expectCookiesLike({
token: 'typeof $V === "string"',
[TOKEN_COOKIE_NAME]: 'typeof $V === "string"',
// eslint-disable-next-line unicorn/no-null
HttpOnly: null,
SameSite: 'Strict',
Expand Down Expand Up @@ -84,7 +85,7 @@ describe('AuthController (e2e)', () => {
.withBody(credentials)
.expectStatus(HttpStatus.OK)
.expectCookiesLike({
token: 'typeof $V === "string"',
[TOKEN_COOKIE_NAME]: 'typeof $V === "string"',
// eslint-disable-next-line unicorn/no-null
HttpOnly: null,
SameSite: 'Strict',
Expand Down

0 comments on commit e6b60ba

Please sign in to comment.