Skip to content

Commit

Permalink
Merge pull request #99 from LocalMingle/dev
Browse files Browse the repository at this point in the history
[완료] 에릭, 종화, 희용 백엔드 머지
  • Loading branch information
kimjonghwa230412 authored Oct 26, 2023
2 parents 115f246 + 39f4ff8 commit bc69f31
Show file tree
Hide file tree
Showing 34 changed files with 545 additions and 668 deletions.
36 changes: 18 additions & 18 deletions src/app.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
// import { Test, TestingModule } from '@nestjs/testing';
// import { AppController } from './app.controller';
// import { AppService } from './app.service';

describe('AppController', () => {
let appController: AppController;
// describe('AppController', () => {
// let appController: AppController;

beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
// beforeEach(async () => {
// const app: TestingModule = await Test.createTestingModule({
// controllers: [AppController],
// providers: [AppService],
// }).compile();

appController = app.get<AppController>(AppController);
});
// appController = app.get<AppController>(AppController);
// });

describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
// describe('root', () => {
// it('should return "Hello World!"', () => {
// expect(appController.getHello()).toBe('Hello World!');
// });
// });
// });
4 changes: 2 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from './prisma/prisma.module';
import { UsersModule } from './users/users.module';
import { EventsModule } from './events/events.module';
Expand All @@ -9,6 +7,8 @@ import { MailModule } from './mails/mail.module';
import { ConfigModule } from '@nestjs/config';
import { DataModule } from './data/data.module';
import { SearchesModule } from './searches/searches.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
imports: [
Expand Down
6 changes: 3 additions & 3 deletions src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
// getHello(): string {
// return 'Hello World!';
// }
}
20 changes: 7 additions & 13 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,20 @@ import {
UseGuards,
Res,
Req,
} from '@nestjs/common'; // Headers 추가
import { AuthService } from './auth.service';
} from '@nestjs/common';
import {
ApiOkResponse,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { LoginDto } from './dto/login.dto';
import { Request, Response } from 'express';
import { AuthEntity } from './entity/auth.entity';
import { UsersService } from 'src/users/users.service';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { Request, Response } from 'express';

interface IOAuthUser {
//interface 설정
user: {
name: string;
email: string;
Expand All @@ -34,10 +32,7 @@ interface IOAuthUser {
@ApiTags('Auth')
@ApiOkResponse({ type: AuthEntity })
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly usersService: UsersService
) {}
constructor(private readonly authService: AuthService) {}
//-----------------------로그인-----------------------------//
@ApiOperation({ summary: '로그인' })
@ApiResponse({ status: 200, description: '로그인에 성공하셨습니다.' })
Expand All @@ -46,8 +41,7 @@ export class AuthController {
@Post('login')
async login(
@Body() { email, password }: LoginDto,
@Req() req: Request,
@Res({ passthrough: true }) res: Response // Response 객체 주입
@Res({ passthrough: true }) res: Response
): Promise<void> {
const { accessToken, refreshToken, userId } = await this.authService.login({
email,
Expand All @@ -60,6 +54,7 @@ export class AuthController {
}

//-----------------------토큰 재발급-----------------------------//
@Post('refresh')
@ApiOperation({ summary: '리프레시 토큰을 사용하여 엑세스 토큰 재발급' })
@ApiResponse({
status: 200,
Expand All @@ -69,7 +64,6 @@ export class AuthController {
status: 401,
description: '리프레시 토큰이 유효하지 않습니다.',
})
@Post('refresh')
async refreshAccessToken(
@Headers('refreshToken') refreshToken: string, // 요청 헤더에서 refresh-token 값을 추출
@Res({ passthrough: true }) res: Response
Expand Down
17 changes: 2 additions & 15 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
import { PrismaService } from './../prisma/prisma.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
//import { IAuthServiceLogin } from './interface/auth-service.interface';
import { UsersService } from 'src/users/users.service';

@Injectable()
Expand All @@ -25,7 +24,7 @@ export class AuthService {
}> {
// 1. 이메일이 일치하는 유저를 DB에서 찾기
const user = await this.usersService.findByEmail({ email });
console.log(user);

// 2. 일치하는 유저가 없으면 에러
if (!user) throw new NotFoundException('이메일이 없습니다.');

Expand All @@ -41,12 +40,10 @@ export class AuthService {

// 4. 리프레시 토큰 생성
const refreshToken = this.setRefreshToken({ user });

// 5. 액세스 토큰 및 리프레시 토큰을 반환
const accessToken = this.getAccessToken({ user });

// 5. 액세스 토큰 및 리프레시 토큰을 반환
res.header('accessToken', accessToken);

res.header('refreshToken', refreshToken);

// 6. DB에 리프레시 토큰을 저장한다.
Expand Down Expand Up @@ -75,7 +72,6 @@ export class AuthService {
{ sub: user.userId },
{ secret: process.env.JWT_REFRESH_KEY, expiresIn: '2w' }
);

return refreshToken;
}

Expand All @@ -92,14 +88,12 @@ export class AuthService {
user: { userId }, // 사용자 ID를 전달
// res: null,
});

return newAccessToken;
}

async OAuthLogin({ req, res }): Promise<{
accessToken: string;
refreshToken: string;
// userId: number;
}> {
// 1. 회원조회
let user = await this.usersService.findByEmail({ email: req.user.email }); // user를 찾아서
Expand All @@ -114,11 +108,8 @@ export class AuthService {
intro: req.user.intro,
profileImg: req.user.profileImg,
};
// console.log('소셜 로그인 회원가입 : ', createUser); // createUser 정보를 콘솔에 출력
user = await this.usersService.create(createUser);
console.log('소셜로그인 회원가입 정보', createUser);
}

// 3. 회원가입이 되어 있다면? 로그인(AT, RT를 생성해서 브라우저에 전송)한다
const accessToken = this.getAccessToken({ user }); // res를 전달
const refreshToken = this.setRefreshToken({ user }); // res를 전달
Expand All @@ -132,7 +123,6 @@ export class AuthService {

console.log('로컬 엑세스 토큰', accessToken);
console.log('로컬 리프레시 토큰', refreshToken);
//console.log(user.userId);
// 리다이렉션
res.redirect(
`http://localhost:5173?accessToken=${encodeURIComponent(
Expand All @@ -141,9 +131,6 @@ export class AuthService {
refreshToken
)}&userId=${encodeURIComponent(user.userId)}`
);
//&userId=${encodeURIComponent(user.userId)}
// return res.redirect('http://localhost:5500');
// return { accessToken, refreshToken };
return { accessToken, refreshToken };
}
}
4 changes: 2 additions & 2 deletions src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ export class LoginDto {
@IsNotEmpty()
@ApiProperty({
description: 'Email',
example: 'test1@naver.com',
example: 'abcd1234@naver.com',
})
email: string;

@IsString()
@IsNotEmpty()
@ApiProperty({
description: 'Password',
example: 'abc123456789!',
example: 'abcd1234!',
})
password: string;
}
1 change: 0 additions & 1 deletion src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
// export class JwtAuthGuard extends AuthGuard('jwt') {}
export class JwtAccessAuthGuard extends AuthGuard('access') {}
export class JwtRefreshAuthGuard extends AuthGuard('refresh') {}
10 changes: 2 additions & 8 deletions src/auth/interface/auth-service.interface.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
// export interface IUsersServiceCreate {
// email: string;
// name: string;
// password: string;
// }

import { User } from '@prisma/client';

export interface IUsersServiceFindByEmail {
Expand All @@ -17,10 +11,10 @@ export interface IAuthServiceLogin {

export interface IAuthServiceGetAccessToken {
user: User;
res: any; // res 매개 변수 추가
res: any;
}

export interface IAuthServiceGetRefereshToken {
user: User;
res: any; // res 매개 변수 추가
res: any;
}
46 changes: 0 additions & 46 deletions src/auth/strategies/jwt-refresh.strategy.ts

This file was deleted.

12 changes: 5 additions & 7 deletions src/auth/strategies/jwt-social-google.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import * as bcrypt from 'bcrypt';
import { PrismaService } from '../../prisma/prisma.service'; // 프리즈마 서비스 파일 경로를 사용하는 경로로 수정해야 합니다.
import { Inject } from '@nestjs/common';

// @Injectable()
export class JwtGoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(
private readonly prisma: PrismaService,
@Inject(PrismaService) private readonly prismaService: PrismaService // 추가
@Inject(PrismaService) private readonly prismaService: PrismaService
) {
super({
clientID: process.env.GOOGLE_CLIENT_ID,
Expand All @@ -18,16 +19,15 @@ export class JwtGoogleStrategy extends PassportStrategy(Strategy, 'google') {
}

async validate(accessToken: string, refreshToken: string, profile: any) {
console.log('google 엑세스토큰:', accessToken);
console.log('google 리프레시 토큰:', refreshToken);
console.log('google 프로필:', profile);
// console.log('google 엑세스토큰:', accessToken);
// console.log('google 리프레시 토큰:', refreshToken);
// console.log('google 프로필:', profile);

// 비밀번호 암호화
const hashedPassword = await bcrypt.hash(profile.id.toString(), 10);

// 고유한 익명 nickname 생성
const nickname = await this.generateUniqueAnonymousName();
//console.log('닉네임 확인', nickname);
return {
name: profile.displayName,
email: profile.emails[0].value,
Expand All @@ -53,8 +53,6 @@ export class JwtGoogleStrategy extends PassportStrategy(Strategy, 'google') {

const anonymousName = `${anonymousPrefix}${randomString}`;

//return anonymousName; // 밑의 로직이 작동안하면 임시적으로 사용

// 프리즈마를 사용하여 중복 확인
const existingUser = await this.prisma.userDetail.findUnique({
where: { nickname: anonymousName },
Expand Down
8 changes: 4 additions & 4 deletions src/auth/strategies/jwt-social-kakao.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ export class JwtKakaoStrategy extends PassportStrategy(Strategy, 'kakao') {
}

async validate(accessToken: string, refreshToken: string, profile: any) {
console.log('카카오에서 주는 accessToken:' + accessToken);
console.log('카카오에서 주는 refreshToken:' + refreshToken);
console.log('카카오 프로필', profile);
console.log(profile._json.kakao_account.email);
// console.log('카카오에서 주는 accessToken:' + accessToken);
// console.log('카카오에서 주는 refreshToken:' + refreshToken);
// console.log('카카오 프로필', profile);
// console.log(profile._json.kakao_account.email);

// 비밀번호 암호화
const hashedPassword = await bcrypt.hash(profile.id.toString(), 10);
Expand Down
8 changes: 4 additions & 4 deletions src/auth/strategies/jwt-social-naver.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ export class JwtNaverStrategy extends PassportStrategy(Strategy, 'naver') {
}

async validate(accessToken: string, refreshToken: string, profile: Profile) {
console.log('네이버에서 주는 accessToken:' + accessToken);
console.log('네이버에서 주는 refreshToken:' + refreshToken);
console.log(profile);
console.log(profile.email);
// console.log('네이버에서 주는 accessToken:' + accessToken);
// console.log('네이버에서 주는 refreshToken:' + refreshToken);
// console.log(profile);
// console.log(profile.email);

// 비밀번호 암호화
const hashedPassword = await bcrypt.hash(profile.id.toString(), 10);
Expand Down
Loading

0 comments on commit bc69f31

Please sign in to comment.