Skip to content
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

#188 로그인 만료 시간이 너무 짧음 - cookie의 expiry 추가, #428 Redis 연결 실패 시 재시도 추가 #429

Merged
merged 5 commits into from
Nov 9, 2023
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
4 changes: 2 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// 모듈 require
const express = require("express");
const http = require("http");
const { port: httpPort, eventConfig } = require("./loadenv");
const { nodeEnv, port: httpPort, eventConfig } = require("./loadenv");
const logger = require("./src/modules/logger");
const { connectDatabase } = require("./src/modules/stores/mongo");
const { startSocketServer } = require("./src/modules/socket");
Expand All @@ -20,7 +20,7 @@ app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// reverse proxy가 설정한 헤더를 신뢰합니다.
app.set("trust proxy", true);
if (nodeEnv === "production") app.set("trust proxy", 1);

// [Middleware] CORS 설정
app.use(require("./src/middlewares/cors"));
Expand Down
9 changes: 6 additions & 3 deletions loadenv.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
require("dotenv").config({ path: `./.env.${process.env.NODE_ENV}` });

module.exports = {
nodeEnv: process.env.NODE_ENV,
nodeEnv: process.env.NODE_ENV, // required
mongo: process.env.DB_PATH, // required
session: process.env.SESSION_KEY || "TAXI_SESSION_KEY", // optional
session: {
secret: process.env.SESSION_KEY || "TAXI_SESSION_KEY", // optional
expiry: 14 * 24 * 3600 * 1000, // 14일, ms 단위입니다.
},
redis: process.env.REDIS_PATH, // optional
sparcssso: {
id: process.env.SPARCSSSO_CLIENT_ID || "", // optional
Expand Down Expand Up @@ -40,5 +43,5 @@ module.exports = {
slackWebhookUrl: {
report: process.env.SLACK_REPORT_WEBHOOK_URL || "", // optional
},
eventConfig: (process.env.EVENT_CONFIG && JSON.parse(process.env.EVENT_CONFIG))
eventConfig: process.env.EVENT_CONFIG && JSON.parse(process.env.EVENT_CONFIG),
};
30 changes: 7 additions & 23 deletions src/middlewares/session.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,14 @@
const expressSession = require("express-session");
const redis = require("redis");
const MongoStore = require("connect-mongo");
const RedisStore = require("connect-redis")(expressSession);
const {
redis: redisUrl,
mongo: mongoUrl,
session: sessionSecret,
} = require("../../loadenv");
const logger = require("../modules/logger");

// 환경변수 REDIS_PATH 유무에 따라 session 저장 방식이 변경됩니다.
let sessionStore = null;
if (redisUrl) {
const client = redis.createClient({
url: redisUrl,
legacyMode: true,
});
client.connect().catch(logger.error);
sessionStore = new RedisStore({ client });
} else {
sessionStore = MongoStore.create({ mongoUrl });
}
const { nodeEnv, session: sessionConfig } = require("../../loadenv");
const sessionStore = require("../modules/stores/sessionStore");

module.exports = expressSession({
secret: sessionSecret,
secret: sessionConfig.secret,
resave: false,
saveUninitialized: false,
store: sessionStore,
cookie: {
maxAge: sessionConfig.expiry,
secure: nodeEnv === "production",
},
});
7 changes: 4 additions & 3 deletions src/modules/auths/login.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
const { session: sessionConfig } = require("../../../loadenv");
const logger = require("../logger");

const getLoginInfo = (req) => {
if (req.session.loginInfo) {
const { id, sid, oid, name, time } = req.session.loginInfo;
const timeFlow = Date.now() - time;
if (timeFlow > 14 * 24 * 3600 * 1000 /* 14일 */) {
// if (timeFlow > 1 * 3600 * 1000 /* 1시간 */) {
// 14일이 지난 세션에 대해서는 로그인 정보를 반환하지 않습니다.
// 세션은 새로운 요청 시 갱신되지 않습니다.
if (timeFlow > sessionConfig.expiry) {
return { id: undefined, sid: undefined, oid: undefined, name: undefined };
}
req.session.loginInfo.time = Date.now();
return { id, sid, oid, name };
}
return { id: undefined, sid: undefined, oid: undefined, name: undefined };
Expand Down
37 changes: 37 additions & 0 deletions src/modules/stores/sessionStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const expressSession = require("express-session");
const redis = require("redis");
const MongoStore = require("connect-mongo");
const RedisStore = require("connect-redis")(expressSession);
const {
redis: redisUrl,
mongo: mongoUrl,
session: sessionConfig,
} = require("../../../loadenv");
const logger = require("../logger");

const getSessionStore = (redisUrl) => {
// 환경변수 REDIS_PATH 유무에 따라 session 저장 방식이 변경됩니다.
if (redisUrl) {
const client = redis.createClient({
url: redisUrl,
legacyMode: true,
});

// redis client 연결 성공 시 로그를 출력합니다.
client.on("ready", () => {
logger.info("Redis session store is connected!");
});

// redis client 에러 발생 시 1초에 두 번 재연결을 시도합니다.
client.on("error", (err) => {
logger.error(err);
});

client.connect().catch(logger.error);
return new RedisStore({ client, ttl: sessionConfig.expiry });
} else {
return MongoStore.create({ mongoUrl });
}
};

module.exports = getSessionStore(redisUrl);
Loading