Skip to content

Commit

Permalink
fix: categories api 유저 아이디 가드로 변경 (#166)
Browse files Browse the repository at this point in the history
  • Loading branch information
yeongbinim authored Nov 22, 2023
1 parent f20fd94 commit 8d4c658
Show file tree
Hide file tree
Showing 12 changed files with 40 additions and 51 deletions.
3 changes: 1 addition & 2 deletions BE/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { CategoriesModule } from './categories/categories.module';
import { MatesModule } from './mates/mates.module';
import { UsersModule } from './users/users.module';
import { UsersModel } from './users/entity/users.entity';
import { GoogleStrategy } from './google.strategy';
import { PassportModule } from '@nestjs/passport';
import { AuthModule } from './auth/auth.module';

Expand Down Expand Up @@ -40,6 +39,6 @@ import { AuthModule } from './auth/auth.module';
AuthModule,
],
controllers: [AppController],
providers: [AppService, GoogleStrategy],
providers: [AppService],
})
export class AppModule {}
2 changes: 1 addition & 1 deletion BE/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ export class AuthController {

@Get('logout')
@UseGuards(AccessTokenGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '로그아웃' })
@ApiResponse({ status: 200, description: '로그아웃 성공' })
@ApiResponse({ status: 401, description: '인증 실패' })
@ApiBearerAuth()
logout(@User('id') userId: number, @Res() res: Response) {
console.log(`${userId}를 로그아웃 시키는 로직`);
res.redirect('/');
Expand Down
4 changes: 3 additions & 1 deletion BE/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from 'src/users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { GoogleStrategy } from './google.strategy';

@Module({
imports: [
Expand All @@ -19,6 +20,7 @@ import { JwtModule } from '@nestjs/jwt';
UsersModule,
],
controllers: [AuthController],
providers: [AuthService],
providers: [AuthService, GoogleStrategy],
exports: [AuthService],
})
export class AuthModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
super({
clientID: config.get('GOOGLE_CLIENT_ID'),
clientSecret: config.get('GOOGLE_CLIENT_SECRET'),
callbackURL: 'http://localhost:3000/auth/google',
callbackURL: config.get('GOOGLE_CALLBACK_URL'),
scope: ['email'],
});
}
Expand Down
32 changes: 23 additions & 9 deletions BE/src/categories/categories.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,31 @@ import {
Param,
Patch,
Post,
Headers,
UseGuards,
} from '@nestjs/common';
import {
ApiBadRequestResponse,
ApiBearerAuth,
ApiCreatedResponse,
ApiOperation,
ApiParam,
ApiTags,
} from '@nestjs/swagger';
import { CategoriesService } from './categories.service';
import { CategoryGetDto } from './dto/request/get-categories.dto';
import { CategoryCreateDto } from './dto/request/create-categories.dto';
import { CategoryUpdateDto } from './dto/request/update-categories.dto';
import { CategoryDto } from './dto/response/category.dto';
import { AccessTokenGuard } from 'src/auth/guard/bearer-token.guard';
import { User } from 'src/users/decorator/user.decorator';

