auth.service.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { BadRequestException, Injectable } from '@nestjs/common'
  2. import { JwtService } from '@nestjs/jwt'
  3. import { auth } 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.auth.create({
  14. data: {
  15. username: dto.name,
  16. password: paw,
  17. email: dto.emali,
  18. },
  19. })
  20. delete user.password
  21. const token = await this.token(user)
  22. return { cod: 200, msg: '注册成功', token }
  23. }
  24. async login(dto: LoginDto) {
  25. const user = await this.prisma.auth.findUnique({
  26. where: {
  27. username: dto.name,
  28. },
  29. })
  30. if (!user) {
  31. throw new BadRequestException('用户名错误')
  32. }
  33. if (!(await verify(user.password, dto.paw))) {
  34. throw new BadRequestException('密码错误')
  35. }
  36. delete user.password
  37. const token = await this.token(user)
  38. return { cod: 200, msg: '登陆成功', token }
  39. }
  40. async token({ auth_id, username }: auth) {
  41. const token = await this.jwt.signAsync({
  42. username,
  43. sub: auth_id,
  44. })
  45. return token
  46. }
  47. }