auth.service.ts 1.5 KB

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