[TIL] Passport (Local)

VonBielefeld·2023년 12월 12일
0

TIL

목록 보기
26/32

설치

npm install passport passport-local

사용 방법

1) 미들웨어에 쿠키 세션 등록

import passport from "passport";
app.use(
  cookieSession({
    name: "cookie-session-name",
    keys: "supersecret",
  })
);
app.use(function (request, response, next) {
  if (request.session && !request.session.regenerate) {
    request.session.regenerate = (cb) => {
      cb();
    };
  }
  if (request.session && !request.session.save) {
    request.session.save = (cb) => {
      cb();
    };
  }
  next();
});

2) 로그인 라우터 구성

app.post("/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) return next(err);
    if (!user) {
      console.log("no user");
      return res.json({ msg: info });
    }

    req.logIn(user, function (err) {
      if (err) return next(err);
      res.redirect("/");
    });
  })(req, res, next);
});

3) 로그인 전략 생성

import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { prisma } from "../utils/prisma/index.js";
import "dotenv/config";

// req.login(user)
passport.serializeUser((user, done) => {
  done(null, user.id);
});
// client => session => request
passport.deserializeUser((id, done) => {
  prisma.users.findUnique({ where: { id: +id } }).then((user) => {
    done(null, user);
  });
});

const LocalStrategyConfig = new LocalStrategy({ usernameField: "email", passwordField: "password" }, async (email, password, done) => {
  const user = await prisma.users
    .findUnique({
      where: { email: email },
    })
    .toJson();
  if (!user) {
    return done(null, false, { msg: `Email ${email} not found` });
  }
  const comparePW = user.password === password;
  if (!comparePW) {
    return done(null, false, { msg: `password not correct` });
  }

  return done(null, user);
});

passport.use("local", LocalStrategyConfig);

1개의 댓글

comment-user-thumbnail
2024년 11월 19일

Obtaining an EU passport with a Company Global Citizen Pass offers an efficient route to European citizenship. This program is designed for individuals seeking to benefit from the privileges of EU residency, including travel, business, and healthcare opportunities. By investing in an eligible company or through specific business ventures, one can gain access to the Global Citizen Pass. This process simplifies the pathway to citizenship by meeting various criteria for investors and entrepreneurs. For more details, including steps and requirements visit https://newsdirect.ng/how-to-get-eu-passport-with-company-global-citizen-pass/.

답글 달기