标签: passport-local

如何从管理员帐户切换到另一个用户帐户

我有一个用户表,其中有一个管理员帐户和一些其他普通用户帐户。

我想为特定用户执行所有活动。它应该像由同一用户完成的活动一样。

有人可以告诉我如何在不登录该帐户的情况下从管理员帐户切换到另一个帐户。

目前我使用护照认证。(护照本地)

这是我的代码

app.get('/secure/group/login', function(req,res,next) {
        passport.authenticate('local',function(err,user,info) {
            console.log("error is "+err);
            req.logIn('tessAccount',function(err) {
                    console.log("Weer" +err);

            });
            console.log("dd");

        })(req,res,next);
    });

    });
Run Code Online (Sandbox Code Playgroud)

和护照代码

var LocalStrategy = require('passport-local').Strategy;

module.exports = function(passport) {
    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.token);
    });


passport.use(new BearerStrategy(
  function(token, done) {
      user.tokenExist(token, function(err, user) {
                if (err) {
                    return done(err);
                }
                 else {
                    return done(null, user, { scope: 'all' });
                }
      });
  }
));
    // used to deserialize the user …
Run Code Online (Sandbox Code Playgroud)

node.js passport-local passport.js

3
推荐指数
1
解决办法
1069
查看次数

Node js Next 不是护照策略错误中的函数

似乎无法让登录系统工作。我使用包含用户信息的 json 文件,并使用 node.js、express 和护照。这是我的代码(经过删节,仅包含相关信息)。

索引.js

const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
const myDB = require('./jDB');
const passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
const app = express();
const bodyParser = require('body-parser');

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

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

app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));

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

