Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication service/tests #39

Merged
merged 7 commits into from
Oct 19, 2023
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
9 changes: 9 additions & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,18 @@
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.1.1",
"@nestjs/passport": "^10.0.2",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.1.8",
"@prisma/client": "5.2.0",
"@trpc/server": "^10.38.0",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"passport": "^0.6.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"prisma": "^5.2.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
Expand All @@ -41,12 +46,16 @@
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/jwt": "^10.1.1",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/bcrypt": "^5.0.0",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.8.2",
"@types/passport-jwt": "^3.0.10",
"@types/passport-local": "^1.0.36",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^6.4.1",
"@typescript-eslint/parser": "^6.4.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- A unique constraint covering the columns `[email]` on the table `Employee` will be added. If there are existing duplicate values, this will fail.

*/
-- CreateIndex
CREATE UNIQUE INDEX "Employee_email_key" ON "Employee"("email");
2 changes: 1 addition & 1 deletion apps/server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ model Employee {
id String @id @default(uuid()) @db.Uuid
firstName String @db.VarChar(255)
lastName String @db.VarChar(255)
email String @db.VarChar(255)
email String @db.VarChar(255) @unique
pswdHash String? @db.VarChar(255)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
10 changes: 5 additions & 5 deletions apps/server/prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,28 +199,28 @@ async function main() {
id: '777c1974-3104-4744-ae31-7a9296e7784a',
firstName: 'Helen',
lastName: 'Miao',
email: 'email@gmail.com',
email: 'email1@gmail.com',
positionId: CHIEF_OF_STAFF_UUID,
},
{
id: '339cf78e-d13f-4069-b1f7-dee0c64afb31',
firstName: 'Kai',
lastName: 'Zheng',
email: 'email@gmail.com',
email: 'email2@gmail.com',
positionId: CHIEF_FIN_OFFICER_UUID,
},
{
id: 'c6de4017-cb1f-44f1-a707-0f38239e0bca',
firstName: 'Iris',
lastName: 'Zhang',
email: 'email@gmail.com',
email: 'email3@gmail.com',
positionId: AGG_DIR_UUID,
},
{
id: 'b386ef53-d2d1-4bfd-a44c-55b1750a874e',
firstName: 'Anshul',
lastName: 'Shirude',
email: 'email@gmail.com',
email: 'email4@gmail.com',
positionId: CHIEF_LEARNING_ENGAGEMENT_UUID,
},
];
Expand Down Expand Up @@ -262,4 +262,4 @@ main()
console.log('Signature Fields:', allSignatureFields);

await prisma.$disconnect();
});
});
12 changes: 11 additions & 1 deletion apps/server/src/app.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthService } from './auth/auth.service';
import { EmployeesService } from './employees/employees.service';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from './prisma/prisma.service';

describe('AppController', () => {
let appController: AppController;

beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
providers: [
AppService,
AuthService,
EmployeesService,
JwtService,
PrismaService,
],
}).compile();

appController = app.get<AppController>(AppController);
Expand Down
43 changes: 41 additions & 2 deletions apps/server/src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,51 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Post, UseGuards, Request } from '@nestjs/common';
import { AppService } from './app.service';
import {
ApiOkResponse,
ApiForbiddenResponse,
ApiUnprocessableEntityResponse,
ApiBadRequestResponse,
ApiBody,
ApiBearerAuth,
} from '@nestjs/swagger';
import { AppErrorMessage } from './app.errors';
import { JwtEntity } from './auth/entities/jwt.entity';
import { LocalAuthGuard } from './auth/guards/local-auth.guard';
import { EmployeeEntity } from './employees/entities/employee.entity';
import { AuthService } from './auth/auth.service';
import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
constructor(
private appService: AppService,
private authService: AuthService,
) {}

@UseGuards(JwtAuthGuard)
@Get()
@ApiBearerAuth()
getHello(): string {
return this.appService.getHello();
}

@UseGuards(LocalAuthGuard)
@Post('auth/login')
@ApiOkResponse({ type: JwtEntity })
@ApiForbiddenResponse({ description: AppErrorMessage.FORBIDDEN })
@ApiUnprocessableEntityResponse({
description: AppErrorMessage.UNPROCESSABLE_ENTITY,
})
@ApiBadRequestResponse({ description: AppErrorMessage.UNPROCESSABLE_ENTITY })
@ApiBody({
schema: {
properties: {
username: { type: 'string' },
password: { type: 'string' },
},
},
})
async login(@Request() req: EmployeeEntity) {
return this.authService.login(req);
}
}
18 changes: 17 additions & 1 deletion apps/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { FormInstancesModule } from './form-instances/form-instances.module';
import { FormTemplatesModule } from './form-templates/form-templates.module';
import { DepartmentsModule } from './departments/departments.module';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';

