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

feat: JWT 발급 및 인증 #32

Merged
merged 13 commits into from
May 24, 2024
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.ts text eol=lf
99 changes: 99 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.2.1",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.3.1",
"@types/xlsx-populate": "github:JanLoebel/types-xlsx-populate",
Expand Down
2 changes: 2 additions & 0 deletions scripts/git-hooks/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env sh
npm run lint
10 changes: 4 additions & 6 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_FILTER } from '@nestjs/core';

import { AuthModule } from './auth/auth.module';
import { AllExceptionsFilter } from './common/filters/all-exception.filter';
import { DebugModule } from './debug/debug.module';
import { EventModule } from './event/event.module';
import { GroupModule } from './group/group.module';
Expand All @@ -23,10 +21,10 @@ import { UserModule } from './user/user.module';
UserModule,
],
providers: [
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
// {
// provide: APP_FILTER,
// useClass: AllExceptionsFilter,
// },
],
})
export class AppModule {}
17 changes: 17 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ export class AuthController {
return this.authService.kakaoToken(code);
}

@Get('kakao/token/info')
@ApiQuery({ name: 'kakaoToken', required: true })
async kakaoTokenInfo(@Query('kakaoToken') kakaoToken: string) {
return this.authService.kakaoTokenInfo(kakaoToken);
}

@Post('kakao/login')
@ApiQuery({ name: 'kakaoToken', required: true })
async kakaoLogin(@Query('kakaoToken') kakaoToken: string) {
Expand All @@ -46,4 +52,15 @@ export class AuthController {
async kakaoUnlink(@Query('kakaoToken') kakaoToken: string) {
return this.authService.kakaoUnlink(kakaoToken);
}

@Get('login')
@ApiQuery({ name: 'kakaoToken', required: true })
async login(@Query('kakaoToken') kakaoToken: string) {
return this.authService.login(kakaoToken);
}

@Get('signout')
async signout(@Query('kakaoToken') kakaoToken: string) {
return this.authService.signout(kakaoToken);
}
}
36 changes: 36 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

import { jwtConstants } from './constants';

@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 {
request['user'] = await this.jwtService.verifyAsync(token, {
secret: jwtConstants.secret,
});
} catch {
throw new UnauthorizedException();
}
return true;
}

private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
14 changes: 13 additions & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
import { HttpModule } from '@nestjs/axios';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';

import { UserModule } from '../user/user.module';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { jwtConstants } from './constants';

@Module({
imports: [ConfigModule, HttpModule],
imports: [
ConfigModule,
HttpModule,
UserModule,
JwtModule.register({
global: true,
secret: jwtConstants.secret,
signOptions: { expiresIn: '60s' },
}),
],
controllers: [AuthController],
providers: [AuthService],
})
Expand Down
49 changes: 49 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { firstValueFrom } from 'rxjs';

import { UserService } from '../user/user.service';

@Injectable()
export class AuthService {
constructor(
private readonly configService: ConfigService,
private readonly httpService: HttpService,
private readonly userService: UserService,
private readonly jwtService: JwtService,
) {}

kakaoCallback(
Expand Down Expand Up @@ -40,6 +45,19 @@ export class AuthService {
return data['access_token'];
}

async kakaoTokenInfo(kakaoToken: string) {
const { data } = await firstValueFrom(
this.httpService.get('https://kapi.kakao.com/v1/user/access_token_info', {
headers: {
Authorization: `Bearer ${kakaoToken}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
},
}),
);

return data;
}

async kakaoLogin(kakaoToken: string) {
const { data } = await firstValueFrom(
this.httpService.get('https://kapi.kakao.com/v2/user/me', {
Expand Down Expand Up @@ -86,4 +104,35 @@ export class AuthService {

return data;
}

async login(kakaoToken: string) {
const kakaoInfo = await this.kakaoLogin(kakaoToken);

const kakaoId = kakaoInfo.id;
const name = kakaoInfo.kakao_account.profile.nickname;
const email = kakaoInfo.kakao_account.email;

let user = await this.userService.findOneByKakaoId(kakaoId);
if (!user) {
user = await this.userService.create({
kakaoId,
name,
email,
});
}

const payload = { sub: user.id, name: user.name, iat: Date.now() };
return {
access_token: await this.jwtService.signAsync(payload),
};
}

async signout(kakaoToken: string) {
const { kakaoId } = await this.kakaoTokenInfo(kakaoToken);

this.userService.removeOneByKakaoId(kakaoId);
await this.kakaoUnlink(kakaoToken);

return { message: 'Successfully signed out' };
}
}
7 changes: 7 additions & 0 deletions src/auth/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * as dotenv from 'dotenv';
import * as process from 'node:process';

dotenv.config();
export const jwtConstants = {
secret: process.env.JWT_SECRET,
};
Loading
Loading