Skip to content

Commit

Permalink
Merge pull request #204 from boostcampwm2023/feat/200-naver-login
Browse files Browse the repository at this point in the history
[Feat] 네이버 로그인
  • Loading branch information
JoonSoo-Kim authored Dec 5, 2023
2 parents 76706ff + 20d2bf3 commit f3c7b86
Show file tree
Hide file tree
Showing 9 changed files with 142 additions and 6 deletions.
46 changes: 46 additions & 0 deletions BE/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 BE/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"mysql2": "^3.6.3",
"passport": "^0.6.0",
"passport-jwt": "^4.0.1",
"passport-naver-v2": "^2.0.8",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"typeorm": "^0.3.17"
Expand Down
13 changes: 12 additions & 1 deletion BE/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Body,
Controller,
Get,
HttpCode,
Post,
Req,
Expand All @@ -16,13 +17,23 @@ import {
import { CreateUserDto } from "./dto/users.dto";
import { User } from "./users.entity";
import { GetUser } from "./get-user.decorator";
import { JwtAuthGuard } from "./guard/auth.jwt-guard";
import { Request } from "express";
import { AuthGuard } from "@nestjs/passport";

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

@Get("/naver/callback")
@UseGuards(AuthGuard("naver"))
@HttpCode(201)
async naverSignIn(
@GetUser() user: User,
@Req() request: Request,
): Promise<AccessTokenDto> {
return await this.authService.naverSignIn(user, request);
}

@Post("/signup")
@HttpCode(204)
async signUp(@Body() createUserDto: CreateUserDto): Promise<void> {
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,12 +4,13 @@ import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { JwtStrategy } from "./jwt.strategy";
import { JwtStrategy } from "./strategies/jwt.strategy";
import { PrivateDiaryGuard } from "./guard/auth.diary-guard";
import { TypeOrmModule } from "@nestjs/typeorm";
import { User } from "./users.entity";
import { UsersRepository } from "./users.repository";
import { DiariesRepository } from "src/diaries/diaries.repository";
import { NaverOAuthStrategy } from "./strategies/naver.strategy";

@Module({
imports: [
Expand All @@ -29,6 +30,7 @@ import { DiariesRepository } from "src/diaries/diaries.repository";
UsersRepository,
PrivateDiaryGuard,
DiariesRepository,
NaverOAuthStrategy,
],
exports: [PassportModule, UsersRepository],
})
Expand Down
31 changes: 30 additions & 1 deletion BE/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { User } from "./users.entity";
import { Redis } from "ioredis";
import { InjectRedis } from "@liaoliaots/nestjs-redis";
import { Request } from "express";
import * as jwt from "jsonwebtoken";
import { providerEnum } from "src/utils/enum";

@Injectable()
export class AuthService {
Expand Down Expand Up @@ -87,4 +87,33 @@ export class AuthService {

return new AccessTokenDto(accessToken);
}

async naverSignIn(user: User, request: Request): Promise<AccessTokenDto> {
if (
!(await User.findOne({
where: { userId: user.userId, provider: providerEnum.NAVER },
}))
) {
await user.save();
}
const userId = user.userId;

const accessTokenPayload = { userId };
const accessToken = await this.jwtService.sign(accessTokenPayload, {
expiresIn: "1h",
});

const refreshTokenPayload = {
requestIp: request.ip,
accessToken: accessToken,
};
const refreshToken = await this.jwtService.sign(refreshTokenPayload, {
expiresIn: "24h",
});

// 86000s = 24h
await this.redisClient.set(userId, refreshToken, "EX", 86400);

return new AccessTokenDto(accessToken);
}
}
File renamed without changes.
39 changes: 39 additions & 0 deletions BE/src/auth/strategies/naver.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Injectable, BadRequestException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Profile, Strategy } from "passport-naver-v2";
import { User } from "../users.entity";
import { providerEnum } from "src/utils/enum";

@Injectable()
export class NaverOAuthStrategy extends PassportStrategy(Strategy, "naver") {
constructor() {
super({
clientID: process.env.NAVER_CLIENT_ID,
clientSecret: process.env.NAVER_CLIENT_PASS,
callbackURL: `${process.env.BACKEND_URL}/auth/naver/callback`,
});
}

async validate(
accessToken: string,
refreshToken: string,
profile: Profile,
): Promise<User> {
try {
const { email, id, nickname } = profile;
const user = new User();

user.email = email;
user.userId = id + "*naver";
user.nickname = nickname;
user.password = "naver";
user.provider = providerEnum.NAVER;

return user;
} catch (error) {
throw new BadRequestException(
`네이버 로그인 중 오류가 발생했습니다 : ${error.message}`,
);
}
}
}
8 changes: 5 additions & 3 deletions BE/src/auth/users.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,17 @@ import {
OneToMany,
Unique,
} from "typeorm";
import { premiumStatus } from "src/utils/enum";
import { premiumStatus, providerEnum } from "src/utils/enum";
import { Diary } from "../diaries/diaries.entity";
import { Shape } from "src/shapes/shapes.entity";

@Entity()
@Unique(["userId"])
@Unique(["email"])
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;

@Column({ length: 20 })
@Column({ length: 60 })
userId: string;

@Column()
Expand All @@ -47,6 +46,9 @@ export class User extends BaseEntity {
@DeleteDateColumn({ type: "datetime" })
deletedDate: Date;

@Column({ type: "enum", enum: providerEnum, default: providerEnum.BYEOLSOOP })
provider: providerEnum;

@OneToMany(() => Diary, (diary) => diary.user)
diaries: Diary[];

Expand Down
6 changes: 6 additions & 0 deletions BE/src/utils/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,9 @@ export enum sentimentStatus {
NEUTRAL = "neutral",
ERROR = "error",
}

export enum providerEnum {
BYEOLSOOP = "byeolsoop",
NAVER = "naver",
KAKAO = "kakao",
}

0 comments on commit f3c7b86

Please sign in to comment.