如何在单个快速路由 User.route('/').get((req,res,next)=>{ }) 上添加两个身份验证?

问题描述

我有两个passport-jwt认证

  1. 验证用户
  2. 验证合作伙伴

我希望我的合作伙伴添加的地点可供用户以及基于身份验证的合作伙伴访问。

这里是我使用的一些代码,但它是未经授权的响应:

路线: 伙伴路由.js

const bodyParser=require('body-parser');
const Partner=require('../model/partner');
const Place=require('../model/place');
const auth=require('../authentication/auth');
const permission=require('../authentication/verifypermission');
const place = require('../model/place');

const partnerRouter=express.Router();
partnerRouter.use(bodyParser.json());

partnerRouter.route('/login')
.post((req,res,next)=>{
   Partner.findOne({email:req.body.email})
   .then((data)=>{
       if(auth.authenticate(req.body.password,data.hash_password))
       {
           res.end(auth.getToken({_id: data._id}));
       }
   })
   .catch((err)=>{
       console.log(err);
   })
});
partnerRouter.route('/register')
.post((req,next)=>{
    Partner.findOne({email:req.body.email})
   .then((data)=>{
       if(data)
       {
            res.end('Partner already exist with Email '+req.body.email);
       }
       else
       {
            Partner.findOne({contact:req.body.contact})
            .then((data)=>{
                if(data)
                {
                    res.end('Partner already exist with Contact '+req.body.contact);
                }
                else{
                    Partner.create(req.body)
                    .then((data)=>{
                            res.json({"Message":"Partner Successfully Created."})
                    })
                    .catch((err)=>{
                        console.log(err);
                    });
                }
            })
            .catch((err)=>{
                console.log(err);
            });
       }
   })
   .catch((err)=>{
       console.log(err);
   });

});

partnerRouter.route('/places/:partnerid')
.get(auth.verifyPartner,auth.verifyUser,(req,next)=>{
    permission.verifyPermission(req.user._id,req.params.partnerid,(err,data)=>{ // verifyPermission just use to check role of users.
        if(err)
        {
            console.log(err);
        }
        if(data=='Permission_granted')
        {
            place.find({partner_id:req.params.partnerid})
            .then((data)=>{
                res.json(data);
            })
            .catch((err))
        }
        else{
            res.end(data)
        }
    })
})
module.exports=partnerRouter;

userRoute.js

const express=require('express');
const bodyParser=require('body-parser');
const User=require('../model/user');
const User_detail=require('../model/user_detail');
const auth=require('../authentication/auth');
const permission=require('../authentication/verifypermission');

const usersRouter = express.Router();

usersRouter.use(bodyParser.json());

usersRouter.route('/login')
.post((req,next) => {
   User.findOne({ email: req.body.email })
   .then((userdata)=>{
        if(userdata)
        {
            if(auth.authenticate(req.body.password,userdata.hash_password))
            {                      
                res.end(auth.getToken({_id: userdata._id}));
            }
            else{
                res.end("Password Missmatch")
            }   
        }
        else
        {
            res.end("Check your email address");
        }
   })
   .catch((err)=>{
       console.log(err);
   })
}); 

usersRouter.route('/register')
.post((req,next)=>{
    User.findOne({email: req.body.email})
    .then((data)=>{
            if(data)
            {   
                res.end("User Already Exist with email: "+req.body.email);
            }
            else
            {
            User.findOne({contact: req.body.contact})
            .then((data)=>{
                if(data){
                    res.end("User Already Exist with contact number: "+req.body.contact)
                }
                else
                {
                    if(req.body.password)
                    {
                        req.body.hash_password=auth.encryptPassword(req.body.password);
                    }
                    User.create(req.body)
                    .then((data)=>{
                        res.json({"message": "user Successfully created"});
                    })
                    .catch((err)=>{
                        console.log(err);
                    })
                }
            })
        }
    })
    .catch((err)=>{
        console.log(err);
    });
});

module.exports= usersRouter;

身份验证 auth.js

const jwt=require("jsonwebtoken");
const bcrypt=require("bcrypt");
// const passport=require('passport');
var Passport = require('passport').Passport,passport = new Passport(),partnerPassport = new Passport();
const ExtractJwt=require('passport-jwt').ExtractJwt;
const JwtStrategy=require('passport-jwt').Strategy;
const User=require("../model/user");
const Partner = require("../model/partner");

module.exports.getToken = function(user) {
    return jwt.sign(user,'12345-67890-09876-54321',{expiresIn: 3600});
};
module.exports.encryptPassword = function(password) {
    return bcrypt.hashSync(password,10);
};
module.exports.authenticate = function(password,hash_password) {
    return bcrypt.compareSync(password,hash_password);
};

var opts={}
    opts.secretorKey = '12345-67890-09876-54321';
    opts.jwtFromrequest = ExtractJwt.fromAuthHeaderAsBearerToken();

