auth.service.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import * as jwt from 'jsonwebtoken';
  2. import { Injectable, UnauthorizedException } from "@nestjs/common";
  3. import { JwtPayload } from "./auth-types";
  4. import { Role } from "./role";
  5. import { PasswordService } from "./password.service";
  6. import { Connection } from "typeorm";
  7. import { InjectConnection } from "@nestjs/typeorm";
  8. import { UserEntity } from "../entity/user/user.entity";
  9. // TODO: make this configurable e.g. from environment
  10. export const JWT_SECRET = 'some_secret';
  11. @Injectable()
  12. export class AuthService {
  13. constructor(private passwordService: PasswordService,
  14. @InjectConnection() private connection: Connection) {}
  15. async createToken(identifier: string, password: string): Promise<{ user: UserEntity; token: string; }> {
  16. const user = await this.connection.getRepository(UserEntity)
  17. .findOne({
  18. where: {
  19. identifier
  20. }
  21. });
  22. if (!user) {
  23. throw new UnauthorizedException();
  24. }
  25. const passwordMatches = await this.passwordService.check(password, user.passwordHash);
  26. if (!passwordMatches) {
  27. throw new UnauthorizedException();
  28. }
  29. const payload: JwtPayload = { identifier , roles: user.roles };
  30. const token = jwt.sign(payload, JWT_SECRET, { expiresIn: 3600 });
  31. return { user, token };
  32. }
  33. async validateUser(payload: JwtPayload): Promise<any> {
  34. return await this.connection.getRepository(UserEntity).findOne({
  35. where: {
  36. identifier: payload.identifier
  37. }
  38. });
  39. }
  40. }