Skip to content

Commit d14301b

Browse files
committed
Ajouter les modifications du module AuthModule
1 parent e2bfbb0 commit d14301b

File tree

6 files changed

+64
-12
lines changed

6 files changed

+64
-12
lines changed

src/_common/data/api-session.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export class ApiSession {
2+
public readonly _id: string;
3+
public readonly username: string;
4+
public readonly displayName: string;
5+
public readonly token: string;
6+
7+
public constructor(data: Partial<ApiSession>) {
8+
for (const key in data) {
9+
this[key] = data[key];
10+
}
11+
}
12+
}
Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import { Types } from 'mongoose';
2-
31
export class ConsoleSession {
42
public readonly _id: string = '000000000000000000000000';
53
public readonly username: string = 'console';
6-
public readonly entityId: Types.ObjectId = new Types.ObjectId('000000000000000000000000');
74
public readonly displayName: string = 'Console';
5+
86
public constructor() {}
97
}

src/cli/cli.module.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { KeyringsCommand, KeyringsCreateQuestions } from './keyrings.command';
1212
import { KeyringsModule } from '~/core/keyrings/keyrings.module';
1313
import { BackendsCommand } from './backends.command';
1414
import { BackendsModule } from '~/core/backends/backends.module';
15+
import { AuthModule } from '~/core/auth/auth.module';
1516

