返回

javascript-我该如何处理由 passport.js 创建的这个“会话”?

发布时间:2022-07-05 03:40:51 232
# 前端

我正在实现用户身份验证,一旦他们通过身份验证,他们就可以在数据库中积垢他们的用户数据。我目前可以对用户进行身份验证,并让用户注册一个新帐户,但我不确定下一步该怎么做。一旦我的用户通过身份验证,我的节点服务器应该传递回我的前端什么?我到处都读到我打算使用令牌和会话来检查用户是否对每个请求都具有身份验证。

Auth.js

const router = express.Router()
const passport = require("passport")


router.post("/login", (req, res, next) => {
    passport.authenticate("local", function(err, user, info) {
        console.log(user)
        if(err){
            return res.status(400).json({errors: err})
        }
        if(!user){
            return res.status(400).json({errors: "Incorrect username or password"})
        }
        //figure out what this does 
        req.logIn(user, function(err){
            if(err){
                return res.status(400).json({errors: err});
            }
            return res.status(200).json({success: `Logged in ${user.id}`})
        })

    })(req, res, next)
})

module.exports = router 

Setup.js(适用于护照J)

const bcrypt = require("bcrypt")
const User = require('../models/user')
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;

passport.serializeUser((user, done) => {
    done(null, user.id)
})

passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user);
    })
})

passport.use(
    new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
        //Match user
        User.findOne({ email: email })
            .then(user => {
                //match password
                bcrypt.compare(password, user.password, (err, isMatch) => {
                    if (err) throw err;
                    if (isMatch) {
                        console.log("successfully auth")
                        return done(null, user);
                    } else {
                        console.log("incorrect password ")
                        return done(null, false, { message: "Incorrect Password" })
                    }
                })

            })
            .catch(err => {
                console.log("no account found")
                return done(null, false, { message: err })
            })
    })
)
module.exports = passport

index.js

require('dotenv').config()
const express = require('express');
const session = require('express-session');
const mongoose = require("mongoose")
const MongoStore = require("connect-mongo")
const cors = require("cors");
const axios = require('axios');
const User = require('./models/user')
const bcrypt = require('bcrypt')

const passport = require("./passport/setup")
const auth = require("./routes/auth")


const app = express();
app.use(cors());
let port = process.env.PORT;
if (port == null || port == "") {
  port = 5000;
}

mongoose.connect(process.env.ATLAS_URI).then(console.log("MongoDB Connection Success")).catch(err => console.log("MongoDB Connection Failed" + err))
// For backend and express init
app.use(express.json());
app.use(express.urlencoded({ extended: false }))

app.use(session({
  secret: 'random secret',
  resave: false,
  saveUninitialized: true,
  store: MongoStore.create({ mongoUrl: process.env.ATLAS_URI }),
}));


app.use(passport.initialize())
app.use(passport.session())

app.use("/auth", auth)

app.post('/register', (req, res) => {
  const email = req.body.email
  const plainTextPassword = req.body.password;

  //check if user already exists 
  User.find({ name: email }, (err, existingUser) => {
    if (existingUser.length === 0) {
      bcrypt.hash(plainTextPassword, 8, async (err, hash) => {
        try {
          const user = new User({
            email: email,
            password: hash
          });
          let result = await user.save();
          if (result) { 
            console.log("account registered successfully")
            res.send(result)
          }

        } catch (e) {
          res.send("Something Went Wrong");
          console.log("something went wrong ---" + e)
        }
      })
    } else {
      console.log("user account already exists! Login instead. ")
    }
  })

})

我不想调试错误,只需要知道方法是什么。基本上,我希望用户登录一次,然后能够在web应用程序和crud周围导航到他们的数据库。非常感谢。

我的会话存储在mongodb中的另一个集合中,但idk如何处理它

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像