Passport를 이용해 "가장 기본적인" 로그인 기능 구현.
const passport = require("passport");
const session = require("express-session");
app.use(
session({ secret: "비밀코드", resave: true, saveUninitialized: false })
);
app.use(passport.initialize());
app.use(passport.session());
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
router.post(
"/login",
passport.authenticate("local", { failureRedirect: "/fail" }),
function (req, res) {
res.redirect("/");
}
);
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
session: true,
passReqToCallback: false,
},
async function (email, password, done) {
console.log(email, password);
try {
const result = await user.findOne({
where: { email: email, password: password },
});
if (!result)
return done(null, false, { message: "존재하지않는 아이디요" });
if (email == result.password) {
return done(null, result);
} else {
return done(null, false, { message: "비번틀렸어요" });
}
} catch (err) {
return done(err);
}
}
)
);
passport.serializeUser(function (user, done) {
console.log("serializeUser ", user);
done(null, user.user_id);
});
passport.deserializeUser(async function (id, done) {
console.log("deserializeUser id ", id);
var userinfo = await user.findOne({
where: { user_id: id },
});
done(null, userinfo);
});
function checkLogin(req, res, next) {
if (req.user) {
console.log("login checked");
next();
} else {
console.log("login first");
res.send("로그인 안하셨는데요?");
}
}
router.put("/user/:user_id", checkLogin, async (req, res) => {
const { user_id } = req.params;
const { email, password, nickname } = req.body;
try {
await user.update(
{
email,
password,
nickname,
},
{
where: { user_id },
}
);
res.status(200).send({
ok: true,
});
} catch (err) {
console.error(err);
res.status(400).send({
ok: false,
message: `${err}`,
});
}
});