Skip to content

Commit

Permalink
Merge pull request #139 from ldhbenecia/feature/mogaco
Browse files Browse the repository at this point in the history
[Feat] 모각코 로그인 권한 처리 및 API Response 카멜케이스 처리
  • Loading branch information
ldhbenecia authored Nov 22, 2023
2 parents 63def5c + 181491b commit f54444d
Show file tree
Hide file tree
Showing 22 changed files with 120 additions and 197 deletions.
5 changes: 4 additions & 1 deletion app/backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,7 @@ lerna-debug.log*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/extensions.json

# Prisma migrations
/prisma/migrations
3 changes: 2 additions & 1 deletion app/backend/libs/decorators/get-user.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ExecutionContext, createParamDecorator } from '@nestjs/common';
import { Member } from '@prisma/client';

export const GetUser = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
export const GetUser = createParamDecorator((data: unknown, ctx: ExecutionContext): Member => {
const request = ctx.switchToHttp().getRequest();
return request.user;
});
13 changes: 0 additions & 13 deletions app/backend/prisma/migrations/20231111101044_init/migration.sql

This file was deleted.

70 changes: 0 additions & 70 deletions app/backend/prisma/migrations/20231121023456_init/migration.sql

This file was deleted.

This file was deleted.

11 changes: 0 additions & 11 deletions app/backend/prisma/migrations/20231121065729_init/migration.sql

This file was deleted.

This file was deleted.

