Skip to content

Commit e1f1eb3

Browse files
committed
Refactor auth controller and service
1 parent 9f8b1b5 commit e1f1eb3

File tree

4 files changed

+25
-14
lines changed

4 files changed

+25
-14
lines changed

src/core/auth/auth.controller.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import { AuthGuard } from '@nestjs/passport';
88
import { Response } from 'express';
99
import { ReqIdentity } from '~/_common/decorators/params/req-identity.decorator';
1010
import { AgentType } from '~/_common/types/agent.type';
11+
import { hash } from 'crypto';
12+
import { omit } from 'radash';
1113

1214
@Public()
1315
@ApiTags('core/auth')
@@ -38,8 +40,8 @@ export class AuthController extends AbstractController {
3840
const user = await this.service.getSessionData(identity);
3941
return res.status(HttpStatus.OK).json({
4042
user: {
41-
...user,
42-
sseToken: 'hZcdVqHScVDsDFdHOdcjmufEKFJVKaS8', //TODO: change to real token
43+
...omit(user, ['security']),
44+
sseToken: hash('sha256', user.security.secretKey),
4345
},
4446
});
4547
}
@@ -48,10 +50,10 @@ export class AuthController extends AbstractController {
4850
@Post('refresh')
4951
@ApiOperation({ summary: "Récupère un nouveau jeton d'authentification" })
5052
public async refresh(@Res() res: Response, @Body() body: { refresh_token: string }): Promise<Response> {
51-
const tokens = await this.service.renewTokens(body.refresh_token);
53+
const [agents, tokens] = await this.service.renewTokens(body.refresh_token);
5254
return res.status(HttpStatus.OK).json({
5355
...tokens,
54-
sseToken: 'hZcdVqHScVDsDFdHOdcjmufEKFJVKaS8', //TODO: change to real token
56+
sseToken: hash('sha256', agents.security.secretKey),
5557
});
5658
}
5759

src/core/auth/auth.service.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ export class AuthService extends AbstractService implements OnModuleInit {
9393
if (identity) {
9494
return identity.toObject();
9595
}
96-
} catch (e) {}
96+
} catch (e) { }
9797
return null;
9898
}
9999
try {
@@ -178,16 +178,16 @@ export class AuthService extends AbstractService implements OnModuleInit {
178178
};
179179
}
180180

181-
public async renewTokens(refresh_token: string): Promise<{
181+
public async renewTokens(refresh_token: string): Promise<[Agents, {
182182
access_token: string;
183183
refresh_token?: string;
184-
}> {
184+
}]> {
185185
const data = await this.redis.get([this.REFRESH_TOKEN_PREFIX, refresh_token].join(this.TOKEN_PATH_SEPARATOR));
186186
if (!data) throw new UnauthorizedException();
187187
const { identityId } = JSON.parse(data);
188-
const identity = await this.agentsService.findOne({ _id: identityId });
188+
const identity = await this.agentsService.findOne<Agents>({ _id: identityId });
189189
if (!identity) throw new ForbiddenException();
190-
return this.createTokens(omit(identity.toObject(), ['password']), refresh_token);
190+
return [identity, await this.createTokens(omit(identity.toObject(), ['password']), refresh_token)];
191191
}
192192

193193
public async clearSession(jwt: string): Promise<void> {

src/core/backends/backends.controller.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ import {
77
ParseIntPipe,
88
Post,
99
Query,
10+
Req,
1011
Res,
1112
Sse,
1213
UnauthorizedException,
1314
} from '@nestjs/common';
1415
import { ApiOperation, ApiTags } from '@nestjs/swagger';
15-
import { Response } from 'express';
16+
import { Response, Request } from 'express';
1617
import Redis from 'ioredis';
1718
import { Observable, Subscriber } from 'rxjs';
1819
import { Public } from '~/_common/decorators/public.decorator';
@@ -22,6 +23,9 @@ import { SyncIdentitiesDto } from './_dto/sync-identities.dto';
2223
import { Types } from 'mongoose';
2324
import { ActionType } from './_enum/action-type.enum';
2425
import { DeleteIdentitiesDto } from './_dto/delete-identities.dto';
26+
import { hash } from 'crypto';
27+
import { AgentsService } from '../agents/agents.service';
28+
import { Agents } from '../agents/_schemas/agents.schema';
2529

2630
function fireMessage(observer: Subscriber<MessageEvent>, channel: string, message: any, loggername: string) {
2731
try {
@@ -40,6 +44,7 @@ export class BackendsController {
4044
private readonly logger = new Logger(BackendsController.name);
4145

4246
constructor(
47+
private agentsService: AgentsService,
4348
private backendsService: BackendsService,
4449
@InjectRedis() protected readonly redis: Redis,
4550
) { }
@@ -124,8 +129,11 @@ export class BackendsController {
124129
@Public()
125130
@Sse('sse')
126131
@ApiOperation({ summary: 'Server Sent Event - Récupère en temps réel les Jobs et affiche leurs état' })
127-
public async sse(@Res() res: Response, @Query('key') key: string): Promise<Observable<MessageEvent>> {
128-
if (key !== 'hZcdVqHScVDsDFdHOdcjmufEKFJVKaS8') throw new UnauthorizedException();
132+
public async sse(@Res() res: Response, @Query('id') id: string, @Query('key') key: string): Promise<Observable<MessageEvent>> {
133+
if (!id || !key) throw new UnauthorizedException();
134+
const user = await this.agentsService.findById<Agents>(id);
135+
if (!user) throw new UnauthorizedException();
136+
if (key !== hash('sha256', user.security.secretKey)) throw new UnauthorizedException();
129137

130138
res.socket.on('close', () => {
131139
Logger.debug(`Observer close connection`, this.constructor.name);

src/core/backends/backends.module.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ import { ConfigModule } from '@nestjs/config';
55
import { IdentitiesModule } from '~/management/identities/identities.module';
66
import { JobsModule } from '../jobs/jobs.module';
77
import { TasksModule } from '../tasks/tasks.module';
8+
import { AgentsModule } from '../agents/agents.module';
89
@Module({
9-
imports: [ConfigModule, IdentitiesModule, JobsModule, TasksModule],
10+
imports: [ConfigModule, IdentitiesModule, JobsModule, TasksModule, AgentsModule],
1011
controllers: [BackendsController],
1112
providers: [BackendsService],
1213
exports: [BackendsService],
1314
})
14-
export class BackendsModule {}
15+
export class BackendsModule { }

0 commit comments

Comments
 (0)