Skip to content

Commit

Permalink
Merge branch 'dev' into feature/requests
Browse files Browse the repository at this point in the history
  • Loading branch information
grulla99 authored Jul 11, 2024
2 parents 4dff4d5 + fee34e9 commit 2ae18d4
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 52 deletions.
13 changes: 12 additions & 1 deletion src/common/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ switch (process.env.NODE_ENV) {
domain: '.murakano.site',
secure: true,
};
conf.cookieInRefreshTokenDeleteOptions = {
httpOnly: true,
maxAge: 0,
sameSite: 'Lax',
domain: '.murakano.site',
secure: true,
};
conf.envMode = 'prod';
break;
case 'development':
Expand All @@ -54,7 +61,11 @@ switch (process.env.NODE_ENV) {
maxAge: 12 * 60 * 60 * 1000,
sameSite: 'Lax',
};
1;
conf.cookieInRefreshTokenDeleteOptions = {
httpOnly: true,
maxAge: 0,
sameSite: 'Lax',
};
conf.envMode = 'dev';
break;
default:
Expand Down
2 changes: 2 additions & 0 deletions src/common/constants/error-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const ErrorMessage = Object.freeze({
KAKAO_LOGIN_ERROR: '카카오 로그인중 오류가 발생하였습니다.',
NO_REFRESH_TOKEN: 'refresh token이 존재하지 않습니다.',
REFRESH_TOKEN_ERROR: 'refresh token 검증중 오류가 발생하였습니다.',
DELETE_USER_ERROR: '회원탈퇴중 오류가 발생하였습니다.',

// WORD
RECENT_WORDS_ERROR: '최근 검색어 조회중 오류가 발생하였습니다.',
Expand All @@ -41,6 +42,7 @@ const ErrorMessage = Object.freeze({
GET_REQUESTS_ERROR: '요청 조회중 오류가 발생하였습니다.',
DELETE_REQUEST_ERROR: '요청 삭제중 오류가 발생하였습니다.',
UPDATE_REQUEST_STATE_ERROR: '요청 상태 변경중 오류가 발생하였습니다.',
ADD_REQUEST_WORDS_ERROR: '단어는 영어와 기호만 입력할 수 있습니다.',
});

module.exports = ErrorMessage;
2 changes: 1 addition & 1 deletion src/common/constants/success-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ const SuccessMessage = Object.freeze({
LOGIN_SUCCESSS: '로그인 성공',
LOGOUT_SUCCESS: '로그아웃 성공',

DELETE_USER_SUCCESS: '회원 탈퇴 성공',
REFRESH_TOKEN: 'access token 발급 성공',

GET_PROFILE_SUCCESS: '유저 정보 조회 성공',

// WORD - 최근검색어
Expand Down
2 changes: 1 addition & 1 deletion src/common/utils/rateLimit.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ exports.postApiLimiter = rateLimit({

exports.commonLimiter = rateLimit({
windowMs: 60 * 1000, // 1분 간격
max: 50, // windowMs동안 최대 호출 횟수
max: 1000, // windowMs동안 최대 호출 횟수
handler(req, res) {
// 제한 초과 시 콜백 함수
res.status(this.statusCode).json({
Expand Down
51 changes: 33 additions & 18 deletions src/routes/user/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../../common/config');


const userService = require('./user.service');
const sendResponse = require('../../common/utils/response-handler');
const ErrorMessage = require('../../common/constants/error-message');
Expand All @@ -13,6 +12,7 @@ const {
registerBodySchema,
emailCheckReqQuerySchema,
loginBodySchema,
requestBodySchema,
} = require('./user.schema');
const { generateAccessToken, generateRefreshToken } = require('../../common/utils/auth');
const { getKakaoToken, getUserInfo } = require('../../common/utils/kakao');
Expand Down Expand Up @@ -186,7 +186,7 @@ exports.getProfile = (req, res) => {
};

exports.logout = (_, res) => {
res.clearCookie('refreshToken');
res.clearCookie('refreshToken', config.cookieInRefreshTokenDeleteOptions);
return sendResponse.ok(res, {
message: SuccessMessage.LOGOUT_SUCCESS,
});
Expand Down Expand Up @@ -223,23 +223,26 @@ exports.delRecentSearch = async (req, res) => {
// 새로운 단어 등록 및 수정
exports.postWords = async (req, res) => {
try {
const validData = validateRequest(requestBodySchema, req.body);
const { _id } = req.user;
const { nickname } = req.params; // URL 파라미터에서 nickname 추출
const { formData, type } = req.body; // formData와 type을 요청 본문에서 분리

const { nickname } = req.params;
const { formData, type } = req.body;
const result = await userService.postWords(_id, formData, nickname, type);

sendResponse.ok(res, {
message: SuccessMessage.REGISTER_WORDS_SUCCESS,
data: result
data: result,
});
} catch (error) {
console.log("Error during postWords:", error);
console.log('Error during postWords:', error);
if (error?.type === 'ajv') {
return sendResponse.badRequest(res, ErrorMessage.ADD_REQUEST_WORDS_ERROR);
}
sendResponse.fail(req, res, ErrorMessage.REGISTER_WORDS_ERROR);
}
};

exports.UserRequests = async (req, res) => {
try{
try {
const { _id } = req.user;
const requests = await userService.getUserRequests(_id);
sendResponse.ok(res, {
Expand All @@ -253,7 +256,7 @@ exports.UserRequests = async (req, res) => {
};

exports.UserRequestsAll = async (req, res) => {
try{
try {
const requests = await userService.getUserRequestsAll();
sendResponse.ok(res, {
message: SuccessMessage.GET_REQUESTS_SUCCESS,
Expand All @@ -263,10 +266,10 @@ exports.UserRequestsAll = async (req, res) => {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.GET_REQUESTS_ERROR);
}
}
};

exports.deleteRequest = async (req, res) => {
try{
try {
const { _id } = req.user; // 현재 로그인한 사용자의 고유 식별자
const { word } = req.params;
await userService.deleteRequest(_id, word);
Expand All @@ -277,7 +280,7 @@ exports.deleteRequest = async (req, res) => {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.DELETE_REQUEST_ERROR);
}
}
};

exports.getRole = async (req, res) => {
const { _id } = req.user;
Expand All @@ -286,20 +289,20 @@ exports.getRole = async (req, res) => {
message: SuccessMessage.GET_ROLE_SUCCESS,
data: { role },
});
}
};

exports.updateRequest = async (req, res) => {
const { requestId } = req.params;
const { formData } = req.body;
await userService.updateRequest(requestId, formData);
sendResponse.ok(res, {
message: SuccessMessage.UPDATE_REQUEST_SUCCESS
message: SuccessMessage.UPDATE_REQUEST_SUCCESS,
});
}
};

exports.updateRequestState = async (req, res) => {
try {
const { _id} = req.user;
const { _id } = req.user;
const { requestId } = req.params;
const { status, formData, requestType } = req.body;

Expand All @@ -311,5 +314,17 @@ exports.updateRequestState = async (req, res) => {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.UPDATE_REQUEST_STATE_ERROR);
}
}
};

exports.deleteUser = async (req, res) => {
try {
const { _id } = req.user;
await userService.deleteUser(_id);
sendResponse.ok(res, {
message: SuccessMessage.DELETE_USER_SUCCESS,
});
} catch (err) {
console.log(err);
sendResponse.fail(req, res, ErrorMessage.DELETE_USER_ERROR);
}
};
57 changes: 32 additions & 25 deletions src/routes/user/user.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ exports.delRecentSearch = async (_id, searchTerm) => {

exports.updateRecentSearch = async (_id, searchTerm) => {
try {
console.log("id", _id)
console.log("searchTerm", searchTerm)
console.log('id', _id);
console.log('searchTerm', searchTerm);
const user = await User.findById(_id).exec();
if (!user) {
console.log('User not found');
}
const recentSearch = user.recentSearches.find((search) => search.searchTerm === searchTerm);
console.log("recentSearch", recentSearch)
console.log('recentSearch', recentSearch);
if (recentSearch) {
// 검색어가 이미 존재하는 경우
if (recentSearch.deletedAt) {
Expand Down Expand Up @@ -94,7 +94,7 @@ exports.postWords = async (userId, formData, nickname, type) => {
throw new Error('User not found');
}

console.log("User before modification:", JSON.stringify(user.requests, null, 2));
console.log('User before modification:', JSON.stringify(user.requests, null, 2));

if (type === 'add') {
user.requests.push({
Expand All @@ -105,10 +105,10 @@ exports.postWords = async (userId, formData, nickname, type) => {
deletedAt: null,
status: 'pend',
type: 'add',
suggestedBy: nickname // nickname 추가
suggestedBy: nickname, // nickname 추가
});
} else if (type === 'mod') {
const request = user.requests.find(req => req.word === formData.devTerm);
const request = user.requests.find((req) => req.word === formData.devTerm);
if (!request) {
user.requests.push({
word: formData.devTerm,
Expand All @@ -118,8 +118,8 @@ exports.postWords = async (userId, formData, nickname, type) => {
deletedAt: null,
status: 'pend',
type: 'mod',
suggestedBy: nickname // nickname 추가
})
suggestedBy: nickname, // nickname 추가
});
} else {
console.log('이미 같은 단어 수정 요청이 존재합니다.');
throw new Error('Word not found');
Expand All @@ -129,24 +129,23 @@ exports.postWords = async (userId, formData, nickname, type) => {
}

await user.save();
console.log("User after modification:", JSON.stringify(user.requests, null, 2));
return user.requests.find(req => req.word === formData.devTerm);
console.log('User after modification:', JSON.stringify(user.requests, null, 2));
return user.requests.find((req) => req.word === formData.devTerm);
} catch (err) {
console.error(err);
throw err;
}
};

exports.getUserRequests = async (userId) => {
try {
try {
const user = await User.findById(userId).select('requests').exec();
if (!user) {
throw new Error('User not found');
}
// requests 배열에서 deletedAt이 null인 항목만 필터링
const activeRequests = user.requests.filter(request => request.deletedAt === null);
const activeRequests = user.requests.filter((request) => request.deletedAt === null);
return activeRequests;

} catch (err) {
console.error(err);
}
Expand All @@ -157,8 +156,8 @@ exports.getUserRequestsAll = async () => {
const users = await User.find({}, { requests: 1, _id: 0 }); // 모든 유저의 requests 필드만 가져옴
const allRequests = [];

users.forEach(user => {
user.requests.forEach(request => {
users.forEach((user) => {
user.requests.forEach((request) => {
if (request.deletedAt === null) {
allRequests.push(request);
}
Expand All @@ -169,29 +168,29 @@ exports.getUserRequestsAll = async () => {
} catch (err) {
console.error(err);
}
}
};

exports.deleteRequest = async (userId, requestWord) => {
try {
const user = await User.findById(userId).select('requests').exec();
if (!user) {
console.log("사용자를 찾을 수 없음");
console.log('사용자를 찾을 수 없음');
throw new Error('User not found');
}

const request = user.requests.find(req => req.word === requestWord && req.deletedAt === null);
const request = user.requests.find((req) => req.word === requestWord && req.deletedAt === null);
if (request) {
console.log("삭제할 요청 찾음:", request);
console.log('삭제할 요청 찾음:', request);
request.deletedAt = Date.now(); // 요청을 삭제로 표시
await user.save();

console.log("요청 삭제 성공");
console.log('요청 삭제 성공');
} else {
}
} catch (err) {
console.error(err);
}
}
};

exports.getRole = async (userId) => {
try {
Expand All @@ -200,7 +199,7 @@ exports.getRole = async (userId) => {
} catch (err) {
console.error(err);
}
}
};

exports.updateRequest = async (requestId, formData) => {
try {
Expand All @@ -209,7 +208,7 @@ exports.updateRequest = async (requestId, formData) => {
throw new Error('User not found');
}

const request = user.requests.find(req => req._id.toString() === requestId && req.deletedAt === null);
const request = user.requests.find((req) => req._id.toString() === requestId && req.deletedAt === null);
if (request) {
// formData의 각 속성 값으로 request의 해당 속성 값 업데이트
if (formData.addInfo !== undefined) {
Expand All @@ -236,7 +235,7 @@ exports.updateRequest = async (requestId, formData) => {

exports.updateRequestState = async (userId, requestId, status) => {
try {
console.log("updateRequestState 레포진입!!!!!!!!!!!!", userId, requestId, status)
console.log('updateRequestState 레포진입!!!!!!!!!!!!', userId, requestId, status);
const user = await User.findOneAndUpdate(
{ 'requests._id': requestId },
{ $set: { 'requests.$.status': status } },
Expand All @@ -248,7 +247,15 @@ exports.updateRequestState = async (userId, requestId, status) => {
} else {
console.log('Request status updated successfully');
}
} catch (err) {
console.error(err);
}
};

exports.deleteUserById = async (_id) => {
try {
return await User.findByIdAndDelete(_id);
} catch (err) {
console.error(err);
}}
}
};
8 changes: 5 additions & 3 deletions src/routes/user/user.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ const {
updateRequest,
getRole,
updateRequestState,
deleteUser,
} = require('./user.controller');
const { isLoggedIn, isNotLoggedIn, isUser } = require('../../common/utils/auth');
const { isLoggedIn, isNotLoggedIn } = require('../../common/utils/auth');
const userRouter = express.Router();

userRouter.delete('/', isLoggedIn, deleteUser);

// 회원가입
userRouter.post('/register', isNotLoggedIn, register);
userRouter.get('/check/nickname', isNicknameExist);
Expand Down Expand Up @@ -49,8 +52,7 @@ userRouter.get('/role', isLoggedIn, getRole); // 사용자 역할 가져오기
userRouter.delete('/requests/:word', isLoggedIn, deleteRequest); // 사용자 요청 삭제
userRouter.post('/requests/:requestId', isLoggedIn, updateRequest); // 사용자 요청 수정


//요청 상태 변경
//요청 상태 변경
userRouter.post('/requests/:requestId/status', isLoggedIn, updateRequestState); // 사용자 요청 status 변경

module.exports = userRouter;
Loading

0 comments on commit 2ae18d4

Please sign in to comment.