Skip to content
Open
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
62 changes: 60 additions & 2 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@
"@nestjs/jwt": "^8.0.0",
"@nestjs/passport": "^8.0.0",
"@nestjs/platform-express": "^8.4.7",
"aws-jwt-verify": "^5.1.1",
"aws-sdk": "^2.1030.0",
"aws-serverless-express": "^3.4.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"cookie-parser": "^1.4.7",
"crypto": "^1.0.1",
"dotenv": "^16.4.5",
"jwt-decode": "^4.0.0",
Expand All @@ -32,6 +34,7 @@
"@nestjs/testing": "^8.4.7",
"@types/aws-lambda": "^8.10.149",
"@types/aws-serverless-express": "^3.3.10",
"@types/cookie-parser": "^1.4.10",
"@types/jest": "^27.0.0",
"@types/node": "^20.0.0",
"esbuild": "^0.25.2",
Expand Down
22 changes: 18 additions & 4 deletions backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Controller, Post, Body } from '@nestjs/common';
import { Controller, Post, Body, Res } from '@nestjs/common';
import { AuthService } from './auth.service';
import { User } from '../types/User';
import { Response } from 'express';
import { UserStatus } from '../../../middle-layer/types/UserStatus';

@Controller('auth')
Expand All @@ -19,18 +20,31 @@ export class AuthController {

@Post('login')
async login(
@Res({ passthrough: true }) response: Response,
@Body('username') username: string,
@Body('password') password: string,
@Body('password') password: string,
): Promise<{
access_token?: string;
user: User;
session?: string;
challenge?: string;
requiredAttributes?: string[];
username?: string;
position?: string;
}> {
return await this.authService.login(username, password);
const result = await this.authService.login(username, password);

// Set cookie with access token
if (result.access_token) {
response.cookie('access_token', result.access_token, {
httpOnly: true, // Cannot be accessed by JavaScript (XSS protection)
secure: process.env.NODE_ENV === 'production', // Only HTTPS in production
sameSite: 'strict', // CSRF protection
maxAge: 3600000, // 1 hour in milliseconds
path: '/', // Cookie available on all routes
});
}
delete result.access_token;
return result
}

@Post('set-password')
Expand Down
76 changes: 76 additions & 0 deletions backend/src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
import { Observable } from "rxjs";
import { CognitoJwtVerifier } from "aws-jwt-verify";




@Injectable()
export class VerifyUserGuard implements CanActivate {
private verifier: any;
constructor() {
const userPoolId = process.env.COGNITO_USER_POOL_ID;
if (userPoolId) {
this.verifier = CognitoJwtVerifier.create({
userPoolId,
tokenUse: "access",
clientId: process.env.COGNITO_CLIENT_ID,
});
} else {
throw new Error(

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > updateGrant() > should update the correct grant and return a stringified JSON with the updated grant

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > makeGrantsInactive() > should inactivate multiple grants and return the updated grant objects

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > getGrantById() > should throw an error if given an invalid id

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > getGrantById() > should return the correct grant given a valid id

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > getAllGrants() > should throw an error if there is an issue retrieving the grants

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > getAllGrants() > should return an empty list of grants if no grants exist in the database

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > getAllGrants() > should return a populated list of grants

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13

Check failure on line 20 in backend/src/auth/auth.guard.ts

View workflow job for this annotation

GitHub Actions / build

src/grant/__test__/grant.service.spec.ts > GrantService > should be defined

Error: [AUTH] USER POOL ID is not defined in environment variables ❯ new VerifyUserGuard src/auth/auth.guard.ts:20:13 ❯ TestingInjector.instantiateClass node_modules/@nestjs/core/injector/injector.js:330:19 ❯ callback node_modules/@nestjs/core/injector/injector.js:48:41 ❯ TestingInjector.resolveConstructorParams node_modules/@nestjs/core/injector/injector.js:122:24 ❯ TestingInjector.loadInstance node_modules/@nestjs/core/injector/injector.js:52:9 ❯ TestingInjector.loadInjectable node_modules/@nestjs/core/injector/injector.js:70:9 ❯ TestingInstanceLoader.createInstancesOfInjectables node_modules/@nestjs/core/injector/instance-loader.js:62:9 ❯ node_modules/@nestjs/core/injector/instance-loader.js:30:13
"[AUTH] USER POOL ID is not defined in environment variables"
);
}
}

async canActivate(context: ExecutionContext): Promise<boolean> {
try {
const request = context.switchToHttp().getRequest();
const accessToken = request.cookies["access_token"];
const result = await this.verifier.verify(accessToken);

return true;
} catch (error) {
console.error("Token verification failed:", error); // Debug log
return false;
}
}
}

@Injectable()
export class VerifyAdminRoleGuard implements CanActivate {
private verifier: any;
constructor() {
const userPoolId = process.env.COGNITO_USER_POOL_ID;
if (userPoolId) {
this.verifier = CognitoJwtVerifier.create({
userPoolId,
tokenUse: "access",
clientId: process.env.COGNITO_CLIENT_ID,
});
} else {
throw new Error(
"[AUTH] USER POOL ID is not defined in environment variables"
);
}
}
async canActivate(context: ExecutionContext): Promise<boolean> {
try {
const request = context.switchToHttp().getRequest();
const accessToken = request.cookies["access_token"];
const result = await this.verifier.verify(accessToken);
const groups = result['cognito:groups'] || [];
console.log("User groups from token:", groups);
if (!groups.includes('Admin')) {
console.warn("Access denied: User is not an Admin");
return false;
} else {
return true;
}

} catch (error) {
console.error("Token verification failed:", error); // Debug log
return false;
}
}
}
4 changes: 2 additions & 2 deletions backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ private isValidEmail(email: string): boolean {

if (!accessToken) {
throw new Error("Access token is undefined.");
}
}

const getUserResponse = await this.cognito
.getUser({ AccessToken: accessToken })
Expand Down Expand Up @@ -403,7 +403,7 @@ private isValidEmail(email: string): boolean {
user = newUser;
}

return { access_token: idToken, user, message: "Login Successful!" };
return { access_token: accessToken, user, message: "Login Successful!" };
} catch (error: unknown) {
/* Login Failures */
const cognitoError = error as AwsCognitoError;
Expand Down
Loading
Loading