Skip to content

Commit

Permalink
Merge pull request #429 from sparcs-kaist/#188.3-set-session-expiry
Browse files Browse the repository at this point in the history
  • Loading branch information
withSang authored Nov 9, 2023
2 parents f03e0a1 + 6c1c9c6 commit d4893b0
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 31 deletions.
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);

0 comments on commit d4893b0

Please sign in to comment.