Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"start:dev": "node ../contracts/sync.mjs && nest start --watch",
"start:debug": "node ../contracts/sync.mjs && nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
Expand Down
121 changes: 111 additions & 10 deletions backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import {
Body,
Controller,
Post,
Delete,
Get,
Header,
Param,
ParseUUIDPipe,
Patch,
Post,
Req,
Res,
UseGuards,
Expand All @@ -16,10 +20,17 @@ import { Request, Response } from 'express';
import { Profile as GoogleProfile } from 'passport-google-oauth20';
import { Profile as GithubProfile } from 'passport-github2';

import { AuthService } from './auth.service';
import { AuthService, SessionContext } from './auth.service';
import { TwoFactorService } from './two-factor.service';
import { RegisterAuthDto } from './dto/register-auth.dto';
import { LoginAuthDto } from './dto/login-auth.dto';
import { RefreshAuthDto } from './dto/refresh-auth.dto';
import {
ChangePasswordDto,
DisableTwoFactorDto,
TwoFactorChallengeDto,
TwoFactorCodeDto,
} from './dto/two-factor.dto';
import {
getFrontendUrl,
isAllowedFrontendOrigin,
Expand All @@ -40,6 +51,7 @@ import { LoginRateLimitGuard } from './login-rate-limit.guard';
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly twoFactorService: TwoFactorService,
private readonly configService: ConfigService,
) {}

Expand All @@ -50,7 +62,10 @@ export class AuthController {
@Req() request?: Request,
) {
this.assertTrustedBrowserRequest(request);
const tokens = await this.authService.register(dto);
const tokens = await this.authService.register(
dto,
this.getSessionContext(request),
);
setAuthCookies(response, tokens, this.configService);
return tokens;
}
Expand All @@ -63,9 +78,15 @@ export class AuthController {
@Req() request?: Request,
) {
this.assertTrustedBrowserRequest(request);
const tokens = await this.authService.login(dto);
setAuthCookies(response, tokens, this.configService);
return tokens;
const result = await this.authService.login(
dto,
this.getSessionContext(request),
);

if ('access_token' in result) {
setAuthCookies(response, result, this.configService);
}
return result;
}

@Post('refresh')
Expand All @@ -79,9 +100,12 @@ export class AuthController {
request.headers.cookie,
REFRESH_COOKIE_NAME,
);
const tokens = await this.authService.refreshToken({
refreshToken: cookieRefreshToken ?? dto?.refreshToken,
});
const tokens = await this.authService.refreshToken(
{
refreshToken: cookieRefreshToken ?? dto?.refreshToken,
},
this.getSessionContext(request),
);
setAuthCookies(response, tokens, this.configService);
return tokens;
}
Expand Down Expand Up @@ -131,6 +155,74 @@ export class AuthController {
};
}

@Get('sessions')
@UseGuards(JwtAuthGuard)
listSessions(@Req() request: Request & { user?: User }) {
return this.authService.listSessions(request.user!.id);
}

@Delete('sessions/:id')
@UseGuards(JwtAuthGuard)
revokeSession(
@Req() request: Request & { user?: User },
@Param('id', ParseUUIDPipe) id: string,
) {
return this.authService.revokeSession(request.user!.id, id);
}

@Patch('change-password')
@UseGuards(JwtAuthGuard)
changePassword(
@Req() request: Request & { user?: User },
@Body() dto: ChangePasswordDto,
) {
return this.authService.changePassword(
request.user!.id,
dto.currentPassword,
dto.newPassword,
);
}

@Post('2fa/setup')
@UseGuards(JwtAuthGuard)
setupTwoFactor(@Req() request: Request & { user?: User }) {
return this.twoFactorService.setup(request.user!);
}

@Post('2fa/verify')
@UseGuards(JwtAuthGuard)
verifyTwoFactor(
@Req() request: Request & { user?: User },
@Body() dto: TwoFactorCodeDto,
) {
return this.twoFactorService.confirm(request.user!.id, dto.code);
}

@Post('2fa/challenge')
async challengeTwoFactor(
@Body() dto: TwoFactorChallengeDto,
@Req() request: Request,
@Res({ passthrough: true }) response?: Response,
) {
this.assertTrustedBrowserRequest(request);
const tokens = await this.authService.completeTwoFactorLogin(
dto.twoFactorToken,
dto.code,
this.getSessionContext(request),
);
setAuthCookies(response, tokens, this.configService);
return tokens;
}

@Post('2fa/disable')
@UseGuards(JwtAuthGuard)
disableTwoFactor(
@Req() request: Request & { user?: User },
@Body() dto: DisableTwoFactorDto,
) {
return this.twoFactorService.disable(request.user!.id, dto.password);
}

@Get('google')
@UseGuards(AuthGuard('google'))
googleAuth() {
Expand Down Expand Up @@ -160,6 +252,7 @@ export class AuthController {
const tokens = await this.authService.handleOAuthLogin(
email,
fullName || email,
this.getSessionContext(req),
);

return this.redirectWithCookies(tokens, res);
Expand Down Expand Up @@ -194,6 +287,7 @@ export class AuthController {
const tokens = await this.authService.handleOAuthLogin(
identifier,
fullName,
this.getSessionContext(req),
);

return this.redirectWithCookies(tokens, res);
Expand All @@ -202,7 +296,7 @@ export class AuthController {
private redirectWithCookies(tokens: AuthTokens, res: Response) {
setAuthCookies(res, tokens, this.configService);
const redirectUrl = new URL(getFrontendUrl(this.configService));
const basePath = redirectUrl.pathname.replace(/\/+$/, "");
const basePath = redirectUrl.pathname.replace(/\/+$/, '');
redirectUrl.pathname = `${basePath}/auth/oauth/callback`;
redirectUrl.search = '';
redirectUrl.hash = new URLSearchParams({
Expand All @@ -211,6 +305,13 @@ export class AuthController {
return res.redirect(redirectUrl.toString());
}

private getSessionContext(request?: Request): SessionContext {
return {
userAgent: request?.headers['user-agent'],
ipAddress: request?.ip,
};
}

private assertTrustedBrowserRequest(request?: Request): void {
if (!request) return;

Expand Down
12 changes: 11 additions & 1 deletion backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';

import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TwoFactorService } from './two-factor.service';
import { RefreshSession } from './entities/refresh-session.entity';
import { UsersModule } from '../users/users.module';
import { JwtStrategy } from './strategies/jwt.strategy';
import { GoogleStrategy } from './strategies/google.strategy';
Expand All @@ -13,6 +16,7 @@ import { GithubStrategy } from './strategies/github.strategy';
@Module({
imports: [
UsersModule,
TypeOrmModule.forFeature([RefreshSession]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
Expand All @@ -27,7 +31,13 @@ import { GithubStrategy } from './strategies/github.strategy';
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, GoogleStrategy, GithubStrategy],
providers: [
AuthService,
TwoFactorService,
JwtStrategy,
GoogleStrategy,
GithubStrategy,
],
exports: [AuthService, JwtModule, PassportModule],
})
export class AuthModule {}
Loading
Loading