세션기반 인증
세션기반 인증 - 로그인
// sever/index.js
const express = require("express");
const cors = require("cors");
const logger = require("morgan");
const session = require("express-session");
const fs = require("fs");
const https = require("https");
const controllers = require("./controllers");
const app = express();
// mkcert에서 발급한 인증서를 사용하기 위한 코드
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const HTTPS_PORT = process.env.HTTPS_PORT || 4000;
// express-session 라이브러리를 이용해 쿠키를 설정
app.use(
session({
secret: "@codestates",
resave: false,
saveUninitialized: true,
cookie: {
domain: "localhost",
path: "/",
sameSite: "none",
httpOnly: true,
secure: true,
},
})
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
const corsOptions = {
origin: "http://localhost:3000",
methods: ["GET", "POST", "OPTIONS"],
credentials: true,
};
app.use(cors(corsOptions));
app.post("/login", controllers.login);
app.post("/logout", controllers.logout);
app.get("/userinfo", controllers.userInfo);
let server;
if (fs.existsSync("./key.pem") && fs.existsSync("./cert.pem")) {
const privateKey = fs.readFileSync(__dirname + "/key.pem", "utf8");
const certificate = fs.readFileSync(__dirname + "/cert.pem", "utf8");
const credentials = {
key: privateKey,
cert: certificate,
};
server = https.createServer(credentials, app);
server.listen(HTTPS_PORT, () => console.log(`🚀 HTTPS Server is starting on ${HTTPS_PORT}`));
} else {
server = app.listen(HTTPS_PORT, () => console.log(`🚀 HTTP Server is starting on ${HTTPS_PORT}`));
}
module.exports = server;
// server/login.js
const {USER_DATA} = require("../../db/data");
module.exports = (req, res) => {
const {userId, password} = req.body.loginInfo;
const {checkedKeepLogin} = req.body;
const userInfo = {
...USER_DATA.filter((user) => user.userId === userId && user.password === password)[0],
};
if (!userInfo.id) {
res.status(401).send("Not Authorized");
} else if (checkedKeepLogin) {
req.session.sessionId = userInfo.id;
req.session.cookie.maxAge = 1000 * 60 * 30;
res.redirect("/userinfo");
} else {
req.session.sessionId = userInfo.id;
res.redirect("/userinfo");
}
};
// server/logout.js
module.exports = (req, res) => {
const cookiesOption = {
domain: "localhost",
path: "/",
httpOnly: true,
sameSite: "none",
secure: true,
};
req.session.destroy();
res.status(205).clearCookie("connect.sid", cookiesOption).send("Logged Out Successfully");
};
// server/userInfo.js
const {USER_DATA} = require("../../db/data");
module.exports = (req, res) => {
const sessionId = req.session.sessionId;
const userInfo = {
...USER_DATA.filter((user) => user.id === sessionId)[0],
};
if (!sessionId || !userInfo.id) {
res.status(401).send("Not Authorized");
} else {
delete userInfo.password;
res.send(userInfo);
}
};