Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/controllers/authControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { generateAccessToken, generateRefreshToken } from './jwtControllers.js';

const prisma = new PrismaClient();

const getKoreaNow = () => {
const now = new Date(); // 현재 UTC 기준 시간
now.setHours(now.getHours() + 9); // 9시간 추가 (UTC → KST 변환)
return now;
};

// 카카오 로그인 페이지로 리디렉션 (프론트에서 하는 작업) (테스트용)
export const redirectToKakaoLogin = (req, res) => {
Expand Down Expand Up @@ -105,12 +110,14 @@ export const handleKakaoUser = async (req, res) => {
const { kakaoAccessToken } = req.body; // 클라이언트에서 받은 액세스 토큰

try {
// 카카오 사용자 정보 가져오기기
// 카카오 사용자 정보 가져오기
const userInfo = await getKakaoUser(kakaoAccessToken);

const { id: userID, kakao_account } = userInfo; // 카카오 사용자 ID 및 계정 정보
const email = kakao_account.email;

const koreaNow = getKoreaNow();

// 데이터베이스에서 사용자 확인 또는 새 사용자 생성
let user = await prisma.user.findUnique({ where: { email } });

Expand Down Expand Up @@ -141,6 +148,8 @@ export const handleKakaoUser = async (req, res) => {
nickname, // 생성된 닉네임
friendCode, // 친구 코드
profileImageUrl: defaultProfileImageUrl, // 기본 프로필 이미지
createdAt: koreaNow,
updatedAt: koreaNow
},
});
}
Expand Down
11 changes: 7 additions & 4 deletions src/controllers/bucketControllers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { PrismaClient } from '@prisma/client';
import momentTime from 'moment-timezone';
import { s3Client } from '../config/s3config.js';

