2 글 보임 - 1 에서 2 까지 (총 2 중에서)
-
글쓴이글
-
2023년 8월 2일 04:24 #93132
이지환참가자react에서 axios요청으로 node서버에서 로그인 처리 과정중에 세션은 만들어지는데 MongoStore로 세션을 저장하려고 아래 코드처럼 썼는데 로그인 성공했을때 세션은 만들어지고, 연결도 정상적으로 되는데 몽고쪽으로 데이터가 넘어가지 않는 이유가 뭘까요? 코드입니다. 위에 라이브러리 불러오는 부분과 mongoose 연결 cors는 다 되어있고 생략했습니다.
// express-session 설정 app.use( session({ secret: process.env.SECRETKEY, // 세션 암호화에 사용될 비밀키 resave: false, saveUninitialized: false, store: MongoStore.create({ mongoUrl: process.env.DB_URL }), // cookie: { // // maxAge: 1000 * 60 * 60 * 24, // 세션 쿠키의 유효시간 24시간 // httpOnly: false, // 클라이언트 스크립트에서 쿠키에 접근하지 못하도록 설정 // secure: true, // 배포 환경에서는 true로 설정 (HTTPS에서만 쿠키 전송) // }, }) );
// Passport 초기화 및 세션 지원 app.use(passport.initialize()); app.use(passport.session());
// Passport LocalStrategy 설정 passport.use( new LocalStrategy( { usernameField: 'username', passwordField: 'password', session: true, //(요기는 세션을 만들건지) }, async (username, password, done) => { try { // 사용자 정보를 데이터베이스에서 조회 const adminUser = await AdminUser.findOne({ username: username }); if (!adminUser) { // 사용자가 존재하지 않을 경우 return done(null, false, { message: '존재하지 않는 사용자입니다.' }); }
// 비밀번호 비교 (bcrypt.compare를 사용하여 저장된 암호화된 비밀번호와 비교) const isPasswordValid = await bcrypt.compare(password, adminUser.password);
if (!isPasswordValid) { // 비밀번호가 일치하지 않을 경우 return done(null, false, { message: '비밀번호가 일치하지 않습니다.' }); }
// 로그인 성공, 사용자 정보를 done 콜백 함수에 전달하여 인증 성공을 알림 return done(null, adminUser); } catch (error) { console.error('로그인 에러:', error); return done(error); } } ) ); //세션만들기 passport.serializeUser(function (user, done) { done(null, user.username) });
passport.deserializeUser(function (user, done) { done(null, {}) });
// 라우트 설정 app.post('/api/adminlogin', (req, res, next) => { passport.authenticate('local', (err, user, info) => { if (err) { return res.status(500).json({ error: '로그인 중 오류가 발생했습니다.' }); } if (!user) { // 사용자 인증 실패 return res.json({ success: false, message: info.message }); } // 쇼핑몰을 구분하는 정보 (예: 쇼핑몰 ID 또는 이름) const mallIdentifier = user.businessName; // 이 부분은 사용자 데이터베이스에서 쇼핑몰 식별자를 가져오는 방식에 따라 달라질 수 있습니다. const adminNumber = user.adminNumber; const adminUse = user.adminUse; const adminName = user.username; console.log(user);
// 로그인 성공 시 세션에 사용자 정보 저장 (req.session에 저장) req.session.user = adminName; req.session.isAdmin = adminNumber; req.session.adminUse = adminUse; req.session.mallIdentifier = mallIdentifier;
console.log(req.session) req.session.save()
return res.json({ success: true, message: '로그인 성공' }); })(req, res, next); });
// 기타 라우트 등록 및 서버 실행 코드 // ...
-
글쓴이글
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
- 답변은 로그인 후 가능합니다.