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

Account Managment #29

Merged
merged 16 commits into from
Feb 26, 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
28 changes: 10 additions & 18 deletions apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
import { RoutesModule } from './routes.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ConfigModule } from '@nestjs/config';
import { envFiles } from './config';
import { HealthModule } from './health/health.module';
import { AuthModule } from './auth/auth.module';
import { DatabaseModule } from './database/database.module';
import { UsersModule } from './users/users.module';
import { ProfileModule } from './profile/profile.module';

@Module({
imports: [
Expand All @@ -15,25 +18,14 @@ import { HealthModule } from './health/health.module';
}),
ServeStaticModule.forRoot({
rootPath: join(__dirname, '/../../frontend/dist'),
exclude: ['/rest-api*', "health*"],
exclude: ['/rest-api*', 'health*'],
}),
RoutesModule,
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: 'mysql',
host: config.get<string>('DB_HOST'),
port: config.get<number>('DB_PORT'),
username: config.get<string>('DB_USER'),
password: config.get<string>('DB_PASSWORD'),
database: config.get<string>('DB_DATABASE'),
autoLoadEntities: config.get<boolean>('DB_AUTOLOAD_ENTITIES'),
synchronize: config.get<boolean>('DB_SYNCHRONIZE'),
entities: [join(__dirname, '/**/*.entity{.ts,.js}')],
}),
}),
DatabaseModule,
HealthModule,
AuthModule,
UsersModule,
ProfileModule,
maingockien01 marked this conversation as resolved.
Show resolved Hide resolved
],
controllers: [],
providers: [],
Expand Down
19 changes: 19 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LogInDto } from '@team8/types/dtos/auth/login.dto';
import { SignUpDto } from '@team8/types/dtos/auth/signup.dto';

@Controller()
export class AuthController {
constructor(private authService: AuthService) {}

@Post('signup')
signUp(@Body() signupDto: SignUpDto) {
return this.authService.signUp(signupDto);
}

@Post('login')
logIn(@Body() logInDto: LogInDto) {
return this.authService.logIn(logInDto);
}
}
11 changes: 11 additions & 0 deletions apps/backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from '../users/users.module';

@Module({
imports: [UsersModule],
providers: [AuthService],
controllers: [AuthController],
})
export class AuthModule {}
34 changes: 34 additions & 0 deletions apps/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import {
LogInDto,
SignUpDto,
LogInRetDto,
SignUpRetDto,
} from '@team8/types/dtos/auth';

@Injectable()
export class AuthService {
constructor(private usersService: UsersService) {}

async signUp(dto: SignUpDto): Promise<SignUpRetDto> {
//TODO: Hash the password
const user = await this.usersService.create(dto);
const result = new SignUpRetDto();
result.username = user.username;
return result;
}

async logIn(dto: LogInDto): Promise<LogInRetDto> {
//TODO: Return message according to error
const user = await this.usersService.findOneByUsername(dto.username);
if (user?.hashPassword !== dto.hashPassword) {
throw new UnauthorizedException();
}
const result = new LogInRetDto();
result.username = user.username;
// TODO: Generate a JWT and return it here
// instead of the user object
return result;
}
}
26 changes: 26 additions & 0 deletions apps/backend/src/database/database.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
import { join } from 'path';

@Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => ({
type: 'mysql',
host: config.getOrThrow<string>('DB_HOST'),
port: config.getOrThrow<number>('DB_PORT'),
username: config.getOrThrow<string>('DB_USER'),
password: config.getOrThrow<string>('DB_PASSWORD'),
database: config.getOrThrow<string>('DB_DATABASE'),
autoLoadEntities: config.getOrThrow<boolean>(
'DB_AUTOLOAD_ENTITIES',
),
synchronize: config.getOrThrow<boolean>('DB_SYNCHRONIZE'),
entities: [join(__dirname, '../**/*.entity{.ts,.js}')],
}),
inject: [ConfigService],
}),
],
})
export class DatabaseModule {}
59 changes: 36 additions & 23 deletions apps/backend/src/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,48 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, ManyToMany,JoinTable, Relation} from 'typeorm';
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
ManyToMany,
JoinTable,
Relation,
} from 'typeorm';
import { Degree } from './degree.entity';
import { Course} from './course.entity';
import { Course } from './course.entity';
import { Section } from './section.entity';