1617
@Module({
1718
imports: [
@@ -57,6 +58,7 @@ import { BackendsModule } from '~/core/backends/backends.module';
5758
AgentsModule,
5859
KeyringsModule,
5960
BackendsModule,
61+
AuthModule,
6062
],
6163
providers: [
6264
...AgentsCommand.registerWithSubCommands(),

src/cli/keyrings.command.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { ModuleRef } from '@nestjs/core';
22
import { Command, CommandRunner, InquirerService, Question, QuestionSet, SubCommand } from 'nest-commander';
3+
import { ApiSession } from '~/_common/data/api-session';
4+
import { AuthService } from '~/core/auth/auth.service';
35
import { KeyringsCreateDto } from '~/core/keyrings/_dto/keyrings.dto';
6+
import { Keyrings } from '~/core/keyrings/_schemas/keyrings.schema';
47
import { KeyringsService } from '~/core/keyrings/keyrings.service';
58

69
@QuestionSet({ name: 'keyrings-create-questions' })
@@ -20,6 +23,7 @@ export class KeyringsCreateCommand extends CommandRunner {
2023
protected moduleRef: ModuleRef,
2124
private readonly inquirer: InquirerService,
2225
private readonly keyringsService: KeyringsService,
26+
private readonly authService: AuthService,
2327
) {
2428
super();
2529
}
@@ -28,8 +32,27 @@ export class KeyringsCreateCommand extends CommandRunner {
2832
async run(inputs: string[], options: any): Promise<void> {
2933
const keyring = await this.inquirer.ask<KeyringsCreateDto>('keyrings-create-questions', undefined);
3034
try {
31-
const key = await this.keyringsService.create(keyring);
35+
const key = (await this.keyringsService.create(keyring)) as Keyrings;
3236
console.log('Keyring created successfully', key.toJSON());
37+
const options = {
38+
scopes: ['api'],
39+
};
40+
if (key.suspendedAt) {
41+
options['expiresIn'] = key.suspendedAt.getTime() - Date.now();
42+
} else {
43+
options['expiresIn'] = '10y';
44+
}
45+
const { access_token } = await this.authService.createTokens(
46+
new ApiSession({
47+
_id: key._id.toString(),
48+
username: key.name,
49+
displayName: key.name,
50+
token: key.token,
51+
}),
52+
false,
53+
options,
54+
);
55+
console.log('Keyring created successfully', access_token);
3356
} catch (error) {
3457
console.error('Error creating keyring', error);
3558
}

src/core/auth/auth.module.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { AgentsModule } from '~/core/agents/agents.module';
77
import { JwtModule, JwtModuleOptions } from '@nestjs/jwt';
88
import { JwtStrategy } from '~/core/auth/_strategies/jwt.strategy';
99
import { LocalStrategy } from '~/core/auth/_strategies/local.strategy';
10+
import { KeyringsModule } from '../keyrings/keyrings.module';
1011

1112
@Module({
1213
imports: [
@@ -25,8 +26,10 @@ import { LocalStrategy } from '~/core/auth/_strategies/local.strategy';
2526
}),
2627
}),
2728
AgentsModule,
29+
KeyringsModule,
2830
],
2931
controllers: [AuthController],
3032
providers: [AuthService, JwtStrategy, LocalStrategy],
33+
exports: [AuthService],
3134
})
3235
export class AuthModule {}

src/core/auth/auth.service.ts

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { JwtService } from '@nestjs/jwt';
1414
import { resolve } from 'path';
1515
import { existsSync, readFileSync, writeFileSync } from 'fs';
1616
import { ConsoleSession } from '~/_common/data/console-session';
17+
import { KeyringsService } from '../keyrings/keyrings.service';
1718

1819
@Injectable()
1920
export class AuthService extends AbstractService implements OnModuleInit {
@@ -29,6 +30,7 @@ export class AuthService extends AbstractService implements OnModuleInit {
2930
public constructor(
3031
protected moduleRef: ModuleRef,
3132
protected readonly agentsService: AgentsService,
33+
protected readonly keyringsService: KeyringsService,
3234
private readonly jwtService: JwtService,
3335
@InjectRedis() private readonly redis: Redis,
3436
) {
@@ -52,6 +54,7 @@ export class AuthService extends AbstractService implements OnModuleInit {
5254
}
5355
const { access_token } = await this.createTokens(new ConsoleSession(), false, {
5456
expiresIn: '1y',
57+
scopes: ['offline', 'api'],
5558
});
5659
writeFileSync(
5760
devTokenPath,
@@ -78,17 +81,28 @@ export class AuthService extends AbstractService implements OnModuleInit {
7881
}
7982

8083
// eslint-disable-next-line
81-
public async verifyIdentity(payload: any & { identity: AgentType }): Promise<any> {
84+
public async verifyIdentity(payload: any & { identity: AgentType & {token: string} }): Promise<any> {
85+
if (payload.scopes.includes('offline')) {
86+
return payload.identity;
87+
}
88+
if (payload.scopes.includes('api')) {
89+
try {
90+
const identity = await this.keyringsService.findOne({
91+
_id: payload.identity._id,
92+
token: payload.identity.token,
93+
});
94+
if (identity) {
95+
return identity.toObject();
96+
}
97+
} catch (e) {}
98+
return null;
99+
}
82100
try {
83-
if (payload.scopes.includes('offline')) {
84-
return payload.identity;
85-
}
86101
const identity = await this.redis.get([this.ACCESS_TOKEN_PREFIX, payload.jti].join(':'));
87102
if (identity) {
88103
return JSON.parse(identity);
89104
}
90-
} finally {
91-
}
105+
} catch (e) {}
92106
return null;
93107
}
94108

@@ -101,15 +115,15 @@ export class AuthService extends AbstractService implements OnModuleInit {
101115
refresh_token?: string;
102116
}> {
103117
const scopes = ['sesame'];
104-
if (refresh_token === false) scopes.push('offline');
118+
if (options?.scopes) scopes.push(...options.scopes);
105119
const jwtid = `${identity._id}_${randomBytes(16).toString('hex')}`;
106120
const access_token = this.jwtService.sign(
107121
{ identity, scopes },
108122
{
109123
expiresIn: this.ACCESS_TOKEN_EXPIRES_IN,
110124
jwtid,
111125
subject: `${identity._id}`,
112-
...options,
126+
...omit(options, ['scopes']),
113127
},
114128
);
115129
if (refresh_token === false) return { access_token };

0 commit comments

Comments
 (0)