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

Commit

Permalink
Allow users to change their email, displayName and password (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
henrybrink authored Apr 28, 2024
1 parent 1a2ea1c commit 91140b5
Show file tree
Hide file tree
Showing 16 changed files with 230 additions and 11 deletions.
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,4 @@ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Prisma
*.sqlite
*.sqlite-journal
35 changes: 35 additions & 0 deletions backend/package-lock.json

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

2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
"@prisma/client": "^5.11.0",
"@types/bcrypt": "^5.0.2",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"passport": "^0.7.0",
"passport-http": "^0.3.0",
"reflect-metadata": "^0.2.0",
Expand Down
15 changes: 15 additions & 0 deletions backend/src/api/user/patch.user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { IsEmail, IsOptional, Length } from 'class-validator';

export class PatchUserDTO {
@IsEmail()
@IsOptional()
email: string | undefined;

@Length(12, 72)
@IsOptional()
password: string | undefined;

@Length(2, 128)
@IsOptional()
displayName: string | undefined;
}
72 changes: 69 additions & 3 deletions backend/src/api/user/user.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
import { User } from '@prisma/client';
import { Prisma, User } from '@prisma/client';
import { DeepMockProxy, mockDeep } from 'jest-mock-extended';
import { UserRepository } from '../../db/repositories/user.repository';
import { AuthService } from '../../auth/auth.service';
import { TestConstants } from '../../../test/lib/constants';
import { NestRequest } from '../../types/request.type';
import { PrismaModule } from '../../db/prisma.module';
import { Response } from 'express';
import { PatchUserDTO } from './patch.user.dto';

describe('UserController', () => {
let controller: UserController;
let repository: DeepMockProxy<UserRepository>;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [PrismaModule],
controllers: [UserController],
}).compile();
providers: [UserRepository, AuthService],
})
.overrideProvider(UserRepository)
.useValue(mockDeep<UserRepository>())
.compile();

controller = module.get<UserController>(UserController);
repository = module.get(UserRepository);
});