@Entity()
export class User {
@PrimaryGeneratedColumn()
uid: number;
@PrimaryGeneratedColumn()
uid: number;

@Column()
fullName: string;

@Column()
fullName: string;
@Column({ unique: true })
username: string;

@Column()
username: string;
@Column()
hashPassword: string;

@Column()
hashPassword: string;
// @Column()
// did: number;

@Column()
did: number;
@Column({ default: '' })
pictureProfile: string;

@Column()
pictureProfile: string;
// @ManyToOne(() => Degree, (degree) => degree.users)
// degree: Degree;

@ManyToOne(() => Degree, (degree) => degree.users)
degree: Degree
// @ManyToMany(() => Course)
// @JoinTable()
// courses: Relation<Course[]>;

@ManyToMany(() => Course)
@JoinTable()
courses: Relation<Course[]>;
// @ManyToMany(() => Section)
// @JoinTable()
// sections: Relation<Section[]>;

@ManyToMany(() => Section)
@JoinTable()
sections: Relation<Section[]>;
}
// constructor(user: Partial<User>) {
// Object.assign(this, user);
// }
}
2 changes: 1 addition & 1 deletion apps/backend/src/hello/hello.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import { APPS_NAME } from '@team8/constants/apps';
export class HelloController {
@Get()
getHello(): string {
return `Hello from ${APPS_NAME} updated!`;
return APPS_NAME;
}
}
12 changes: 11 additions & 1 deletion apps/backend/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
console.log(`App is running in ${configService.get('NODE_ENV') || 'dev'} mode, listening on port ${configService.get('PORT')}`);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, //Does not take in unwanted field
}),
);
console.log(
`App is running in ${
configService.get('NODE_ENV') || 'dev'
} mode, listening on port ${configService.get('PORT')}`,
);
await app.listen(configService.get('PORT'));
}
bootstrap();
14 changes: 14 additions & 0 deletions apps/backend/src/profile/profile.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Body, Controller, Post } from '@nestjs/common';
import { ProfileService } from './profile.service';
import { UpdateDto } from '@team8/types/dtos/profile/update.dto';

@Controller()
export class ProfileController {
constructor(private profileService: ProfileService) {}

//TODO: Create update function for each field of user profile
@Post()
update(@Body() updateDto: UpdateDto) {
return this.profileService.update(updateDto);
}
}
11 changes: 11 additions & 0 deletions apps/backend/src/profile/profile.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { ProfileService } from './profile.service';
import { ProfileController } from './profile.controller';
import { UsersModule } from '../users/users.module';

@Module({
imports: [UsersModule],
providers: [ProfileService],
controllers: [ProfileController],
})
export class ProfileModule {}
14 changes: 14 additions & 0 deletions apps/backend/src/profile/profile.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { UpdateDto } from '@team8/types/dtos/profile/update.dto';

@Injectable()
export class ProfileService {
constructor(private usersService: UsersService) {}

async update(dto: UpdateDto): Promise<any> {
//TODO: Hash the password
const user = await this.usersService.update(dto);
return user;
}
}
19 changes: 15 additions & 4 deletions apps/backend/src/routes.module.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
import { Module } from '@nestjs/common';
import { HelloModule } from './hello/hello.module';
//import { HelloModule } from './hello/hello.module';
import { RouterModule } from '@nestjs/core';
import { AuthModule } from '../src/auth/auth.module';
import { ProfileModule } from './profile/profile.module';

@Module({
imports: [
HelloModule,
//HelloModule,
AuthModule,
RouterModule.register([
{
path: '/rest-api',
children: [
// {
// path: '/hello',
// module: HelloModule,
// },
{
path: '/hello',
module: HelloModule,
path: '/auth',
module: AuthModule,
},
{
path: '/profile',
module: ProfileModule,
},
],
},
Expand Down
4 changes: 4 additions & 0 deletions apps/backend/src/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Controller } from '@nestjs/common';

@Controller('users')
export class UsersController {}
13 changes: 13 additions & 0 deletions apps/backend/src/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';

@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
39 changes: 39 additions & 0 deletions apps/backend/src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Injectable, ForbiddenException } from '@nestjs/common';
import { SignUpDto } from '@team8/types/dtos/auth/signup.dto';
import { Repository, QueryFailedError } from 'typeorm';
import { User } from '../entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { UpdateDto } from '@team8/types/dtos/profile/update.dto';

@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private readonly usersRepository: Repository<User>,
) {}

async create(dto: SignUpDto) {
try {
await this.usersRepository.save(dto);
return await this.findOneByUsername(dto.username);
} catch (error) {
if (error instanceof QueryFailedError) {
if (error.driverError.code === 'ER_DUP_ENTRY') {
throw new ForbiddenException('Credential taken');
}
}
}
}

async findOneByUsername(username: string) {
return this.usersRepository.findOneBy({ username });
}

async update(dto: UpdateDto) {
const user = await this.findOneByUsername(dto.username);
if (dto.fullName !== null) user.fullName = dto.fullName;
if (dto.pictureProfile !== null)
user.pictureProfile = dto.pictureProfile;
await this.usersRepository.save(user);
}
}
4 changes: 4 additions & 0 deletions packages/types/dtos/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './login.dto';
export * from './signup.dto';
export * from './loginRet.dto';
export * from './signupRet.dto';
11 changes: 11 additions & 0 deletions packages/types/dtos/auth/login.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';

export class LogInDto {
@IsString()
@IsNotEmpty()
username: string;

@IsString()
@IsNotEmpty()
hashPassword: string;
}
Loading