@Module({
imports: [
Expand All @@ -24,8 +27,21 @@ import { ConfigModule } from '@nestjs/config';
ConfigModule.forRoot({
envFilePath: '.env',
}),
AuthModule,
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does secret mean?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's what's used to generate the jwt token and decode it

signOptions: { expiresIn: `${process.env.JWT_VALID_DURATION}s` },
}),
],
controllers: [AppController],
providers: [AppService],
providers: [
AppService,

// {
// provide: APP_GUARD,
// useClass: JwtAuthGuard,
// },
],
})
export class AppModule {}
21 changes: 21 additions & 0 deletions apps/server/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { EmployeesModule } from '../employees/employees.module';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './strategies/local.strategy';
import { JwtStrategy } from './strategies/jwt.strategy';

@Module({
imports: [
EmployeesModule,
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: `${process.env.JWT_VALID_DURATION}s` },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
144 changes: 144 additions & 0 deletions apps/server/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { EmployeesService } from '../employees/employees.service';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import { EmployeeEntity } from '../employees/entities/employee.entity';

describe('AuthService', () => {
let service: AuthService;
let employeeService: EmployeesService;
let jwtService: JwtService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService, EmployeesService, PrismaService, JwtService],
}).compile();

service = module.get<AuthService>(AuthService);
employeeService = module.get<EmployeesService>(EmployeesService);
jwtService = module.get<JwtService>(JwtService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('validateEmployee', () => {
const email = 'email1@gmail.com';
const password = 'password';
const employeeId = 'employeeId';
const employee = {
id: employeeId,
firstName: 'First',
lastName: 'Last',
positionId: 'positionId',
position: {
id: 'positionId',
name: 'Manager',
single: true,
departmentId: 'departmentId',
department: {
id: 'departmentId',
name: 'Archives',
createdAt: new Date(1672531200),
updatedAt: new Date(1672531200),
},
createdAt: new Date(1672531200),
updatedAt: new Date(1672531200),
},
email: 'info@mfa.org',
pswdHash: 'password',
createdAt: new Date(1672531200),
updatedAt: new Date(1672531200),
};

it('should sucessfully validate credentials', async () => {
const expected = new EmployeeEntity({
id: employeeId,
firstName: 'First',
lastName: 'Last',
positionId: 'positionId',
position: {
id: 'positionId',
name: 'Manager',
single: true,
departmentId: 'departmentId',
department: {
id: 'departmentId',
name: 'Archives',
createdAt: new Date(1672531200),
updatedAt: new Date(1672531200),
},
createdAt: new Date(1672531200),
updatedAt: new Date(1672531200),
},
email: 'info@mfa.org',
createdAt: new Date(1672531200),
updatedAt: new Date(1672531200),
});

jest.spyOn(bcrypt, 'compare').mockImplementation(async () => {
return true;
});
jest.spyOn(employeeService, 'findOneByEmail').mockResolvedValue(employee);

const result = await service.validateEmployee(email, password);
expect(result).toEqual(expected);
});

it('should return null on invalid credentials', async () => {
jest.spyOn(bcrypt, 'compare').mockImplementation(async () => {
return false;
});
jest.spyOn(employeeService, 'findOneByEmail').mockResolvedValue(employee);

const result = await service.validateEmployee(email, password);
expect(result).toBeNull();
});
});

describe('login', () => {
const originalEnv = process.env;
const jwtSecret =
'6f4f04c51b3a6eca490347b9ae450b709f5ae40d4bd1c1003f95bf837a6e5e13';
const validDuration = '600';

beforeEach(() => {
jest.resetModules();
process.env = {
...originalEnv,
JWT_SECRET: jwtSecret,
JWT_VALID_DURATION: validDuration,
};
});

afterEach(() => {
process.env = originalEnv;
});

it('successfully creates a JWT token', async () => {
const request = {
user: {
email: 'email@gmail.com',
id: 'userId',
},
};
const result = await service.login(request);
const decoded = await jwtService.decode(result.access_token);

expect(decoded).not.toBeNull();

const decodedObj = decoded as {
[key: string]: any;
};

expect(decodedObj.email).toEqual(request.user.email);
expect(decodedObj.sub).toEqual(request.user.id);
expect((decodedObj.exp - decodedObj.iat).toString()).toEqual(
process.env.JWT_VALID_DURATION,
);
});
});
});
Loading