feat: Auth module

This commit is contained in:
Mathis H (Avnyr) 2024-02-27 16:45:22 +01:00
parent 73ee4e2894
commit 577d96d68c
Signed by: Mathis
GPG Key ID: 9B3849C18C153DDD
2 changed files with 59 additions and 18 deletions

View File

@ -4,17 +4,15 @@ import { AuthDto } from "./dto";
@Controller('auth') @Controller('auth')
export class AuthController { export class AuthController {
constructor(private authService: AuthService) {} constructor(private authService: AuthService) {}
@Post('signup') @Post("register")
signup(@Body() dto: AuthDto) { async signup(@Body() dto: AuthDto) {
console.log({dto}); return await this.authService.register(dto);
return this.authService.signup() }
}
@Post('signin') @Post("login")
signin(@Body() dto: AuthDto) { async signin(@Body() dto: AuthDto) {
console.log({dto}); return await this.authService.login(dto);
return this.authService.signin() }
}
} }

View File

@ -1,17 +1,60 @@
import { Injectable } from "@nestjs/common"; import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from "src/prisma/prisma.service"; import { PrismaService } from "src/prisma/prisma.service";
import { AuthDto } from "./dto";
import * as argon from "argon2";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
@Injectable({}) @Injectable({})
export class AuthService { 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() { const pwMatches = await argon.verify(User.hash, dto.password);
return {response: "Sign IN"} if (!pwMatches) {
console.warn(
`ACCESS: Refused login for "${dto.email}" (invalid password)`,
);
throw new ForbiddenException("Credential(s) invalid.");
} }
signup() { delete User.hash;
return {response: "Sign UP"} 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.");
}
}
} }
}
} }