Skip to content

Commit ade91ca

Browse files
committed
Refactor JWT strategy and authentication service for improved logging and identity handling
1 parent cd2bafb commit ade91ca

File tree

3 files changed

+22
-20
lines changed

3 files changed

+22
-20
lines changed

src/core/auth/_strategies/jwt.strategy.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { JwtPayload } from 'jsonwebtoken';
99

1010
@Injectable()
1111
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
12-
protected logger: Logger;
12+
protected logger: Logger = new Logger(JwtStrategy.name);
1313

1414
constructor(
1515
private readonly auth: AuthService,
@@ -29,7 +29,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
2929
payload: JwtPayload & { identity: AgentType },
3030
done: VerifiedCallback,
3131
): Promise<void> {
32-
this.logger.verbose(`Atempt to authenticate with JTI: <${payload.jti}>`, JwtStrategy.name);
32+
this.logger.verbose(`Atempt to authenticate with JTI: <${payload.jti}>`);
3333
if (!payload?.identity) return done(new UnauthorizedException(), false);
3434
const user = await this.auth.verifyIdentity(payload);
3535

src/core/auth/auth.controller.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { Response } from 'express';
99
import { ReqIdentity } from '~/_common/decorators/params/req-identity.decorator';
1010
import { AgentType } from '~/_common/types/agent.type';
1111
import { hash } from 'crypto';
12-
import { omit } from 'radash';
12+
import { omit, pick } from 'radash';
1313

1414
@Public()
1515
@ApiTags('core/auth')
@@ -37,12 +37,12 @@ export class AuthController extends AbstractController {
3737
@UseGuards(AuthGuard('jwt'))
3838
@ApiOperation({ summary: 'Récupération de la session en cours' })
3939
public async session(@Res() res: Response, @ReqIdentity() identity: AgentType): Promise<Response> {
40-
this.logger.debug(`Session request for ${identity.id} (${identity.email})`);
40+
this.logger.debug(`Session request for ${identity._id} (${identity.email})`);
4141
const user = await this.service.getSessionData(identity);
42-
this.logger.debug(`Session data delivered for ${identity.id} (${identity.email}) with ${JSON.stringify(user)}`);
42+
this.logger.debug(`Session data delivered for ${identity._id} (${identity.email}) with ${JSON.stringify(user)}`);
4343
return res.status(HttpStatus.OK).json({
4444
user: {
45-
...omit(user, ['security']),
45+
...omit(user, ['security', 'metadata']),
4646
sseToken: hash('sha256', user.security.secretKey),
4747
},
4848
});

src/core/auth/auth.service.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { verify as argon2Verify } from 'argon2';
88
import { Agents } from '~/core/agents/_schemas/agents.schema';
99
import { AgentsService } from '~/core/agents/agents.service';
1010
import { AgentType } from '~/_common/types/agent.type';
11-
import { omit } from 'radash';
11+
import { omit, pascal, pick } from 'radash';
1212
import { JwtPayload } from 'jsonwebtoken';
1313
import { JwtService } from '@nestjs/jwt';
1414
import { resolve } from 'path';
@@ -81,6 +81,7 @@ export class AuthService extends AbstractService implements OnModuleInit {
8181

8282
// eslint-disable-next-line
8383
public async verifyIdentity(payload: any & { identity: AgentType & { token: string } }): Promise<any> {
84+
console.log('payload', payload);
8485
if (payload.scopes.includes('offline')) {
8586
return payload.identity;
8687
}
@@ -100,6 +101,7 @@ export class AuthService extends AbstractService implements OnModuleInit {
100101
const identity = await this.redis.get([this.ACCESS_TOKEN_PREFIX, payload.jti].join(':'));
101102
if (identity) {
102103
const data = JSON.parse(identity);
104+
console.log('data', data);
103105
const success = await this.agentsService.model.countDocuments({
104106
_id: payload.identity._id,
105107
'security.secretKey': data.identity?.security?.secretKey,
@@ -125,7 +127,7 @@ export class AuthService extends AbstractService implements OnModuleInit {
125127
if (options?.scopes) scopes.push(...options.scopes);
126128
const jwtid = `${identity._id}_${randomBytes(16).toString('hex')}`;
127129
const access_token = this.jwtService.sign(
128-
{ identity, scopes },
130+
{ identity: pick(identity, ['_id', 'username', 'email']), scopes },
129131
{
130132
expiresIn: this.ACCESS_TOKEN_EXPIRES_IN,
131133
jwtid,
@@ -147,10 +149,11 @@ export class AuthService extends AbstractService implements OnModuleInit {
147149
[this.REFRESH_TOKEN_PREFIX, refresh_token].join(this.TOKEN_PATH_SEPARATOR),
148150
this.REFRESH_TOKEN_EXPIRES_IN,
149151
);
152+
const userIdentity = await this.agentsService.findOne<Agents>({ _id: identity._id });
150153
await this.redis.set(
151154
[this.ACCESS_TOKEN_PREFIX, jwtid].join(this.TOKEN_PATH_SEPARATOR),
152155
JSON.stringify({
153-
identity,
156+
identity: userIdentity.toJSON(),
154157
refresh_token,
155158
}),
156159
'EX',
@@ -162,19 +165,18 @@ export class AuthService extends AbstractService implements OnModuleInit {
162165
};
163166
}
164167

165-
//TODO: change any
166168
public async getSessionData(identity: AgentType): Promise<AgentType> {
167-
// const entity = await this.agentsService.findOne<Agents>(
168-
// { _id: identity.entityId },
169-
// {
170-
// projection: {
171-
// metadata: 0,
172-
// },
173-
// },
174-
// )
169+
const entity = await this.agentsService.findOne<Agents>(
170+
{ _id: identity._id },
171+
{
172+
projection: {
173+
metadata: 0,
174+
password: 0,
175+
},
176+
},
177+
)
175178
return {
176-
...identity,
177-
// entity,
179+
...omit(entity.toJSON(), ['password']),
178180
};
179181
}
180182

0 commit comments

Comments
 (0)