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

32 lines
932 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-04-04 10:36:59 +02:00
import { JwtDataSchema } from 'picsur-shared/dist/dto/jwt.dto';
import { EUser } from 'picsur-shared/dist/entities/user.entity';
2022-03-28 15:43:52 +02:00
import { AsyncFailable, Fail } from 'picsur-shared/dist/types';
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-06-27 17:37:37 +02:00
constructor(private readonly jwtService: JwtService) {}
2022-02-21 14:53:21 +01:00
2022-04-04 10:36:59 +02:00
async createToken(user: EUser): AsyncFailable<string> {
const jwtData = {
2022-04-01 12:04:49 +02:00
user,
2022-04-04 10:36:59 +02:00
};
2022-02-26 18:16:28 +01:00
2022-03-28 13:44:33 +02:00
// Validate to be sure, this makes client experience better
// in case of any failures
2022-04-04 10:36:59 +02:00
const result = JwtDataSchema.safeParse(jwtData);
if (!result.success) {
return Fail('Invalid JWT: ' + result.error);
2022-02-26 18:16:28 +01:00
}
2022-02-21 14:53:21 +01:00
2022-03-28 15:43:52 +02:00
try {
2022-04-04 10:36:59 +02:00
return await this.jwtService.signAsync(result.data);
2022-03-28 15:43:52 +02:00
} catch (e) {
return Fail("Couldn't create JWT: " + e);
}
2022-02-21 14:53:21 +01:00
}
}