auth.service.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { BadRequestException, Injectable } from '@nestjs/common'
  2. import { JwtService } from '@nestjs/jwt'
  3. import { user } from '@prisma/client'
  4. import { hash, verify } from 'argon2'
  5. import { PrismaService } from 'src/prisma/prisma.service'
  6. import LoginDto from './dto/login.dto'
  7. import registerDto from './dto/register.dto'
  8. @Injectable()
  9. export class AuthService {
  10. constructor(private prisma: PrismaService, private jwt: JwtService) {}
  11. async register(dto: registerDto) {
  12. const paw = await hash(dto.paw)
  13. const user = await this.prisma.user.create({
  14. data: {
  15. username: dto.name,
  16. password: paw,
  17. email: dto.emali,
  18. },
  19. })
  20. delete user.password
  21. return this.token(user)
  22. }
  23. async login(dto: LoginDto) {
  24. const user = await this.prisma.user.findUnique({
  25. where: {
  26. username: dto.name,
  27. },
  28. })
  29. if (!user) {
  30. throw new BadRequestException('用户名错误')
  31. }
  32. if (!verify(user.password, dto.paw)) {
  33. throw new BadRequestException('密码错误')
  34. }
  35. delete user.password
  36. const token = await this.token(user)
  37. return { ...user, token }
  38. }
  39. async token({ username, id }: user) {
  40. return {
  41. token: await this.jwt.signAsync({
  42. username,
  43. sub: id,
  44. }),
  45. }
  46. }
  47. }