passport.deserializeUser(function(id, cb) {
  User.findById(id, function(err, user) {
    cb(err, user);
  }); …
Run Code Online (Sandbox Code Playgroud)

javascript node.js express passport-local passport.js

3
推荐指数
1
解决办法
5635
查看次数

为什么我应该只使用护照序列化用户存储 user.id ?

我已经在一个节点项目上工作了一段时间,并且已经实现了护照来处理身份验证。和很多人一样,我对护照使用的“serializeUser”和“deserializeUser”函​​数感到困惑,据我了解,这些函数用于将用户 ID 存储在会话中(req.session.passport),然后需要时使用该 id 从数据库中获取整个对象。我不明白的是为什么你不能一开始就将整个对象存储在会话中?

我读了一个教程,其中这些函数的实现如下:

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

passport.deserializeUser(function(user, done){
   done(null, user);
});
Run Code Online (Sandbox Code Playgroud)

尝试之后,我发现这个方法没有问题,但是因为很多其他人没有存储他们的整个对象,而是只存储 id,所以我切换到相同的方法,现在代码如下所示:

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

passport.deserializeUser(function(id, done){
    connection.query("SELECT * FROM accounts WHERE accountID = ?", [id], function (err, rows){
        done(err, rows[0]);
    });
});
Run Code Online (Sandbox Code Playgroud)

这也有效,但现在我想知道,这样做我得到了什么?仅存储 ID 是否更有效,因为每次我需要访问用户对象时似乎没有必要访问数据库。非常感谢任何澄清:)

node.js passport-local passport.js

3
推荐指数
1
解决办法
1102
查看次数

使用 JWT Passport 进行 NestJS 身份验证不起作用

我正在尝试使用 jwt-passport 和 nestjs 来设置一个非常简单的登录系统。我遵循了本教程:https : //docs.nestjs.com/techniques/authentication但我无法让它工作。我对这些东西真的很陌生,如果有人能给我指路,我将不胜感激。

我将登录名发送到服务器的方式:

    this.clientAuthService.login(this.userName, this.password).then(response => {
        this.clientAuthService.setToken(response.access_token);
        this.router.navigate(['/backend']);
    });
Run Code Online (Sandbox Code Playgroud)

我的 ClientAuthService:

export class ClientAuthService {

  constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId) {
  }

  getToken(): string {
    if (isPlatformBrowser(this.platformId)) {
      return localStorage.getItem(TOKEN_NAME);
    } else {
      return '';
    }
  }

  setToken(token: string): void {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.setItem(TOKEN_NAME, token);
    }
  }

  removeToken() {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.removeItem(TOKEN_NAME);
    }
  }

  getTokenExpirationDate(token: string): Date {
    const decoded = jwt_decode(token);

    if (decoded.exp === undefined) {
      return null; …
Run Code Online (Sandbox Code Playgroud)

node.js jwt passport-local angular nestjs

3
推荐指数
1
解决办法
2979
查看次数

NodeJS 更新用户 Bcrypt - 密码未经过哈希处理

我正在尝试使用 bcrypt-nodejs 模块为具有哈希密码的 Node.JS 应用程序上的用户配置文件设置更新功能。它在登录时有效,但是当我更新配置文件时,它会使用纯文本更新用户对象(即:我输入“文本”作为密码,数据库显示“文本”)。我想在更新配置文件时对密码进行哈希处理。我该如何解决这个问题?

下面是我的控制器代码:

exports.editUser = function(req, res) {
 // user edit form set to findonendupdate
 User.findByIdAndUpdate({ _id: req.params.user_id, randString: req.body.randString }, req.body, function(err, user) { 

   if (err) 
    res.send(err); 
   res.json({ data: user }); 
 });
};
Run Code Online (Sandbox Code Playgroud)

作为参考,这是适用于新用户注册的用户模型代码:

 passport.use('local', new LocalStrategy(
  function(username, password, callback) {
   User.findOne({ username: username } , function (err, user) {
     if (err) { return callback(err); }

     // No user found with that username
     if (!user) { return callback(null, false); }

     // Make sure the password is …
Run Code Online (Sandbox Code Playgroud)

updates bcrypt node.js passport-local passport.js

2
推荐指数
1
解决办法
6053
查看次数

闪讯 Passport-local-mongoose

我在尝试找出从哪里获取即时消息时遇到问题

router.get('/login', function(req, res) {
    res.render('login', { 
        user : req.user,
        failureMessage : req.flash('fail')
    });
});

router.post('/login', passport.authenticate('local', {
    successRedirect : '/dashboard',
    failureRedirect : '/login',
    failureFlash : true,
}), function(req, res) {
    // none of this will run right?
});
Run Code Online (Sandbox Code Playgroud)

我正在渲染一个登录页面,当用户提交数据时,它会转到 Passport.authenticate 中间件,它会处理其余的事情,而不需要进行额外的回调,所以我如何获取闪存消息,以便在重定向时显示它返回/登录页面?

另一个问题是我是否应该这样做

passport.use(User.createStrategy());
Run Code Online (Sandbox Code Playgroud)

或者

passport.use(new LocalStrategy(User.authenticate()));
Run Code Online (Sandbox Code Playgroud)

文档告诉我使用第一个: https: //github.com/saintedlama/passport-local-mongoose#simplified-passportpassport-local-configuration但我还没有看到使用第一个的教程。

mongoose node.js passport-local

2
推荐指数
1
解决办法
938
查看次数

如果用户经过身份验证,就阻止他们再次登录 Passportjs?

我正在使用 PassportJS,注册和登录功能运行得非常顺利。

我使用 PassportJS 面临的唯一问题(我也在使用会话),即使用户已经登录,他们也可以再次返回到注册/登录 url 并进行注册和/或重新登录!

这很诱惑我。如果有人有修复/建议,请把它写下来。

更新 - 1

我的一瞥routes.js:(使用 PassportJS 和 connet-ensure-login。

app.get('*', function(req, res, next) {
    if (req.url.indexOf('/users/login') < 0 &&
        req.url.indexOf('/users/signup') < 0) {
        req.session.returnTo = null;
    }
    next();
});

// =====================================
// HOME PAGE (with login links) ========
// =====================================
app.get('/', sabSettings, function(req, res) {
    Setting.findOne(function(err, setting) {
        if (err)
            throw err;
        // console.log(setting);
        res.render('index', { title: 'eduBird | Reach the glory', setting: req.setting }); // load the index file
    });
}); …
Run Code Online (Sandbox Code Playgroud)

mongoose node.js passport-local passport.js

2
推荐指数
1
解决办法
1855
查看次数

Passport.js 出现“TypeError:User.serializeUser 不是函数”

我是 Passport JS 的新手,我正在 Passport 中制作我的第一个程序,我的主目录中有 app.js ,主目录内的 models 目录中有 user.js 。当我尝试运行命令node app.js时,我收到以下错误。

C:\Users\RAJ\Desktop\webD\auth\app.js:26
passport.serializeUser(User.serializeUser()); //encrypt
                            ^

TypeError: User.serializeUser is not a function
    at Object.<anonymous> (C:\Users\RAJ\Desktop\webD\auth\app.js:26:29)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:193:16)
    at bootstrap_node.js:617:3
Run Code Online (Sandbox Code Playgroud)

以下是我的两个文件 app.js 和 user.js。

应用程序.js

var express               = require('express'),
mongoose              = require('mongoose'),
bodyParser            = require('body-parser'),
passport              = require('passport'),
User                  = require('./models/user'),
localStrategy         = require('passport-local'),
passportLocalMongoose = require('passport-local-mongoose');

mongoose.connect("mongodb://localhost/auth_demo");

 var …
Run Code Online (Sandbox Code Playgroud)

javascript node.js passport-local passport.js

2
推荐指数
1
解决办法
4429
查看次数

Passport.js Google 策略不适用于 React 应用程序

我正在使用 Passport.js 谷歌策略进行用户身份验证。我正在使用 OAUTH2。

当我启动服务器并通过浏览器点击 API 时,它会启动 google 登录页面。但是当我从 React 前端点击 API 时,它永远不会启动谷歌登录页面。

请找到下面的服务器代码,

const bodyParser = require('body-parser');
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const app = express();
const cors = require('cors');

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

app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
        "Access-Control-Allow-Methods",
        "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    );
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Requested-With,content-type"
    );
    res.setHeader("Access-Control-Allow-Credentials", true);
    next();
});

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());


passport.use('google', new GoogleStrategy({
    clientID: "clientID", -- my client id
    clientSecret: …
Run Code Online (Sandbox Code Playgroud)

node.js reactjs passport-local passport.js passport-google-oauth

2
推荐指数
1
解决办法
2415
查看次数

Is it possible to have multiple local strategies in passport implemented with NestJS

I have a scenario where I need to implement an authentication mechanism for admin and for normal users in my application using the Passport local strategy. I implemented the strategy for the normal users as described here. It is working perfectly fine.

However, now I need to implement the same local strategy for Admin login. I feel like it would have been much easier if both the type of users(admin and normal user) are on the same entity/table because …

passport-local passport.js nestjs

2
推荐指数
1
解决办法
3584
查看次数