@ApiTags('Categories')
@Controller('categories')
export class CategoriesController {
constructor(private readonly categoriesService: CategoriesService) {}

@Get()
@UseGuards(AccessTokenGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '카테고리 조회' })
@ApiCreatedResponse({
type: [CategoryDto],
Expand All @@ -35,14 +39,15 @@ export class CategoriesController {
@ApiBadRequestResponse({
description: '잘못된 요청입니다.',
})
getCategories(
@Headers('authorization') CategoryGetDto,
): Promise<CategoryDto[]> {
getCategories(@User('id') user_id: number): Promise<CategoryDto[]> {
// TODO: 유저 id를 받아올 방식 정하기
user_id;
return this.categoriesService.findByUserId(1);
}

@Post()
@UseGuards(AccessTokenGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '카테고리 생성' })
@ApiCreatedResponse({
type: CategoryDto,
Expand All @@ -52,12 +57,15 @@ export class CategoriesController {
description: '잘못된 요청입니다.',
})
createCategories(
@User('id') user_id: number,
@Body() categoriesData: CategoryCreateDto,
): Promise<CategoryCreateDto> {
return this.categoriesService.create(categoriesData);
return this.categoriesService.create(user_id, categoriesData);
}

@Patch(':category_id')
@UseGuards(AccessTokenGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '카테고리 수정' })
@ApiParam({
name: 'category_id',
Expand All @@ -73,13 +81,16 @@ export class CategoriesController {
description: '잘못된 요청입니다.',
})
updateCategories(
@User('id') user_id: number,
@Body() categoriesData: CategoryUpdateDto,
@Param('category_id') category_id: number,
): Promise<CategoryDto> {
return this.categoriesService.update(categoriesData, category_id);
return this.categoriesService.update(user_id, categoriesData, category_id);
}

@Delete(':category_id')
@UseGuards(AccessTokenGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '카테고리 삭제' })
@ApiParam({
name: 'category_id',
Expand All @@ -93,7 +104,10 @@ export class CategoriesController {
@ApiBadRequestResponse({
description: '잘못된 요청입니다.',
})
deleteCategories(@Param('category_id') category_id: number): Promise<void> {
return this.categoriesService.remove(category_id);
deleteCategories(
@User('id') user_id: number,
@Param('category_id') category_id: number,
): Promise<void> {
return this.categoriesService.remove(user_id, category_id);
}
}
4 changes: 3 additions & 1 deletion BE/src/categories/categories.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { CategoriesService } from './categories.service';
import { CategoriesController } from './categories.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Categories } from './categories.entity';
import { AuthModule } from 'src/auth/auth.module';
import { UsersModule } from 'src/users/users.module';

@Module({
imports: [TypeOrmModule.forFeature([Categories])],
imports: [TypeOrmModule.forFeature([Categories]), AuthModule, UsersModule],
providers: [CategoriesService],
controllers: [CategoriesController],
})
Expand Down
12 changes: 7 additions & 5 deletions BE/src/categories/categories.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ export class CategoriesService {
private categoriesRepository: Repository<Categories>,
) {}

async create(categoriesData: CategoryCreateDto): Promise<CategoryDto> {
const { user_id, ...data } = categoriesData;
async create(
user_id: number,
categoriesData: CategoryCreateDto,
): Promise<CategoryDto> {
const user = { id: user_id } as UsersModel;
const category = this.categoriesRepository.create({
...data,
...categoriesData,
user_id: user,
});
const savedCategory = await this.categoriesRepository.save(category);
Expand All @@ -41,6 +43,7 @@ export class CategoriesService {
}

async update(
user_id: number,
categoriesData: CategoryUpdateDto,
id: number,
): Promise<CategoryDto> {
Expand All @@ -54,7 +57,7 @@ export class CategoriesService {
return this.entityToDto(updatedCategory);
}

async remove(id: number): Promise<void> {
async remove(user_id: number, id: number): Promise<void> {
const result = await this.categoriesRepository.delete(id);
if (result.affected === 0) {
throw new NotFoundException('해당 카테고리가 존재하지 않습니다.');
Expand All @@ -64,7 +67,6 @@ export class CategoriesService {
entityToDto(category: Categories): CategoryDto {
const categoryDto: CategoryDto = {
id: category.id,
user_id: category.user_id.id,
name: category.name,
color_code: category.color_code,
};
Expand Down
7 changes: 0 additions & 7 deletions BE/src/categories/dto/request/create-categories.dto.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

export class CategoryCreateDto {
@ApiProperty({
type: 'number',
example: '1',
description: '유저 id',
})
user_id: number;

@ApiProperty({
type: 'string',
example: '백준',
Expand Down
10 changes: 0 additions & 10 deletions BE/src/categories/dto/request/get-categories.dto.ts

This file was deleted.

7 changes: 0 additions & 7 deletions BE/src/categories/dto/request/update-categories.dto.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

export class CategoryUpdateDto {
@ApiProperty({
type: 'number',
example: '1',
description: '유저 id',
})
user_id: number;

@ApiProperty({
type: 'string',
example: '백준',
Expand Down
6 changes: 0 additions & 6 deletions BE/src/categories/dto/response/category.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ export class CategoryDto {
description: '카테고리 id',
})
id: number;
@ApiProperty({
type: 'number',
example: '1',
description: '유저 id',
})
user_id: number;

@ApiProperty({
type: 'string',
Expand Down
2 changes: 1 addition & 1 deletion BE/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ async function bootstrap() {

app.useGlobalPipes(new ValidationPipe());

await app.listen(configService.get<number>('PORT'));
await app.listen(configService.get<number>('PORT') || 3000);
}
bootstrap();

0 comments on commit 8d4c658

Please sign in to comment.