diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index dde9817..d2ce91d 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -4,17 +4,15 @@ import { AuthDto } from "./dto"; @Controller('auth') export class AuthController { - constructor(private authService: AuthService) {} + constructor(private authService: AuthService) {} - @Post('signup') - signup(@Body() dto: AuthDto) { - console.log({dto}); - return this.authService.signup() - } + @Post("register") + async signup(@Body() dto: AuthDto) { + return await this.authService.register(dto); + } - @Post('signin') - signin(@Body() dto: AuthDto) { - console.log({dto}); - return this.authService.signin() - } + @Post("login") + async signin(@Body() dto: AuthDto) { + return await this.authService.login(dto); + } } \ No newline at end of file diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index ce94ba1..5eec152 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -1,17 +1,60 @@ -import { Injectable } from "@nestjs/common"; +import { ForbiddenException, Injectable } from "@nestjs/common"; import { PrismaService } from "src/prisma/prisma.service"; +import { AuthDto } from "./dto"; +import * as argon from "argon2"; +import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library"; @Injectable({}) export class AuthService { - constructor(private prisma: PrismaService) { - + constructor(private prisma: PrismaService) {} + + async login(dto: AuthDto) { + const User = await this.prisma.user.findUnique({ + where: { + email: dto.email, + }, + }); + if (!User) { + console.warn(`ACCESS: Refused login for "${dto.email}" (email not used)`); + throw new ForbiddenException("Credential(s) invalid."); } - signin() { - return {response: "Sign IN"} + const pwMatches = await argon.verify(User.hash, dto.password); + if (!pwMatches) { + console.warn( + `ACCESS: Refused login for "${dto.email}" (invalid password)`, + ); + throw new ForbiddenException("Credential(s) invalid."); } - signup() { - return {response: "Sign UP"} + delete User.hash; + console.info(`ACCESS: Granted login for "${dto.email}"`); + return User; + } + + async register(dto: AuthDto) { + const userPasswordHash = await argon.hash(dto.password); + try { + const User = await this.prisma.user.create({ + data: { + email: dto.email, + hash: userPasswordHash, + }, + select: { + id: true, + email: true, + firstName: true, + lastName: true, + }, + }); + //delete User.hash; + return User; + } catch (error) { + if (error instanceof PrismaClientKnownRequestError) { + if (error.code === "P2002") { + throw new ForbiddenException("Credential(s) taken."); + } + } } + } } \ No newline at end of file