-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f5bc8a2
basic auth framework
elvincheng3 be52a3b
add testing
elvincheng3 11ced20
bump deps
elvincheng3 a503e59
gen client
elvincheng3 dfdb307
Revert "bump deps"
elvincheng3 cc939e5
remove import
elvincheng3 013beb8
fix build
elvincheng3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 8 additions & 0 deletions
8
apps/server/prisma/migrations/20231017004422_unique_email_constraint/migration.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What does secret mean?
There was a problem hiding this comment.
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