auth.service.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { Injectable } from '@nestjs/common';
  2. import { UserService } from '../user/user.service';
  3. import { JwtService } from '@nestjs/jwt';
  4. import { User } from '../user/user.entity';
  5. import { SafeUser } from '../user/dto/user-safe.dto';
  6. @Injectable()
  7. export class AuthService {
  8. constructor(
  9. private userService: UserService,
  10. private jwtService: JwtService,
  11. ) { }
  12. async validateUser(username: string, pass: string): Promise<User | null> {
  13. const user = await this.userService.findOneByUsername(username);
  14. if (user && (await user.validatePassword(pass))) {
  15. return user;
  16. }
  17. return null;
  18. }
  19. async login(user: SafeUser) {
  20. const payload = {
  21. username: user.username,
  22. sub: user.id,
  23. role: user.role,
  24. tenantId: user.tenantId
  25. };
  26. return {
  27. access_token: this.jwtService.sign(payload),
  28. user: {
  29. id: user.id,
  30. username: user.username,
  31. role: user.role,
  32. tenantId: user.tenantId,
  33. displayName: user.displayName
  34. }
  35. };
  36. }
  37. async getOrCreateApiKey(userId: string) {
  38. return this.userService.getOrCreateApiKey(userId);
  39. }
  40. async regenerateApiKey(userId: string) {
  41. return this.userService.regenerateApiKey(userId);
  42. }
  43. }