43 changes: 24 additions & 19 deletions app/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,35 @@ datasource db {

model Member {
id BigInt @id @default(autoincrement()) @db.BigInt
provider_id String @unique @db.VarChar(191)
created_at DateTime @default(now())
social_type String @db.VarChar(191)
providerId String @unique @db.VarChar(191) @map("provider_id")
email String @unique @db.VarChar(191)
socialType String @db.VarChar(191) @map("social_type")
createdAt DateTime @default(now()) @map("created_at")
users GroupToUser[]
members Participant[]
mogacos Mogaco[]
@@map("Member")
}

model Mogaco {
id BigInt @id @default(autoincrement()) @db.BigInt
group_id BigInt @db.BigInt
groupId BigInt @db.BigInt @map("group_id")
memberId BigInt @db.BigInt @map("member_id")
title String @db.VarChar(191)
contents String @db.VarChar(191)
date DateTime @db.DateTime
max_human_count Int @default(1) @db.TinyInt
maxHumanCount Int @default(1) @db.TinyInt @map("max_human_count")
address String @db.VarChar(191)
status String @db.VarChar(191)
created_at DateTime @default(now())
updated_at DateTime? @updatedAt()
deleted_at DateTime? @db.DateTime
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime? @updatedAt() @map("updated_at")
deletedAt DateTime? @db.DateTime @map("deleted_at")
mogacos Participant[]
@@map("Mogaco")
member Member @relation(fields: [memberId], references: [id])
}

model Group {
Expand All @@ -47,23 +52,23 @@ model Group {
}

model GroupToUser {
group_id BigInt @db.BigInt
user_id BigInt @db.BigInt
groupId BigInt @db.BigInt @map("group_id")
userId BigInt @db.BigInt @map("user_id")
@@id([group_id, user_id])
@@id([groupId, userId])
@@map("GroupToUser")
group Group @relation(fields: [group_id], references: [id])
user Member @relation(fields: [user_id], references: [id])
group Group @relation(fields: [groupId], references: [id])
user Member @relation(fields: [userId], references: [id])
}

model Participant {
post_id BigInt @db.BigInt
user_id BigInt @db.BigInt
postId BigInt @db.BigInt @map("post_id")
userId BigInt @db.BigInt @map("user_id")
@@id([post_id, user_id])
@@id([postId, userId])
@@map("Participant")
mogaco Mogaco @relation(fields: [post_id], references: [id])
member Member @relation(fields: [user_id], references: [id])
}
mogaco Mogaco @relation(fields: [postId], references: [id])
member Member @relation(fields: [userId], references: [id])
}
4 changes: 2 additions & 2 deletions app/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ export class AuthController {
const { providerId, socialType, name, email, profilePicture } = user;

const tokens = await this.authService.handleLogin({
provider_id: providerId,
providerId,
email,
nickname: name,
social_type: socialType,
socialType,
profilePicture,
});

Expand Down
2 changes: 1 addition & 1 deletion app/backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ import { AtStrategy, GoogleStrategy, RtStrategy } from './strategies';
imports: [JwtModule.register({})],
controllers: [AuthController],
providers: [AuthService, AuthRepository, PrismaService, GoogleStrategy, AtStrategy, RtStrategy],
exports: [AuthService],
exports: [AuthService, AtStrategy],
})
export class AuthModule {}
17 changes: 9 additions & 8 deletions app/backend/src/auth/auth.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,27 @@ export class AuthRepository {
async saveUser(userDto: CreateUserDto): Promise<Member> {
return this.prisma.member.create({
data: {
provider_id: userDto.provider_id,
social_type: userDto.social_type,
providerId: userDto.providerId,
socialType: userDto.socialType,
email: userDto.email,
},
});
}

async findUserByIdentifier(provider_id: string): Promise<Member | null> {
async findUserByIdentifier(providerId: string): Promise<Member | null> {
return this.prisma.member.findUnique({
where: {
provider_id,
providerId,
},
});
}

async addRefreshToken(provider_id: string, refreshToken: string): Promise<void> {
async addRefreshToken(providerId: string, refreshToken: string): Promise<void> {
const REDIS_MAX_AGE_REFRESH_TOKEN: number = Number(getSecret('REDIS_MAX_AGE_REFRESH_TOKEN'));
await this.cacheManager.set(provider_id, refreshToken, { ttl: REDIS_MAX_AGE_REFRESH_TOKEN } as any);
await this.cacheManager.set(providerId, refreshToken, { ttl: REDIS_MAX_AGE_REFRESH_TOKEN } as any);
}

async removeRefreshToken(provider_id: string): Promise<void> {
await this.cacheManager.del(provider_id);
async removeRefreshToken(providerId: string): Promise<void> {
await this.cacheManager.del(providerId);
}
}
18 changes: 9 additions & 9 deletions app/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export class AuthService {
) {}

async handleLogin(userDto: CreateUserDto): Promise<Tokens> {
const { provider_id } = userDto;
const existingUser = await this.authRepository.findUserByIdentifier(provider_id);
const { providerId } = userDto;
const existingUser = await this.authRepository.findUserByIdentifier(providerId);

if (!existingUser) {
await this.signUp(userDto);
Expand All @@ -39,14 +39,14 @@ export class AuthService {

async signIn(userDto: CreateUserDto): Promise<Tokens | null> {
const token = this.generateJwt({
providerId: userDto.provider_id,
socialType: userDto.social_type,
providerId: userDto.providerId,
socialType: userDto.socialType,
email: userDto.email,
profilePicture: userDto.profilePicture,
nickname: userDto.nickname,
});

await this.authRepository.addRefreshToken(userDto.provider_id, token.refresh_token);
await this.authRepository.addRefreshToken(userDto.providerId, token.refresh_token);
return token;
}

Expand All @@ -57,17 +57,17 @@ export class AuthService {
async refresh(refreshToken: string): Promise<string> {
try {
const decodedRefreshToken = this.jwtService.verify(refreshToken, { secret: getSecret('JWT_REFRESH_SECRET') });
const { provider_id, social_type } = decodedRefreshToken;
const { providerId, socialType } = decodedRefreshToken;

const token = this.generateJwt({ providerId: provider_id, socialType: social_type });
const token = this.generateJwt({ providerId: providerId, socialType: socialType });

return token.access_token;
} catch (error) {
throw new UnauthorizedException('Invalid refresh token');
}
}

async logout(provider_id: string) {
await this.authRepository.removeRefreshToken(provider_id);
async logout(providerId: string) {
await this.authRepository.removeRefreshToken(providerId);
}
}
6 changes: 3 additions & 3 deletions app/backend/src/auth/dto/user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { IsString, IsEmail, MaxLength, MinLength } from 'class-validator';
export class CreateUserDto {
@ApiProperty()
@IsString()
provider_id: string;
providerId: string;

@ApiProperty()
@IsEmail()
Expand All @@ -18,7 +18,7 @@ export class CreateUserDto {

@ApiProperty()
@IsString()
social_type: string;
socialType: string;

@ApiProperty()
@IsString()
Expand All @@ -28,5 +28,5 @@ export class CreateUserDto {
export class LogoutDto {
@ApiProperty()
@IsString()
provider_id: string;
providerId: string;
}
7 changes: 0 additions & 7 deletions app/backend/src/auth/interface/auth.interface.ts

This file was deleted.

15 changes: 12 additions & 3 deletions app/backend/src/auth/strategies/at.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Payload } from '../interface';
import { getSecret } from 'vault';
import { Member } from '@prisma/client';
import { AuthRepository } from '../auth.repository';

@Injectable()
export class AtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor() {
constructor(private authRepository: AuthRepository) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: getSecret('JWT_ACCESS_SECRET'),
});
}

async validate(payload: Payload) {
return payload;
const { providerId } = payload;
const member: Member = await this.authRepository.findUserByIdentifier(providerId);

if (!member) {
throw new UnauthorizedException();
}

return member;
}
}
Loading

0 comments on commit f54444d

Please sign in to comment.