57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
import * as moment from 'moment';
|
|
import { Injectable } from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { UserEntity } from 'src/users/entities/users.entity';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { PinoLogger } from 'nestjs-pino';
|
|
|
|
@Injectable()
|
|
export class AuthAccessService {
|
|
constructor(
|
|
private jwts: JwtService,
|
|
private config: ConfigService,
|
|
private logger: PinoLogger,
|
|
) { }
|
|
|
|
async generate(user: UserEntity) {
|
|
const now = new Date();
|
|
const limit = parseInt(this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
|
|
const expiration = moment(now).add(limit, 'ms').toDate();
|
|
|
|
const token = await this.jwts.signAsync(
|
|
{
|
|
username: user.userLogin,
|
|
sub: user.userId,
|
|
iat: Math.floor(now.getTime() / 1000),
|
|
nbf: Math.floor(now.getTime() / 1000) - 5 * 60,
|
|
exp: Math.floor(expiration.getTime() / 1000),
|
|
},
|
|
{
|
|
secret: this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_SECRET'),
|
|
}
|
|
);
|
|
|
|
this.logger.debug({
|
|
class: AuthAccessService.name,
|
|
method: this.generate.name,
|
|
user,
|
|
access_token: token,
|
|
exp: expiration,
|
|
msg: 'User generated an access token.',
|
|
});
|
|
|
|
return {
|
|
access_token: token,
|
|
exp: expiration.getTime(),
|
|
}
|
|
}
|
|
|
|
async verify(token: string) {
|
|
return await this.jwts.verifyAsync(token,
|
|
{
|
|
secret: this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_SECRET')
|
|
}
|
|
);
|
|
}
|
|
}
|