module.exports.Jwtpassport=passport.use(new JwtStrategy(opts,function(jwt_payload,done){
        // console.log("JWT payload: ",jwt_payload);
        User.findOne({_id: jwt_payload._id},function(err,userdata){
            if(err)
            {
                return done(err,false);
            }
            if(userdata)
            {
                return done(null,userdata);
            }
            else
            {
                return done(null,false);
            }
        })

}))

module.exports.Jwtpartnerpassport=partnerPassport.use(new JwtStrategy(opts,jwt_payload);
        Partner.findOne({_id: jwt_payload._id},partnerdata){
            if(err)
            {
                return done(err,false);
            }
            if(partnerdata)
            {
                return done(null,partnerdata);
            }
            else
            {
                return done(null,false);
            }
        })
}))

module.exports.verifyUser = passport.authenticate('jwt',{session: false});
module.exports.verifyPartner = partnerPassport.authenticate('jwt',{session: false});

型号 用户.js

const mongoose=require('mongoose');
const bcrypt=require('bcrypt');

const userSchema= new mongoose.Schema({
    firstname:
    {
        type:String,require: true,trim:true,min:3,max:15
    },lastname:
    {
        type:String,email:
    {
        type:String,unique:true,lowercase:true
    },contact:
    {
        type:String,unique:true
    },hash_password:
    {
        type:String,require:true
    },role:
    {
        type:String,enum:['user','admin'],default:'user'
    },profile_picture:
    {
        type:String
    },status:
    {
        type:Boolean,default:1
    }

},{ timestamps:true });

userSchema.virtual('password')
.set(function(password){
    this.hash_password=bcrypt.hashSync(password,10);
});

module.exports = mongoose.model('User',userSchema); 

partner.js

const mongoose=require('mongoose');
const bcrypt=require('bcrypt');

const partnerSchema=mongoose.Schema({
    firstname:
    {
        type:String,email:{
        type:String,contact:{
        type:String,hash_password:{
        type:String,default:1
    }
},{ timestamps:true });

partnerSchema.virtual('password')
.set(function(password){
    this.hash_password=bcrypt.hashSync(password,10);
});

module.exports=mongoose.model("Partner",partnerSchema)

place.js

const mongoose=require('mongoose')

const placeSchema=mongoose.Schema({
    partner_id:{
        type: mongoose.Schema.Types.ObjectId,ref: 'Partner'
    },title:{
        type:String,require:true,lowercase:true,city:{
        type:String,state:{
        type:String,country:{
        type:String,pincode:{
        type:String,require: true
    },category:{
        type:String,sub_category:{
        type:String,description:{
        type:String,address:{
        type:String,nearest_railway_station:{
        type:String,nearest_airport:{
        type:String,image:{
        type:String,},Product_sale:{
        type:Boolean,default:0
    },status:{
        type:Boolean,default:0
    }
},{timestamps:true})

module.exports=mongoose.model('Place',placeSchema);

index.js

const express= require('express');
const http= require('http');
const mongoose=require('mongoose');
var Passport = require('passport').Passport,partnerPassport = new Passport();

const app= express();

app.use(passport.initialize());
app.use(partnerPassport.initialize());

const hostname = 'localhost';
const port = 2000;
const url="mongodb://localhost:27017"

mongoose.connect(
    'mongodb://localhost:27017/susvagatam',{
        useNewUrlParser: true,useUnifiedTopology: true,useCreateIndex: true,useFindAndModify:false
    }
).then(()=>{
    console.log('database connected');
});

const partnerRouter = require('./route/partnerRouter.js');
const usersRouter = require('./route/usersRouter.js');


app.use('/partners',partnerRouter);
app.use('/users',usersRouter);


const server= http.createServer(app)
server.listen(port,hostname,()=>{
    console.log('server is runing')
});

如果我只添加合作伙伴然后工作正常,或者如果我只添加用户然后也可以正常工作。但是当添加两者时它不能正常工作。未经授权回复

单次认证正常,但两次认证无效。

解决方法

似乎您在这里需要的是 authorization 而不是 authentication

verifyUser 处理身份验证,而 verifyPartner 只处理合作伙伴的授权。

将您的 verifyPartner 重构为如下所示:

module.exports.verifyPartner = (req,res,done) => {
  Partner.findOne({ _id: req.params.partnerid },(err,partnerdata) => {
    if (err) {
      return done(err,false);
    }

    if (partnerdata) {
      return done(null,partnerdata);
    }

    return done(null,false);
  });
};

'/places/:partnerid' 路线上,您将它用作中间件,请确保在 verifyUser 之前先调用 verifyPartner

像这样:

partnerRouter.route('/places/:partnerid')
  .get(auth.verifyUser,auth.verifyPartner,(req,next)=> {...})

通过这种方式进行身份验证并首先验证 user,然后再继续检查用户是否是授权合作伙伴。