Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

Enable Password Hashing in Registration #239

Merged
merged 4 commits into from
Jun 18, 2024
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
24 changes: 12 additions & 12 deletions backend/src/api/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,13 @@ import { AutoGuard } from '../../auth/auto.guard';
import { PatchUserDTO } from './patch.user.dto';
import { RegisterUserDTO } from './register.user.dto';
import { AuthService } from '../../auth/auth.service';
import { UserRepository } from '../../db/repositories/user.repository';
import { NestRequest } from '../../types/request.type';

type SanitizedUser = Omit<User, 'password'>;

@Controller('user')
export class UserController {
constructor(
private authService: AuthService,
private userRepository: UserRepository,
) {}
constructor(private authService: AuthService) {}

_sanitizeUser(user: User): SanitizedUser {
const sanitizedUser: SanitizedUser & { password?: string } = user;
Expand All @@ -34,13 +30,20 @@ export class UserController {
}

@Post('/')
async postRegister(@Body() userPatch: RegisterUserDTO) {
this.userRepository.createUser(
async postRegister(@Body() userPatch: RegisterUserDTO, @Res() res: Response) {
const user = await this.authService.createUser(
userPatch.email,
userPatch.displayName,
userPatch.password,
false,
);

if (user) {
return res.status(201).json({ status: 'Registration was successfull' });
} else {
return res
.status(500)
.json({ status: 'Registration was not successfull' });
}
}

/**
Expand Down Expand Up @@ -84,10 +87,7 @@ export class UserController {
}

if (Object.keys(userChanges).length > 0) {
const user = await this.userRepository.updateUser(
req.user.id,
userChanges,
);
const user = await this.authService.updateUser(req.user.id, userChanges);

res.status(200).json(this._sanitizeUser(user));
} else {
Expand Down
21 changes: 21 additions & 0 deletions backend/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { DeepMockProxy, mockDeep } from 'jest-mock-extended';
import { hashSync } from 'bcrypt';
import { PrismaClient } from '@prisma/client';
import { UserRepository } from '../db/repositories/user.repository';
import { TestConstants } from '../../test/lib/constants';

describe('AuthService', () => {
let service: AuthService;
Expand Down Expand Up @@ -58,4 +59,24 @@ describe('AuthService', () => {
await service.validateUserPassword('[email protected]', 'incorrect'),
).toBeNull();
});

it('should be able to create a user and hash the password', async () => {
jest
.spyOn(service, 'hashPassword')
.mockImplementation(async () => 'HASHED');

userRepository.createUser.mockResolvedValue(
TestConstants.database.users.exampleUser,
);

const result = await service.createUser('MOCKED', 'MOCKED', 'MOCKED');

expect(result).toStrictEqual(TestConstants.database.users.exampleUser);
expect(userRepository.createUser).toHaveBeenCalledWith(
'MOCKED',
'MOCKED',
'HASHED',
false,
);
});
});
29 changes: 28 additions & 1 deletion backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@nestjs/common';
import { User } from '@prisma/client';
import { Prisma, User } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { UserRepository } from '../db/repositories/user.repository';

Expand Down Expand Up @@ -40,4 +40,31 @@ export class AuthService {
async hashPassword(password: string): Promise<string> {
return await bcrypt.hash(password, 12);
}

/**
* Creates a new user
*
* @param email
* @param displayName
* @param password Plain text password, will be hashed before creation
* @returns Created User
*/
async createUser(
email: string,
displayName: string,
password: string,
): Promise<User> {
const hashedPassword = await this.hashPassword(password);

return await this.userRepository.createUser(
email,
displayName,
hashedPassword,
false,
);
}

async updateUser(userId, data: Prisma.UserUpdateInput) {
return await this.userRepository.updateUser(userId, data);
}
}
Loading