Skip to content

Commit

Permalink
feat: add logs for successful registration, successful login and fail…
Browse files Browse the repository at this point in the history
…ed login
  • Loading branch information
stonith404 committed Jul 10, 2024
1 parent 9d9cc7b commit d2bfb9a
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 15 deletions.
6 changes: 4 additions & 2 deletions backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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(
Expand Down
14 changes: 11 additions & 3 deletions backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
BadRequestException,
ForbiddenException,
Injectable,
Logger,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
Expand All @@ -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;
Expand All @@ -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) {
Expand All @@ -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");

Expand All @@ -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);
}

Expand Down
2 changes: 1 addition & 1 deletion backend/src/oauth/oauth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class OAuthController {
accessToken?: string;
refreshToken?: string;
loginToken?: string;
} = await this.oauthService.signIn(user);
} = await this.oauthService.signIn(user, request.ip);
if (token.accessToken) {
this.authService.addTokensToResponse(
response,
Expand Down
23 changes: 14 additions & 9 deletions backend/src/oauth/oauth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Inject, Injectable } from "@nestjs/common";
import { Inject, Injectable, Logger } from "@nestjs/common";
import { User } from "@prisma/client";
import { nanoid } from "nanoid";
import { AuthService } from "../auth/auth.service";
Expand All @@ -15,6 +15,7 @@ export class OAuthService {
private auth: AuthService,
@Inject("OAUTH_PLATFORMS") private platforms: string[],
) {}
private readonly logger = new Logger(OAuthService.name);

available(): string[] {
return this.platforms
Expand All @@ -39,7 +40,7 @@ export class OAuthService {
return Object.fromEntries(oauthUsers.map((u) => [u.provider, u]));
}

async signIn(user: OAuthSignInDto) {
async signIn(user: OAuthSignInDto, ip: string) {
const oauthUser = await this.prisma.oAuthUser.findFirst({
where: {
provider: user.provider,
Expand All @@ -50,10 +51,11 @@ export class OAuthService {
},
});
if (oauthUser) {
this.logger.log(`Successful login for user ${user.email} from IP ${ip}`);
return this.auth.generateToken(oauthUser.user, true);
}

return this.signUp(user);
return this.signUp(user, ip);
}

async link(
Expand Down Expand Up @@ -119,7 +121,7 @@ export class OAuthService {
}
}

private async signUp(user: OAuthSignInDto) {
private async signUp(user: OAuthSignInDto, ip: string) {
// register
if (!this.config.get("oauth.allowRegistration")) {
throw new ErrorPageException("no_user", "/auth/signIn", [
Expand Down Expand Up @@ -151,11 +153,14 @@ export class OAuthService {
return this.auth.generateToken(existingUser, true);
}

const result = await this.auth.signUp({
email: user.email,
username: await this.getAvailableUsername(user.providerUsername),
password: null,
});
const result = await this.auth.signUp(
{
email: user.email,
username: await this.getAvailableUsername(user.providerUsername),
password: null,
},
ip,
);

await this.prisma.oAuthUser.create({
data: {
Expand Down

0 comments on commit d2bfb9a

Please sign in to comment.