我试图在护照策略中添加一个usernameField中的手机,这样用户也可以使用那里的电话号码和电子邮件登录,但是在互联网上搜索后又有点怎么做 - 阅读passport.js docs它对我没有任何意义。 问题1:我应该更改我的schemamongoose模型,或者我可以在护照本地策略中添加第三个字段。
import mongoose from 'mongoose';
import { Router } from 'express';
import Account from '../model/account';
import bodyParser from 'body-parser';
import passport from 'passport';
import {generateAccessToken, respond, authenticate} from '../middleware/authMiddleware';
api.post('/register', (req, res) => {
Account.register(new Account({
username: req.body.email,
phoneNumber: req.body.phoneNumber,
myId: req.body.myId,
termsandcondition: req.body.termsandcondition,
verifiedEmailCode: uuid()
}), req.body.password, function(err, account) {
if (err) {
return res.json({
"status": false,
"code" : 500,
"message": 'An error occurred: ' + err
});
}
passport.authenticate(
'local', {
session: false
})(req, res, () => {
// send email
const confirmUrl = `${config.siteUrl}/api/v1/account/register/verifyemail?token=${req.user.verifiedEmailCode}`;
gmail.sendMail({
from: config.gmail.user,
to: req.user.username,
subject: 'Please confirm your email with Beamlive',
html: `<a href="${confirmUrl}">Please confirm your email with mylive</a>`,
auth: {
user: config.gmail.user,
refreshToken: config.gmail.refreshToken,
accessToken: config.gmail.accessToken
}
}, (err, info) => {
if(err) {
console.log('error sending email', err);
return;
}
console.log('successfully sent registration email');
})
})
.then(message => {
})
.done();
res.json({
"User":{"UserID": req.user.username,
"PhoneNumber": req.user.phoneNumber,
"myId": req.user.beamId.IdOne,
"termsandcondition": req.user.termsandcondition
},
"status": true,
"code": 200,
"message": 'You have successfully registered with mylive'
});
});
});
});
api.post('/login', (req, res, next) => passport.authenticate(
'local', {
session: false,
scope: []
}, (err, user, info) => {
if(err) {
return next(err);
}
if(!user.verifiedEmail && !user.verifiedPhone) {
return res.json({ "status": false, "code": 403, "message": "You need to verify your email or Phone number" });
}
req.logIn(user, next);
})(req, res, next), generateAccessToken, respond);
return api;
}
// auth middle-ware:
import jwt from 'jsonwebtoken';
import expressJwt from 'express-jwt';
const TOKENTIME = 60*60*24*30 // 30 days
const SECRET = "server key will go here";
let authenticate = expressJwt({ secret : SECRET })
let generateAccessToken = (req, res, next) => {
req.token = req.token || {};
req.token = jwt.sign({
id: req.user.id,
}, SECRET, {
expiresIn: TOKENTIME// 30 days
});
next();
}
let respond = (req, res) => {
res.status(200).json({
user: {userID: req.user.username,
token: req.token,
tokenTime: TOKENTIME},
status: true,
code: 200,
message: 'User logged In'
});
}
module.exports = {
authenticate,
generateAccessToken,
respond
};
// Index.js:
app.use(passport.initialize());
let Account = require('./model/account');
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
Account.authenticate()
));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// Schema mongodb:
import passportLocalMongoose from 'passport-local-mongoose';
let Account = new Schema({
phoneNumber: String,
email: String,
password: String
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
答案 0 :(得分:2)
passport-local-mongoose 库允许您在添加插件时传递一些选项,其中一个选项是 usernameQueryFields ,根据文档:
usernameQueryFields:指定用于识别用户的模型的替代字段(例如,电子邮件)。
因此,为了使用phoneNumber
字段,您应该可以执行以下操作:
let Account = new Schema({
phoneNumber: String,
email: String,
password: String
});
Account.plugin(passportLocalMongoose, { usernameQueryFields: ["phoneNumber", "email"] });
module.exports = mongoose.model("Account", Account);