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

[TBCCT-22] Profile page #33

Merged
merged 8 commits into from
Oct 11, 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
1 change: 0 additions & 1 deletion .npmrc

This file was deleted.

4 changes: 3 additions & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@
"@nestjs/platform-express": "^10.0.0",
"@nestjs/typeorm": "^10.0.2",
"@ts-rest/nest": "^3.51.0",
"@types/multer": "^1.4.12",
"@types/multer": "1.4.12",
"bcrypt": "catalog:",
"class-transformer": "catalog:",
"class-validator": "catalog:",
"dotenv": "16.4.5",
"lodash": "^4.17.21",
"nestjs-base-service": "catalog:",
"nodemailer": "^6.9.15",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
Expand Down
2 changes: 2 additions & 0 deletions api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { NotificationsModule } from '@api/modules/notifications/notifications.mo
import { AdminModule } from '@api/modules/admin/admin.module';
import { ImportModule } from '@api/modules/import/import.module';
import { ApiEventsModule } from '@api/modules/api-events/api-events.module';
import { UsersModule } from '@api/modules/users/users.module';

@Module({
imports: [
Expand All @@ -16,6 +17,7 @@ import { ApiEventsModule } from '@api/modules/api-events/api-events.module';
ApiEventsModule,
AdminModule,
ImportModule,
UsersModule,
],
controllers: [AppController],
providers: [AppService],
Expand Down
9 changes: 9 additions & 0 deletions api/src/decorators/get-user.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { User } from '@shared/entities/users/user.entity';

export const GetUser = createParamDecorator(
(data: unknown, ctx: ExecutionContext): User => {
const request = ctx.switchToHttp().getRequest();
return request.user;
},
);
2 changes: 1 addition & 1 deletion api/src/modules/auth/authentication.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class AuthenticationController {
return tsRestHandler(
authContract.resetPassword,
async ({ body: { password } }) => {
await this.authService.updatePassword(user, password);
await this.authService.resetPassword(user, password);
return {
body: null,
status: 201,
Expand Down
27 changes: 21 additions & 6 deletions api/src/modules/auth/authentication.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import { UsersService } from '@api/modules/users/users.service';
import { User } from '@shared/entities/users/user.entity';
import * as bcrypt from 'bcrypt';
import { CommandBus, EventBus } from '@nestjs/cqrs';
import { UserWithAccessToken } from '@shared/dtos/user.dto';
import { UserWithAccessToken } from '@shared/dtos/users/user.dto';
import { TOKEN_TYPE_ENUM } from '@shared/schemas/auth/token-type.schema';
import { CreateUserDto } from '@shared/schemas/users/create-user.schema';
import { CreateUserDto } from '@shared/dtos/users/create-user.dto';
import { randomBytes } from 'node:crypto';
import { SendWelcomeEmailCommand } from '@api/modules/notifications/email/commands/send-welcome-email.command';
import { JwtManager } from '@api/modules/auth/services/jwt.manager';
import { SignUpDto } from '@shared/schemas/auth/sign-up.schema';
import {
SignUpDto,
UpdateUserPasswordDto,
} from '@shared/schemas/auth/sign-up.schema';
import { UserSignedUpEvent } from '@api/modules/admin/events/user-signed-up.event';

@Injectable()
Expand Down Expand Up @@ -56,7 +59,7 @@ export class AuthenticationService {
throw new UnauthorizedException();
}
user.isActive = true;
await this.usersService.updatePassword(user, newPassword);
await this.usersService.saveNewHashedPassword(user, newPassword);
this.eventBus.publish(new UserSignedUpEvent(user.id, user.email));
}

Expand All @@ -67,7 +70,19 @@ export class AuthenticationService {
throw new UnauthorizedException();
}

async updatePassword(user: User, newPassword: string): Promise<void> {
await this.usersService.updatePassword(user, newPassword);
async updatePassword(user: User, dto: UpdateUserPasswordDto): Promise<User> {
const { password, newPassword } = dto;
if (await this.isPasswordValid(user, password)) {
return this.usersService.saveNewHashedPassword(user, newPassword);
}
throw new UnauthorizedException();
}

async resetPassword(user: User, newPassword: string): Promise<void> {
await this.usersService.saveNewHashedPassword(user, newPassword);
}

async isPasswordValid(user: User, password: string): Promise<boolean> {
return bcrypt.compare(password, user.password);
}
}
63 changes: 60 additions & 3 deletions api/src/modules/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,61 @@
import { Controller } from '@nestjs/common';
import {
Controller,
ClassSerializerInterceptor,
UseInterceptors,
HttpStatus,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';

@Controller('users')
export class UsersController {}
import { UsersService } from './users.service';
import { tsRestHandler, TsRestHandler } from '@ts-rest/nest';
import { GetUser } from '@api/decorators/get-user.decorator';
import { User } from '@shared/entities/users/user.entity';
import { usersContract as c } from '@shared/contracts/users.contract';
import { JwtAuthGuard } from '@api/modules/auth/guards/jwt-auth.guard';
import { AuthenticationService } from '@api/modules/auth/authentication.service';

@Controller()
@UseInterceptors(ClassSerializerInterceptor)
@UseGuards(JwtAuthGuard)
export class UsersController {
constructor(
private usersService: UsersService,
private auth: AuthenticationService,
) {}

@TsRestHandler(c.findMe)
async findMe(@GetUser() user: User): Promise<any> {
return tsRestHandler(c.findMe, async ({ query }) => {
const foundUser = await this.usersService.getById(user.id, query);
if (!foundUser) {
throw new UnauthorizedException();
}
return { body: { data: foundUser }, status: HttpStatus.OK };
});
}

@TsRestHandler(c.updatePassword)
async updatePassword(@GetUser() user: User): Promise<any> {
return tsRestHandler(c.updatePassword, async ({ body }) => {
const updatedUser = await this.auth.updatePassword(user, body);
return { body: { data: updatedUser }, status: HttpStatus.OK };
});
}

@TsRestHandler(c.updateMe)
async update(@GetUser() user: User): Promise<any> {
return tsRestHandler(c.updateMe, async ({ body }) => {
const updatedUser = await this.usersService.update(user.id, body);
return { body: { data: updatedUser }, status: HttpStatus.CREATED };
});
}

@TsRestHandler(c.deleteMe)
async deleteMe(@GetUser() user: User): Promise<any> {
return tsRestHandler(c.deleteMe, async () => {
await this.usersService.remove(user.id);
return { body: null, status: HttpStatus.OK };
});
}
}
5 changes: 3 additions & 2 deletions api/src/modules/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '@shared/entities/users/user.entity';
import { UsersController } from '@api/modules/users/users.controller';
import { AuthModule } from '@api/modules/auth/auth.module';

@Module({
imports: [TypeOrmModule.forFeature([User])],
imports: [TypeOrmModule.forFeature([User]), forwardRef(() => AuthModule)],
providers: [UsersService],
exports: [UsersService],
controllers: [UsersController],
Expand Down
31 changes: 22 additions & 9 deletions api/src/modules/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,52 @@ import { User } from '@shared/entities/users/user.entity';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';

import { AppBaseService } from '@api/utils/app-base.service';
import { CreateUserDto } from '@shared/dtos/users/create-user.dto';
import { UpdateUserDto } from '@shared/dtos/users/update-user.dto';
import { AppInfoDTO } from '@api/utils/info.dto';
@Injectable()
export class UsersService {
constructor(@InjectRepository(User) private repo: Repository<User>) {}
export class UsersService extends AppBaseService<
User,
CreateUserDto,
UpdateUserDto,
AppInfoDTO
> {
constructor(
@InjectRepository(User) private userRepository: Repository<User>,
) {
super(userRepository, 'user', 'users');
}

async findOneBy(id: string) {
return this.repo.findOne({
return this.userRepository.findOne({
where: { id },
});
}

async findByEmail(email: string): Promise<User | null> {
return this.repo.findOne({ where: { email } });
return this.userRepository.findOne({ where: { email } });
}

async createUser(newUser: Partial<User>) {
const existingUser = await this.findByEmail(newUser.email);
if (existingUser) {
throw new ConflictException(`Email ${newUser.email} already exists`);
}
return this.repo.save(newUser);
return this.userRepository.save(newUser);
}

async updatePassword(user: User, newPassword: string) {
async saveNewHashedPassword(user: User, newPassword: string) {
user.password = await bcrypt.hash(newPassword, 10);
return this.repo.save(user);
return this.userRepository.save(user);
}

async delete(user: User) {
return this.repo.remove(user);
return this.userRepository.remove(user);
}

async isUserActive(id: string) {
const user = await this.repo.findOneBy({ id });
const user = await this.userRepository.findOneBy({ id });
return user.isActive;
}
}
67 changes: 67 additions & 0 deletions api/src/utils/app-base.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
BaseService,
DEFAULT_PAGINATION,
FetchSpecification,
} from 'nestjs-base-service';

import { Repository } from 'typeorm';
import { PaginationMeta } from '@shared/dtos/global/api-response.dto';

export abstract class AppBaseService<
// eslint-disable-next-line @typescript-eslint/ban-types
Entity extends object,
CreateModel,
UpdateModel,
Info,
> extends BaseService<Entity, CreateModel, UpdateModel, Info> {
constructor(
protected readonly repository: Repository<Entity>,
protected alias: string = 'base_entity',
protected pluralAlias: string = 'base_entities',
protected idProperty: string = 'id',
) {
super(repository, alias, { idProperty });
}

async findAllPaginated(
fetchSpecification?: FetchSpecification,
extraOps?: Record<string, any>,
info?: Info,
): Promise<{
data: (Partial<Entity> | undefined)[];
metadata: PaginationMeta | undefined;
}> {
const entitiesAndCount: [Partial<Entity>[], number] = await this.findAll(
{ ...fetchSpecification, ...extraOps },
info,
);
return this._paginate(entitiesAndCount, fetchSpecification);
}

private _paginate(
entitiesAndCount: [Partial<Entity>[], number],
fetchSpecification?: FetchSpecification,
): {
data: (Partial<Entity> | undefined)[];
metadata: PaginationMeta | undefined;
} {
const totalItems: number = entitiesAndCount[1];
const entities: Partial<Entity>[] = entitiesAndCount[0];
const pageSize: number =
fetchSpecification?.pageSize ?? DEFAULT_PAGINATION.pageSize ?? 25;
const page: number =
fetchSpecification?.pageNumber ?? DEFAULT_PAGINATION.pageNumber ?? 1;
const disablePagination: boolean | undefined =
fetchSpecification?.disablePagination;
const meta: PaginationMeta | undefined = disablePagination
? undefined
: new PaginationMeta({
totalPages: Math.ceil(totalItems / pageSize),
totalItems,
size: pageSize,
page,
});

return { data: entities, metadata: meta };
}
}
4 changes: 4 additions & 0 deletions api/src/utils/info.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { InfoDTO } from 'nestjs-base-service';
import { User } from '@shared/entities/users/user.entity';

export type AppInfoDTO = InfoDTO<User>;
Loading
Loading