it('should be defined', () => {
Expand All @@ -31,8 +46,59 @@ describe('UserController', () => {
user,
};

const response = (await controller.me(req)) as any;
const response = (await controller.getMe(req)) as any;

expect(response?.password).toBeUndefined();
});

it('should be able to change information about a user', async () => {
repository.updateUser.mockResolvedValue(
TestConstants.database.users.exampleUser,
);

const changeQuery: Prisma.UserUpdateInput = {
displayName: 'Test 1',
email: '[email protected]',
password: 'TEST123',
};

const mockRequest = {
user: {
id: TestConstants.database.users.exampleUser.id,
},
} as NestRequest;

const mockResponse = mockDeep<Response>();
mockResponse.status.mockReturnThis();

await controller.patchMe(
mockRequest,
{
displayName: changeQuery.displayName as string,
email: changeQuery.email as string,
password: changeQuery.password as string,
},
mockResponse as any,
);

expect(mockResponse.status).toHaveBeenCalledWith(200);
expect(mockResponse.json).toHaveBeenCalledWith(
TestConstants.database.users.exampleUser,
);
});

it('should not be able to modify a user with an empty modify request', async () => {
const mockRequest = mockDeep<NestRequest>();
const mockResponse = mockDeep<Response>();

mockResponse.status.mockReturnThis();

await controller.patchMe(
mockRequest as NestRequest,
{} as PatchUserDTO,
mockResponse as Response,
);

expect(mockResponse.status).toHaveBeenCalledWith(400);
});
});
65 changes: 62 additions & 3 deletions backend/src/api/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
import { Controller, Get, Request, UseGuards } from '@nestjs/common';
import { User } from '@prisma/client';
import {
Body,
Controller,
Get,
Patch,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { Prisma, User } from '@prisma/client';
import { Response } from 'express';
import { AutoGuard } from '../../auth/auto.guard';
import { PatchUserDTO } from './patch.user.dto';
import { AuthService } from '../../auth/auth.service';
import { UserRepository } from '../../db/repositories/user.repository';
import { NestRequest } from '../../types/request.type';

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

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

_sanatizeUser(user: User): SanatizedUser {
const sanatizedUser: SanatizedUser & { password?: string } = user;

Expand All @@ -23,7 +41,48 @@ export class UserController {
*/
@Get('/me')
@UseGuards(AutoGuard)
async me(@Request() req) {
async getMe(@Req() req) {
return this._sanatizeUser(req.user);
}

@Patch('/me')
@UseGuards(AutoGuard)
async patchMe(
@Req() req: NestRequest,
@Body() userPatch: PatchUserDTO,
@Res() res: Response,
) {
const userChanges: Prisma.UserUpdateInput = {};

if (userPatch.password) {
const hashedPassword = await this.authService.hashPassword(
userPatch.password,
);

userChanges.password = hashedPassword;
}

if (userPatch.email) {
userChanges.email = userPatch.email;
userChanges.verified = false;
}

if (userPatch.displayName) {
userChanges.displayName = userPatch.displayName;
}

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

res.status(200).json(this._sanatizeUser(user));
} else {
res.status(400).json({
error: 'Nothing was changed',
statusCode: 400,
});
}
}
}
3 changes: 2 additions & 1 deletion backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { UserController } from './api/user/user.controller';
import { PrismaModule } from './db/prisma.module';
import { LOGGER_SERVICE } from './logger/logger.service';

@Module({
imports: [AuthModule],
imports: [AuthModule, PrismaModule],
controllers: [AppController, UserController],
providers: [
AppService,
Expand Down
1 change: 1 addition & 0 deletions backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ import { AutoGuard } from './auto.guard';
@Module({
imports: [PrismaModule, PassportModule],
providers: [AuthService, HTTPStrategy, AutoGuard],
exports: [AuthService],
})
export class AuthModule {}
9 changes: 9 additions & 0 deletions backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,13 @@ export class AuthService {

return null;
}

/**
* Hashes a password using the preferred hash algorithm.
* @param password Plaintext password
* @returns Hashe password
*/
async hashPassword(password: string): Promise<string> {
return await bcrypt.hash(password, 12);
}
}
2 changes: 1 addition & 1 deletion backend/src/db/repositories/user.repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('UserRepository tests', () => {
it('should be able to modify a user', async () => {
prisma.user.update.mockResolvedValue(exampleUser);

const user = await userRepository.updateUser(exampleUser);
const user = await userRepository.updateUser(exampleUser.id, exampleUser);
expect(user).toEqual(exampleUser);
});
});
9 changes: 6 additions & 3 deletions backend/src/db/repositories/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,15 @@ export class UserRepository {
* @param user
* @returns Updated User
*/
public async updateUser(user: User): Promise<User> {
public async updateUser(
id: string,
update: Prisma.UserUpdateInput,
): Promise<User> {
return await this.prisma.user.update({
where: {
id: user.id,
id: id,
},
data: user,
data: update,
});
}

Expand Down
2 changes: 2 additions & 0 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}

Expand Down
5 changes: 5 additions & 0 deletions backend/src/types/request.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Request } from 'express';

export type NestRequest = Request & {
user: { id: string };
};
4 changes: 4 additions & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default withMermaid({
{ text: 'Projekt', link: '/project/idea' },
{ text: 'Statusberichte', link: '/reports/reports'},
{ text: 'Guidelines', link: '/guidelines/project-guideline' },
{ text: 'Development', link: '/development/overview', }
],

sidebar: {
Expand Down Expand Up @@ -53,6 +54,9 @@ export default withMermaid({
]
}
],
'/development': [
{ text: 'Authentication', link: '/development/authentication' }
]
},

socialLinks: [
Expand Down
13 changes: 13 additions & 0 deletions docs/development/authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Authentication
> [!WARNING]
> The currently used authentication mechanism is subject to changes and only intended for development purposes.
## Local Authentication (Development)
During development `Basic`-Authentication is enabled to make authentication easier. You need to supply a username and a password.
There are example users available, when using the database seeds.

### Example Users
The password for all available example users is
`1234`.
Please note that those users are not available in production.

- `[email protected]`: Max Mustermann
3 changes: 3 additions & 0 deletions docs/development/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Development
> [!WARNING]
> This section is subject to change as it's intended to document the development process. This is not intented for an external audience.

0 comments on commit 91140b5

Please sign in to comment.