【问题标题】:How to use PassportJS in Express with Routing Parameters?如何在 Express 中使用带有路由参数的 PassportJS?
【发布时间】:2020-03-20 23:50:16
【问题描述】:

目前,我正在为我的最后一年项目开发一个由 Node and Express (JS) 和 MongoDB 提供支持的 Web 应用程序。我正在学习并同时尝试实现各种功能。我的学习曲线很长。如能考虑,将不胜感激。

我一直在尝试仅为所有注册用户创建用户配置文件

我想要达到的目标是:

1) 当有人使用如下路由参数时:

app.get("/users/:username", function(req,res) {
  //Code
});

我希望仅当用户通过身份验证时请求才能成功 - PassportJS(本地策略)。

2) 如果他们只尝试点击 /user 路径 - 那么它应该显示未经授权。

3) 当他们登录时,它应该通过路径向他们显示页面 - /users/{username}/map

注意:地图只是另一个 .ejs 文件。

P.S:我尝试了各种方法,但无法在此处全部列出,以下是我当前的代码:

//jshint esversion:6
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const mongoose = require("mongoose");
const encrypt = require("mongoose-encryption");

//For Sessions and Cookies
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");


app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended:true
}));


//Initializing Sessions
app.use(session({
  secret: "Hrishikesh",
  resave: false,
  saveUninitialized: false
}));

//Initializing Passport
app.use(passport.initialize());

//Using Passport to deal with sessions
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/dunzoUserDB" , { useUnifiedTopology: true , useNewUrlParser: true });
mongoose.set("useCreateIndex", true);

//Schema for Users
const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  username: String
});

//Passport-local-mongoose ----> To be modified in Schema
userSchema.plugin(passportLocalMongoose); //Used to hash & salt password and also to save our Users into our MongoDB


//Model
const User = mongoose.model("User", userSchema);

//Functions of Passport Local Mongoose to serialize and De-serialize cookies and information within them.
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get("/", function(req,res) {
  res.render("index");
});

app.get("/login", function(req,res) {
  res.render("login");
});

app.get("/register", function(req,res) {
  res.render("register");
});

app.get("/map", function(req, res) {
  if(req.isAuthenticated()) {
    res.render("map");
  } else {
    res.redirect("/login");
  }

});





app.post("/register", function(req, res) {

//We will be using Passport-local-mongoose for all registration and authentication as a middleman for us
User.register({username: req.body.username}, req.body.password, function(err, user) {
  if (err) {
    console.log(err);
    res.redirect("/register")
  } else {
    //If registered successfully, perform LOCAL Authentication - Nothing to UNDERSTAND here
    passport.authenticate("local")(req, res, function(){
        res.redirect("/login");
    });
  }
})

});

app.post("/login", function(req,res) {
const user = new User({
  username: req.body.username,
  password: req.body.password
});

//Login method from Passport
req.login(user, function(err) {
  if (err) {
    console.log(err);
    res.redirect("login");
  } else {
    passport.authenticate("local",) (req, res, function(){
        res.redirect("/map");
      });
  }
})
});

app.get('/logout',
  function(req, res){
    req.logout();
    res.redirect('/');
  });



app.listen(3000, function(){
  console.log("Server started on Port 3000");
});

【问题讨论】:

    标签: node.js mongodb express passport.js


    【解决方案1】:

    我不熟悉使用 session 或 passport-local-mongoose,因为我只使用过 JWT,但我在我的应用程序中做了类似的事情:

    app.js

    var passport = require('passport');
    var LocalStrategy = require('passport-local').Strategy;
    var AnonymousStrategy = require('passport-anonymous').Strategy;
    
    passport.use(new LocalStrategy(User.authenticate()));
    passport.use(new AnonymousStrategy());
    
    app.use(passport.authenticate(['local', 'anonymous'], { /* any options you want */ })
    

    以上内容将确保您的应用可以将用户识别为实际用户或匿名用户。

    然后为了保护需要登录用户的端点,我编写了如下中间件

    function validateUser(req, res, next) {
      if (req.isAuthenticated()) {
        next();
      } else {
        // Error stuff
        res.redirect('/login')
      }
    

    然后保护端点:

    app.get("/map", validateUser, function(req, res) {
      res.render("map");
    });
    

    app.get("/user", validateUser, function(req, res) {
      res.render("profile", { user: req.user });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 2020-06-16
      • 2017-10-02
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多