首页 > 解决方案 > 如何在nodejs mongoose中将此回调身份验证转换为Promise

问题描述

我在这里使用 Nodejs Mongoose 但是当我尝试替换回调以承诺时它给了我一个错误(无法将用户序列化到会话中)请帮助我......

var localStrategy = require('passport-local').Strategy;
const user = require('./mongoBase/userSc.js');

const bcrypt = require('bcryptjs');

module.exports = function(passport) {
        passport.use(new localStrategy({ usernameField: 'email' }, (email, password, done) => {
            email = email.toLowerCase();
            user.findOne({ email: email }, (err, data) => {
                if (err) throw err;
                if (!data) {
                    return done(null, false, { message: "User Doesn't Exists.." });
                }
                bcrypt.compare(password, data.password, (err, match) => {
                    if (err) {
                        return done(null, false);
                    }
                    if (!match) {
                        return done(null, false, { message: "Password Doesn't Match" });
                    }
                    if (match) {
                        return done(null, data);
                    }
                });
            });
        }));

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

        passport.deserializeUser(function(id, cb) {
            user.findById(id, function(err, user) {
                cb(err, user);
            });
        });
    }
    // ---------------
    // end of autentication statregy

标签: javascriptnode.jsexpressmongoose

解决方案


这是我的 spotify 护照代码,也许它可以帮助你一些。如果此答案回答了您的问题,请单击答案旁边的复选框。

module.exports = function(passport) {
    passport.use(
        new SpotifyStrategy(
          {
            clientID: 'CLIENT ID',
            clientSecret: 'CLIENT SECRET',
            callbackURL: 'http://localhost:8888/auth/spotify/callback',
          },
          async (accessToken, refreshToken, expires_in, profile, done) => {
            // Do async operations
            
                    
              async function checking() {
                // Do async operations
              }  

              await checking();

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

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

推荐阅读