Skip to content

Commit

Permalink
chore: swagger 인증 적용
Browse files Browse the repository at this point in the history
  • Loading branch information
SeungGwan123 committed Nov 14, 2024
1 parent d4a767b commit 8bdeb53
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 70 deletions.
71 changes: 42 additions & 29 deletions packages/server/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,43 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Request,
UseGuards
} from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';

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

@HttpCode(HttpStatus.OK)
@Post('login')
signIn(@Body() signInDto: Record<string, any>) {
return this.authService.signIn(signInDto.username);
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Request,
UseGuards
} from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
import { ApiProperty, ApiBody, ApiBearerAuth, ApiSecurity } from '@nestjs/swagger';
class SignInDto {
@ApiProperty({
example: 'admin',
description: 'Email address of the user',
required: true,
})
username: string;
}

@UseGuards(AuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
}


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

@ApiBody({ type: SignInDto })
@HttpCode(HttpStatus.OK)
@Post('login')
signIn(@Body() signInDto: Record<string, any>) {
return this.authService.signIn(signInDto.username);
}


@UseGuards(AuthGuard)
@ApiBearerAuth('access-token')
@ApiSecurity('access-token')
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
}
80 changes: 41 additions & 39 deletions packages/server/src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,44 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { Request } from 'express';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { Request } from 'express';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(
token,
{
secret: jwtConstants.secret
}
);
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
try {
const payload = await this.jwtService.verifyAsync(
token,
{
secret: jwtConstants.secret
}
);
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();

private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
console.log(request.headers)
console.log(request)
return type === 'Bearer' ? token : undefined;
}
return true;
}

private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}


16 changes: 15 additions & 1 deletion packages/server/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { SwaggerModule, DocumentBuilder, SwaggerCustomOptions } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);

Expand All @@ -15,7 +15,21 @@ async function bootstrap() {
.setDescription('CorinEE API description')
.setVersion('1.0')
.addTag('corinee')
.addBearerAuth(
{
type: 'http',
scheme: 'bearer',
name: 'Authorization',
in: 'header',
},
'access-token',
)
.build();
const customOptions: SwaggerCustomOptions = {
swaggerOptions: {
persistAuthorization: true,
},
};
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, documentFactory);

Expand Down
5 changes: 4 additions & 1 deletion packages/server/src/trade/trade.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Body, Controller, Get, Query, Param, Request, UseGuards } from '@nestjs/common';
import { TradeService } from './trade.service';
import { AuthGuard } from 'src/auth/auth.guard';
import { ApiBearerAuth, ApiSecurity } from '@nestjs/swagger';

@Controller('trade')
export class TradeController {
constructor(private tradeService: TradeService) {}

@UseGuards(AuthGuard)
@ApiBearerAuth('access-token')
@ApiSecurity('access-token')
@UseGuards(AuthGuard)
@Get('calculate-percentage-buy/:moneyType')
calculatePercentBuy(
@Request() req,
Expand Down

0 comments on commit 8bdeb53

Please sign in to comment.