Files
Picsur/backend/src/managers/auth/auth.service.ts

31 lines
963 B
TypeScript
Raw Normal View History

2022-02-26 18:16:28 +01:00
import { Injectable, Logger } from '@nestjs/common';
2022-02-21 14:53:21 +01:00
import { JwtService } from '@nestjs/jwt';
2022-02-28 10:29:40 +01:00
import { instanceToPlain, plainToClass } from 'class-transformer';
2022-03-12 20:15:48 +01:00
import { JwtDataDto } from 'picsur-shared/dist/dto/jwt.dto';
2022-03-19 21:34:33 +01:00
import { strictValidate } from 'picsur-shared/dist/util/validate';
2022-03-07 20:19:58 +01:00
import { EUserBackend } from '../../models/entities/user.entity';
2022-02-21 14:53:21 +01:00
@Injectable()
2022-03-07 20:19:58 +01:00
export class AuthManagerService {
2022-02-26 18:16:28 +01:00
private readonly logger = new Logger('AuthService');
2022-03-12 15:10:22 +01:00
constructor(private jwtService: JwtService) {}
2022-02-21 14:53:21 +01:00
2022-03-01 22:05:59 +01:00
async createToken(user: EUserBackend): Promise<string> {
2022-02-26 18:16:28 +01:00
const jwtData: JwtDataDto = plainToClass(JwtDataDto, {
2022-03-21 23:23:32 +01:00
user: {
username: user.username,
roles: user.roles,
},
2022-02-26 18:16:28 +01:00
});
2022-03-19 21:34:33 +01:00
const errors = await strictValidate(jwtData);
2022-02-26 18:16:28 +01:00
if (errors.length > 0) {
this.logger.warn(errors);
throw new Error('Invalid jwt token generated');
}
2022-02-21 14:53:21 +01:00
2022-02-28 10:29:40 +01:00
return this.jwtService.signAsync(instanceToPlain(jwtData));
2022-02-21 14:53:21 +01:00
}
}