Passport本地mongoose node.js支持多种用户类型 [英] Support for multiple user types by Passport-local mongoose node.js

查看:110
本文介绍了Passport本地mongoose node.js支持多种用户类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要两种类型的用户登录(用户,客户端).我到底如何在我的app.js中为两种类型创建localStrategies,对用户进行序列化和反序列化 我有两个单独的模式,都使用PassportLocalMongoose插件.

I wanted two types of users logging in (User, Client). How exactly can I create localStrategies, serialize and deserialize user for both types in my app.js I have two separate schemas, both using the PassportLocalMongoose plugin.

我目前如下配置我的护照,

I currently configuraing my passport like below,

var User = require('./models/User');
var Client= require('./models/Client');
passport.use(new LocalStrategy(User.authenticate(), Client.authenticate()));
passport.serializeUser(User.serializeUser(), Client.serializeUser());
passport.deserializeUser(User.deserializeUser(), Client.deserializeUser());

问题出在我尝试注册时.注册为用户有效,但作为客户端显示未经授权"错误. 我该如何解决这个问题?

The problem lies when I try to register. Registering as a User works, but as a client shows "Unauthorized" error. How can I fix this problem?

推荐答案

在阅读了password.js的文档(对Jared表示敬意)之后,我了解到我几乎在做错所有事情.

After going through the documentation of passport.js (kudos to Jared), I understood that I was doing almost everything wrong.

  1. 创建了两个localStrategies

  1. Created two localStrategies

passport.use('userLocal', new LocalStrategy(User.authenticate())); passport.use('clientLocal', new LocalStrategy(Client.authenticate()));

passport.use('userLocal', new LocalStrategy(User.authenticate())); passport.use('clientLocal', new LocalStrategy(Client.authenticate()));

并进行身份验证,

passport.authenticate('userLocal')(req, res, function () {
    res.redirect('/profile');
  });
and
passport.authenticate('clientLocal')(req, res, function () {
    res.redirect('/client');
  });

  1. 为serializeUser和deseriealizeUser使用了通行证模块(l =不使用passport-local-mongoose模块).

  1. Used passport module (l=not using the passport-local-mongoose module) for serializeUser and deseriealizeUser.

passport.serializeUser(function(user, done) { done(null, user); });

passport.serializeUser(function(user, done) { done(null, user); });

passport.deserializeUser(function(user, done) { if(user!=null) done(null,user); });

passport.deserializeUser(function(user, done) { if(user!=null) done(null,user); });

整个用户架构(对象)现在存储在请求中,并且可以通过您的任何路由进行访问.

The whole user schema (object) is now stored in the request and can be accessed through any of your routes.

希望它可以帮助解决类似问题的人.

Hope it helps out others with a similar issue.

这篇关于Passport本地mongoose node.js支持多种用户类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