const getKoreaNow = () => {
Expand All @@ -9,15 +8,14 @@ const getKoreaNow = () => {
return now;
};

const koreaNow = getKoreaNow();
// const koreaNow = momentTime().tz("Asia/Seoul").toDate();
const prisma = new PrismaClient();

//버킷리스트 생성
export const createBucket = async (req, res) => {
try {
const userID = req.user.userID;
const { type, content } = req.body;
const koreaNow = getKoreaNow();

if (!type || !content) {
return res.status(400).json({
Expand Down Expand Up @@ -58,6 +56,7 @@ export const uploadAchievementPhoto = async (req, res) => {
try {
const userID = req.user.userID;
const { bucketID } = req.params;
const koreaNow = getKoreaNow();

const bucket = await prisma.bucket.findUnique({ where: { bucketID } });
if (!bucket) {
Expand Down Expand Up @@ -132,6 +131,7 @@ export const activateBucketChallenge = async (req, res) => {
try {
const userID = req.user.userID;
const { bucketID } = req.params;
const koreaNow = getKoreaNow();

const bucket = await prisma.bucket.findUnique({ where: { bucketID } });
if (!bucket) {
Expand Down Expand Up @@ -198,6 +198,7 @@ export const deactivateBucketChallenge = async (req, res) => {
try {
const userID = req.user.userID;
const { bucketID } = req.params;
const koreaNow = getKoreaNow();

const bucket = await prisma.bucket.findUnique({ where: { bucketID } });
if (!bucket) {
Expand All @@ -221,7 +222,7 @@ export const deactivateBucketChallenge = async (req, res) => {

const updated = await prisma.bucket.update({
where: { bucketID },
data: { isChallenging: false },
data: { isChallenging: false, updatedAt: koreaNow },
});

const newCount = await prisma.bucket.count({
Expand Down Expand Up @@ -253,6 +254,7 @@ export const getBucketDetail = async (req, res) => {
try {
const userID = req.user.userID;
const { bucketID } = req.params;
const koreaNow = getKoreaNow();

const result = await prisma.$transaction(async (tx) => {
// 버킷 + 모멘트 가져오기
Expand Down Expand Up @@ -304,6 +306,7 @@ export const updateBucket = async (req, res) => {
const userID = req.user.userID; // JWT 인증 후 주입된 값
const { bucketID } = req.params;
const { content } = req.body;
const koreaNow = getKoreaNow();

// 1) 현재 버킷 조회
const existingBucket = await prisma.bucket.findUnique({
Expand Down
5 changes: 2 additions & 3 deletions src/controllers/feedControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@ const getKoreaNow = () => {
return now;
};

const koreaNow = getKoreaNow();
// const koreaNow = momentTime().tz("Asia/Seoul").toDate();
const prisma = new PrismaClient();

export const getFriendFeed = async (req, res) => {
try {
const userID = req.user.userID;
const friendID = req.params.friendID; // 요청 URL에서 친구 ID 가져오기

const koreaNow = getKoreaNow();

// 1. 친구 관계 확인
const friendRelation = await prisma.friend.findMany({
where: {
Expand Down
16 changes: 12 additions & 4 deletions src/controllers/friendControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@ const getKoreaNow = () => {
return now;
};

const koreaNow = getKoreaNow();
// const koreaNow = moment().tz("Asia/Seoul").toDate();
const prisma = new PrismaClient();


// 사용자 친구 목록 조회
export const getFriends = async (req, res) => {
const userID = req.user.userID;

try {
// 친구 목록 조회
const friends = await prisma.friend.findMany({
Expand Down Expand Up @@ -98,6 +95,7 @@ export const checkFriendCode = async (req, res) => {
export const addFriend = async (req, res) => {
const { friendCode } = req.body;
const requesterID = req.user.userID; // 현재 요청을 보낸 사용자 ID
const koreaNow = getKoreaNow();

// 친구코드가 없는 경우 에러 반환
if (!friendCode) {
Expand Down Expand Up @@ -142,10 +140,12 @@ export const addFriend = async (req, res) => {
{
userID: requesterID,
friendUserID: receiverID,
createdAt: koreaNow,
},
{
userID: receiverID,
friendUserID: requesterID,
createdAt: koreaNow,
},
],
});
Expand All @@ -168,11 +168,13 @@ export const addFriend = async (req, res) => {
userID: requesterID,
type: 'FRIEND',
content: `${friend.nickname}님과 친구가 되었어요!`,
createdAt: koreaNow,
},
{
userID: receiverID,
type: 'FRIEND',
content: `${user.nickname}님과 친구가 되었어요!`,
createdAt: koreaNow,
},
]
});
Expand Down Expand Up @@ -258,6 +260,7 @@ cron.schedule('0 0 * * 1', async () => {
export const knockFriend = async (req, res) => {
const userID = req.user.userID; // 현재 사용자 ID
const { friendUserID } = req.body; // 노크할 친구의 사용자 ID
const koreaNow = getKoreaNow();

try {

Expand Down Expand Up @@ -329,6 +332,7 @@ export const knockFriend = async (req, res) => {
userID: friendUserID,
type: 'KNOCK',
content: `${user.nickname}님이 말해요, 피드가 조용해서 심심하대요!`,
createdAt: koreaNow,
}
});

Expand All @@ -344,6 +348,7 @@ export const cheerOnFriendFeed = async (req, res) => {
const userID = req.user.userID; // 인증된 사용자 ID, 토큰에서 추출
const friendID = req.params.friendId; // URL 파라미터로 받은 친구 ID
const momentID = req.params.momentId; // URL 파라미터로 받은 피드 ID
const koreaNow = getKoreaNow();

try {
// 모멘트 확인
Expand Down Expand Up @@ -391,7 +396,8 @@ export const cheerOnFriendFeed = async (req, res) => {
data: {
userID: userID,
momentID: momentID,
cheer: true
cheer: true,
createdAt: koreaNow,
}
});

Expand All @@ -407,6 +413,7 @@ export const cheerOnFriendFeed = async (req, res) => {
userID: friend.userID,
type: 'CHEER',
content: `${user.nickname}님이 ${friend.nickname}님의 "${moment.content}" 달성을 응원한대요!`,
createdAt: koreaNow,
}
});
}
Expand All @@ -422,6 +429,7 @@ export const cheerOnFriendFeed = async (req, res) => {
export const toggleFriendFix = async (req, res) => {
const userID = req.user.userID; // 현재 사용자 ID
const { friendUserID } = req.body; // 고정할/고정 해제할 친구의 사용자 ID
const koreaNow = getKoreaNow();

try {
// 친구 관계 확인
Expand Down
22 changes: 13 additions & 9 deletions src/controllers/homeControllers.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { PrismaClient } from '@prisma/client';
import moment from 'moment-timezone';

const getKoreaNow = () => {
const now = new Date(); // 현재 UTC 기준 시간
now.setHours(now.getHours() + 9); // 9시간 추가 (UTC → KST 변환)
return now;
};

const prisma = new PrismaClient();

// 홈 당일 모멘트 조회
export const getHome = async (req, res) => {
try {
// 현재 인증된 사용자 정보 가져오기
const userID = req.user.userID; // 현재 사용자 ID
const koreaNow = getKoreaNow();

// 현재 사용자 조회
const currentUser = await prisma.user.findUnique({
Expand All @@ -21,14 +28,12 @@ export const getHome = async (req, res) => {
});
};

const date = moment().tz("Asia/Seoul").toDate();

// 사용자의 moments 조회
const moments = await prisma.moment.findMany({
where: {
userID,
startDate: { lte: date },
endDate: { gte: date }
startDate: { lte: koreaNow },
endDate: { gte: koreaNow }
},
select: {
momentID: true,
Expand Down Expand Up @@ -61,8 +66,8 @@ export const getHome = async (req, res) => {
export const getCompletedMomentsByWeek = async (req, res) => {
try {
const userID = req.user.userID;
const now = moment().tz("Asia/Seoul");
const startOfWeek = now.clone().startOf('isoWeek');
const koreaNow = getKoreaNow();
const startOfWeek = koreaNow.clone().startOf('isoWeek');

const weekDates = [];
for (let i = 0; i < 7; i++) {
Expand Down Expand Up @@ -124,6 +129,7 @@ export const getCompletedMomentsByWeek = async (req, res) => {
export const getConsecutiveCompletedDays = async (req, res) => {
try {
const userID = req.user.userID; // 인증된 사용자 ID
const koreaNow = getKoreaNow();

// 현재 사용자 조회
const currentUser = await prisma.user.findUnique({
Expand All @@ -137,11 +143,9 @@ export const getConsecutiveCompletedDays = async (req, res) => {
});
}

const targetDate = moment().tz("Asia/Seoul").toDate();

// 연속된 isCompleted === true인 날짜 개수를 계산
let consecutiveDays = 1;
let checkDate = moment.tz(targetDate, "Asia/Seoul").toDate();
let checkDate = moment.tz(koreaNow, "Asia/Seoul").toDate();
checkDate.setDate(checkDate.getDate() - 1); // 하루 전부터 검사 시작

while (true) {
Expand Down
7 changes: 1 addition & 6 deletions src/controllers/jwtControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,12 @@ export const generateRefreshToken = (user) => {
// JWT 액세스 토큰 갱신
export const refreshAccessToken = async (req) => {
const refreshToken = req.cookies.refreshToken;
console.log("받은 리프래시 토큰:", refreshToken); // 리프래시 토큰 확인
if (!refreshToken) {
throw new Error('Refresh Token이 필요합니다.');
}

try {
const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
console.log("디코딩된 리프래시 토큰 정보:", decoded); // 디코딩 정보 확인

const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
const user = await prisma.user.findUnique({
where: { id: decoded.userId },
});
Expand All @@ -42,10 +39,8 @@ export const refreshAccessToken = async (req) => {

// 새로운 Access Token 발급
const newAccessToken = generateAccessToken(user);
console.log("새로운 액세스 토큰:", newAccessToken); // 새로운 토큰 확인
return newAccessToken;
} catch (err) {
console.log("리프래시 토큰 검증 실패:", err);
throw new Error('유효하지 않은 Refresh Token입니다.');
}
};
11 changes: 7 additions & 4 deletions src/controllers/momentControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ const getKoreaNow = () => {
return now;
};

const koreaNow = getKoreaNow();
// const koreaNow = momentTime().tz("Asia/Seoul").toDate();
const prisma = new PrismaClient();

// 모멘트 생성 API (예외처리 완료)
Expand All @@ -18,6 +16,7 @@ export const createMoments = async (req, res) => {
const userID = req.user.userID;
const { bucketID } = req.params;
const { startDate, endDate, moments, frequency } = req.body;
const koreaNow = getKoreaNow();

// 1) 요청 검증
if (!Array.isArray(moments) || moments.length === 0) {
Expand Down Expand Up @@ -210,6 +209,8 @@ export const updateMoment = async (req, res) => {
try {
const userID = req.user.userID;
const { momentID } = req.params;
const koreaNow = getKoreaNow();

// 모멘트+버킷 조회
const existingMoment = await prisma.moment.findUnique({
where: { momentID },
Expand Down Expand Up @@ -359,6 +360,7 @@ export const getDetailMoment = async (req, res) => {
export const getChallengingBucketsAndMoments = async (req, res) => {
try {
const userID = req.user.userID;
const koreaNow = getKoreaNow();
// 0) 만료된 버킷 처리 (버킷 ID 찾기)
const expiredBuckets = await prisma.bucket.findMany({
where: {
Expand Down Expand Up @@ -455,7 +457,8 @@ export const getChallengingBucketsAndMoments = async (req, res) => {

export const getChallengingBucketCount = async (req, res) => {
try {
const userID = req.user.userID; // JWT 인증 후, userID 획득
const userID = req.user.userID; // JWT 인증 후, userID 획득

// 1) 현재 유저의 도전 중 버킷 갯수
const challengingCount = await prisma.bucket.count({
where: {
Expand All @@ -468,7 +471,7 @@ export const getChallengingBucketCount = async (req, res) => {
success: true,
challengingCount, // 도전 중 버킷 갯수
});
} catch (error) {
} catch (error) {
console.error('도전 중 버킷 개수 조회 실패:', error);
return res.status(500).json({
success: false,
Expand Down