-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/mission 09/제로 #65
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
Open
jeongkyueun
wants to merge
11
commits into
제로/main
Choose a base branch
from
feature/mission-09/제로
base: 제로/main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
The head ref may contain hidden characters: "feature/mission-09/\uC81C\uB85C"
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d29c106
refactor: 7주차 미션 피드백 반영
jeongkyueun 49394d6
feat: 8주차 워크북 실습 완료
jeongkyueun 3512fd6
feat: 스웨거 접속 완료
jeongkyueun 291a69e
feat: 8주차 워크북 실습 최종 완료
jeongkyueun 87a81bb
feat: 8주차 미션/ Swagger 문서화
jeongkyueun d697c91
refactor: 8주차 미션 피드백 반영
jeongkyueun 8455c92
feat: 9주차 실습1 완료
jeongkyueun dafc720
feat: 9주차 미션1 사용자 정보 접근 시 하드코딩 제거 및 동적 조회 로직 적용
jeongkyueun 47df8a2
feat: 9주차 미션2 인증된 사용자 정보 갱신을 위한 PATCH /users/me API 추가
jeongkyueun afb56fd
feat: 9주차 미션3 JWT 인증 시스템을 주요 API에 적용하여 접근 보호 강화
jeongkyueun e79aa37
docs: 영어 문서/설명 한글 번역 추가
jeongkyueun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| import dotenv from "dotenv"; | ||
| import { Strategy as GoogleStrategy } from "passport-google-oauth20"; | ||
| import { prisma } from "./db.config.js"; | ||
| import jwt from "jsonwebtoken"; // JWT 생성을 위해 import | ||
|
|
||
| dotenv.config(); | ||
| const secret = process.env.JWT_SECRET; // .env의 비밀 키 | ||
|
|
||
| export const generateAccessToken = (user) => { | ||
| return jwt.sign( | ||
| { id: user.id, email: user.email }, | ||
| secret, | ||
| { expiresIn: '1h' } | ||
| ); | ||
| }; | ||
|
|
||
| export const generateRefreshToken = (user) => { | ||
| return jwt.sign( | ||
| { id: user.id }, | ||
| secret, | ||
| { expiresIn: '14d' } | ||
| ); | ||
| }; | ||
|
|
||
|
|
||
| // GoogleVerify | ||
| const googleVerify = async (profile) => { | ||
| const email = profile.emails?.[0]?.value; | ||
| if (!email) { | ||
| throw new Error(`profile.email was not found: ${profile}`); | ||
| } | ||
|
|
||
| const user = await prisma.user.findFirst({ where: { email } }); | ||
| if (user !== null) { | ||
| return { id: user.id, email: user.email, name: user.name }; | ||
| } | ||
|
|
||
| const created = await prisma.user.create({ | ||
| data: { | ||
| email, | ||
| name: profile.displayName, | ||
| gender: "추후 수정", | ||
| birth: new Date(1970, 0, 1), | ||
| address: "추후 수정", | ||
| detailAddress: "추후 수정", | ||
| phoneNumber: "추후 수정", | ||
| }, | ||
| }); | ||
|
|
||
| return { id: created.id, email: created.email, name: created.name }; | ||
| }; | ||
|
|
||
| // GoogleStrategy | ||
|
|
||
| export const googleStrategy = new GoogleStrategy( | ||
| { | ||
| clientID: process.env.PASSPORT_GOOGLE_CLIENT_ID, | ||
| clientSecret: process.env.PASSPORT_GOOGLE_CLIENT_SECRET, | ||
| callbackURL: "/oauth2/callback/google", | ||
| scope: ["email", "profile"], | ||
| }, | ||
|
|
||
|
|
||
| async (accessToken, refreshToken, profile, cb) => { | ||
| try { | ||
|
|
||
| const user = await googleVerify(profile); | ||
|
|
||
|
|
||
| const jwtAccessToken = generateAccessToken(user); | ||
| const jwtRefreshToken = generateRefreshToken(user); | ||
|
|
||
|
|
||
|
|
||
| return cb(null, { | ||
| accessToken: jwtAccessToken, | ||
| refreshToken: jwtRefreshToken, | ||
| }); | ||
|
|
||
| } catch (err) { | ||
| return cb(err); | ||
| } | ||
| } | ||
| ); | ||
|
|
||
| import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'; | ||
|
|
||
| const jwtOptions = { | ||
| // 요청 헤더의 'Authorization'에서 'Bearer <token>' 토큰을 추출 | ||
| jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
| secretOrKey: process.env.JWT_SECRET, | ||
| }; | ||
|
|
||
| export const jwtStrategy = new JwtStrategy(jwtOptions, async (payload, done) => { | ||
| try { | ||
| const user = await prisma.user.findFirst({ where: { id: payload.id } }); | ||
|
|
||
| if (user) { | ||
| return done(null, user); | ||
| } else { | ||
| return done(null, false); | ||
| } | ||
| } catch (error) { | ||
| return done(error, false); | ||
| } | ||
| }); | ||
|
|
||
| /** | ||
| * JWT 인증 미들웨어 | ||
| * 인증이 필요한 라우트에 사용 | ||
| */ | ||
| export const authenticateJWT = (req, res, next) => { | ||
| return passport.authenticate('jwt', { session: false }, (err, user, info) => { | ||
| if (err) { | ||
| console.error('JWT 인증 오류:', err); | ||
| return res.status(500).json({ | ||
| success: false, | ||
| message: '인증 처리 중 오류가 발생했습니다.' | ||
| }); | ||
| } | ||
|
|
||
| if (!user) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: '로그인이 필요합니다.' | ||
| }); | ||
| } | ||
|
|
||
| // 인증된 사용자 정보를 req.user에 저장 | ||
| req.user = user; | ||
| next(); | ||
| })(req, res, next); | ||
| }; | ||
|
|
||
| /** | ||
| * 관리자 권한 확인 미들웨어 | ||
| * 관리자만 접근 가능한 라우트에 사용 | ||
| */ | ||
| export const requireAdmin = (req, res, next) => { | ||
| // authenticateJWT 미들웨어를 먼저 통과해야 함 | ||
| if (!req.user) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: '인증이 필요합니다.' | ||
| }); | ||
| } | ||
|
|
||
| // 여기서는 간단히 isAdmin 플래그로 관리자 여부를 확인 | ||
| // 실제 구현에서는 사용자 역할(role)을 확인하는 로직으로 대체해야 함 | ||
| if (req.user.isAdmin) { | ||
| return next(); | ||
| } | ||
|
|
||
| return res.status(403).json({ | ||
| success: false, | ||
| message: '관리자 권한이 필요합니다.' | ||
| }); | ||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
prisma 스키마에서 제로가 정의한 gender는 enum이 아니라 string이에요! String이라 오류는 나지 않지만 서비스 로직 전체가 Male, Female, Other 형태로 가는데 Google 유저만 문자열 형태가 다릅니다! 이 경우에는 updateUser나 responseDTO에서 불일치 가능성이 높아요!
그리고 preferences도 하나도 안 만들어지고 잇어요!
1.Google 생성시 모든 기본 값을 회원가입과 동일한 형식으로 맞춰야하고
2. preferences =[] 초기화도 필요해요!
3. gender를 enum처럼 관리할거라면 변환도 필요하겠죠!