feat: add logs for successful registration, successful login and failed login

This commit is contained in:
Elias Schneider
2024-07-10 18:39:47 +02:00
parent 9d9cc7b4ab
commit d2bfb9a55f
4 changed files with 30 additions and 15 deletions

View File

@@ -45,12 +45,13 @@ export class AuthController {
})
async signUp(
@Body() dto: AuthRegisterDTO,
@Req() { ip }: Request,
@Res({ passthrough: true }) response: Response,
) {
if (!this.config.get("share.allowRegistration"))
throw new ForbiddenException("Registration is not allowed");
const result = await this.authService.signUp(dto);
const result = await this.authService.signUp(dto, ip);
this.authService.addTokensToResponse(
response,
@@ -71,9 +72,10 @@ export class AuthController {
@HttpCode(200)
async signIn(
@Body() dto: AuthSignInDTO,
@Req() { ip }: Request,
@Res({ passthrough: true }) response: Response,
) {
const result = await this.authService.signIn(dto);
const result = await this.authService.signIn(dto, ip);
if (result.accessToken && result.refreshToken) {
this.authService.addTokensToResponse(

View File

@@ -2,6 +2,7 @@ import {
BadRequestException,
ForbiddenException,
Injectable,
Logger,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
@@ -24,8 +25,9 @@ export class AuthService {
private config: ConfigService,
private emailService: EmailService,
) {}
private readonly logger = new Logger(AuthService.name);
async signUp(dto: AuthRegisterDTO) {
async signUp(dto: AuthRegisterDTO, ip: string) {
const isFirstUser = (await this.prisma.user.count()) == 0;
const hash = dto.password ? await argon.hash(dto.password) : null;
@@ -44,6 +46,7 @@ export class AuthService {
);
const accessToken = await this.createAccessToken(user, refreshTokenId);
this.logger.log(`User ${user.email} signed up from IP ${ip}`);
return { accessToken, refreshToken, user };
} catch (e) {
if (e instanceof PrismaClientKnownRequestError) {
@@ -57,7 +60,7 @@ export class AuthService {
}
}
async signIn(dto: AuthSignInDTO) {
async signIn(dto: AuthSignInDTO, ip: string) {
if (!dto.email && !dto.username)
throw new BadRequestException("Email or username is required");
@@ -67,9 +70,14 @@ export class AuthService {
},
});
if (!user || !(await argon.verify(user.password, dto.password)))
if (!user || !(await argon.verify(user.password, dto.password))) {
this.logger.log(
`Failed login attempt for user ${dto.email} from IP ${ip}`,
);
throw new UnauthorizedException("Wrong email or password");
}
this.logger.log(`Successful login for user ${dto.email} from IP ${ip}`);
return this.generateToken(user);
}