Skip to content

Commit

Permalink
fix bug when disable hashing token
Browse files Browse the repository at this point in the history
  • Loading branch information
duysolo committed Dec 14, 2024
1 parent 4c740c3 commit aa1b364
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 21 deletions.
82 changes: 82 additions & 0 deletions src/__tests__/auth.module.fastify.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,85 @@ describe('AuthModule (e2e) - Fastify Adaptor', () => {
},
})
})

describe('AuthModule (e2e) - Fastify Adaptor - Without hashing token', () => {
e2eTestsSetup<NestFastifyApplication>({
initApp: async () => {
const definitions = defaultAuthDefinitionsFixture({
httpAdaptorType: 'fastify',
enableHashingToken: false
})

const app = await createTestAuthApplicationFastify(definitions)

return { app, definitions }
},
loginRequest: () => {
return (app, body) =>
fastifyRequest(app, {
method: 'POST',
path: '/auth/login',
body,
}).then((response) => {
const parsedResponseBody: IAuthWithTokenResponse = response.json() || {}

return {
statusCode: response.statusCode,
authResponse: parsedResponseBody,
headers: response.headers,
cookies: response.cookies,
}
})
},
refreshTokenRequest: () => {
return (app, refreshToken) =>
fastifyRequest(app, {
method: 'POST',
path: '/auth/refresh-token',
headers: {
'Refresh-Token': `${refreshToken}`,
},
}).then((response) => {
const parsedResponseBody: IRefreshTokenAuthResponse =
response.json() || {}

return {
statusCode: response.statusCode,
authResponse: parsedResponseBody,
headers: response.headers,
cookies: response.cookies,
}
})
},
getProfileRequest: () => {
return (app, accessToken) => {
return fastifyRequest(app, {
method: 'GET',
path: '/auth/profile',
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then((response) => {
return {
statusCode: response.statusCode,
userData: response.json() || {},
}
})
}
},
logoutRequest: () => {
return (app, accessToken) =>
fastifyRequest(app, {
method: 'POST',
path: '/auth/logout',
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then((response) => {
return {
statusCode: response.statusCode,
}
})
},
})
})
42 changes: 34 additions & 8 deletions src/domain/services/hash-text.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ export class HashTextService {
private readonly _algorithm: string = 'aes-256-ctr'

public constructor(private readonly _options: IHashingOptions) {
if (
_options.enabled &&
(!_options?.secretKey || _options.secretKey.length !== 32)
) {
if (!_options?.secretKey || _options.secretKey.length !== 32) {
throw new BadRequestException(
'INVALID_HASHING_SECRET_KEY',
'Secret key is required and should be 32 characters'
Expand All @@ -24,15 +21,15 @@ export class HashTextService {
}

public encode(textToEncode: string): string {
if (!textToEncode || !this._options.enabled || !this._options.secretKey) {
if (!textToEncode) {
return textToEncode
}

const iv = crypto.randomBytes(16)

const cipher = crypto.createCipheriv(
this._algorithm,
this._options.secretKey,
this._options.secretKey!,
iv
)

Expand All @@ -50,7 +47,7 @@ export class HashTextService {
}

public decode(hashedText: string): string | undefined {
if (!hashedText || !this._options.enabled || !this._options.secretKey) {
if (!hashedText) {
return hashedText
}

Expand All @@ -61,7 +58,7 @@ export class HashTextService {

const decipher = crypto.createDecipheriv(
this._algorithm,
this._options.secretKey,
this._options.secretKey!,
Buffer.from(hash.iv, 'hex')
)

Expand Down Expand Up @@ -92,3 +89,32 @@ export class HashTextService {
}
}
}

@Injectable()
export class NoHashTextService {
public encode(textToEncode: string): string {
return textToEncode
}

public decode(hashedText: string): string | undefined {
return hashedText
}

public encodeJSON(obj: any): string | undefined {
try {
return this.encode(JSON.stringify(obj))
} catch {
return undefined
}
}

public decodeJSON<T = any>(hashedObj: string): T | undefined {
try {
const decodedText = this.decode(hashedObj)

return decodedText ? JSON.parse(decodedText) : undefined
} catch {
return undefined
}
}
}
28 changes: 15 additions & 13 deletions src/hashing.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DynamicModule, Module, Provider } from '@nestjs/common'
import { ModuleMetadata } from '@nestjs/common/interfaces'
import { HashTextService } from './index'
import { HashTextService, NoHashTextService } from './index'

const HASHING_MODULE_OPTIONS: symbol = Symbol('HASHING_MODULE_OPTIONS')

Expand All @@ -24,14 +24,14 @@ export class HashingModule {

return {
module: HashingModule,
providers: enabled
? [
{
provide: HashTextService,
useValue: new HashTextService({ ...options, enabled }),
},
]
: [],
providers: [
{
provide: HashTextService,
useValue: enabled
? new HashTextService({ ...options, enabled })
: new NoHashTextService(),
},
],
exports: [HashTextService],
global: options.global || false,
}
Expand All @@ -51,10 +51,12 @@ export class HashingModule {
useFactory: (options: IHashingOptions) => {
const { enabled = true } = options

return enabled ? new HashTextService({
...options,
enabled
}) : undefined
return enabled
? new HashTextService({
...options,
enabled,
})
: new NoHashTextService()
},
inject: [HASHING_MODULE_OPTIONS],
}
Expand Down

0 comments on commit aa1b364

Please sign in to comment.