API authentifiée
This commit is contained in:
27
server/src/auth/auth.service.ts
Normal file
27
server/src/auth/auth.service.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common'
|
||||
import { PrismaService } from './../prisma/prisma.service'
|
||||
import { JwtService } from '@nestjs/jwt'
|
||||
import { AuthEntity } from './entity/auth.entity'
|
||||
import * as bcrypt from 'bcrypt'
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(private prisma: PrismaService, private jwtService: JwtService) {}
|
||||
|
||||
async login(name: string, password: string): Promise<AuthEntity> {
|
||||
const user = await this.prisma.user.findUnique({ where: { name: name } })
|
||||
if (!user) {
|
||||
throw new NotFoundException(`Aucun⋅e utilisateur⋅rice avec pour nom ${name}`)
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(password, user.password)
|
||||
|
||||
if (!isPasswordValid) {
|
||||
throw new UnauthorizedException('Mot de passe incorrect')
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken: this.jwtService.sign({ userId: user.id }),
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user