Я новичок в passport.js, и у меня возникают проблемы при аутентификации с использованием passport, local- и passport-local-mongoose.Это терпит неудачу каждый раз, и я понятия не имею, почему это происходит.
Я прочитал много тем здесь и в других местах, пытаясь найти решение.Я также слежу за видеоуроком, и все настроено так же.По какой-то причине я считаю, что это связано с моим рефакторингом, но я потратил на это 2 дня, и мне не повезло.
Вот мой файл app.js:
var express = require("express");
var request = require('request');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var paypal = require('paypal-rest-sdk');
var User = require("./models/user.js");
var Vehicle = require("./models/vehicle.js");
var VehicleData = require("./models/vehicleData.js");
var Admin = require("./models/admin.js");
var passport = require("passport");
var LocalStrategy = require("passport-local");
var passportLocalMongoose = require("passport-local-mongoose");
var loginRoutes = require("./routes/login");
var registerRoutes = require("./routes/register");
//var adminRoutes = require("./routes/admin");
var app = express();
// PAYPAL CONFIGURATION
paypal.configure({//LEFT THIS OUT OF CODE ON PURPOSE});
//setting up the routes
app.use("/login", loginRoutes);
app.use("/register", registerRoutes);
//app.use('/admin', adminRoutes);
//EJS
app.set('view engine', 'ejs');
//BODY PARSER
app.use(bodyParser.urlencoded({ extended: true }));
//setting the root of the website
app.use(express.static(__dirname));
//express-session settings
app.use(require("express-session")({
secret: "I hope this all goes well",
resave: false,
saveUninitialized: false
}));
//passport settings
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// MONGOOSE
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
app.get("/", function(req, res) {
res.render("main/index");
});
app.listen(process.env.PORT, process.env.IP, function() {
console.log("Connected to server on " + process.env.IP + ":" + process.env.PORT);
});
Вотфайл user.js:
var mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
var UserSchema = new mongoose.Schema({
name: {
first: {
type: String,
required: true,
trim: true
},
last: {
type: String,
required: true,
trim: true
}
},
username: {
type: String,
required: true,
//trim: true,
//lowercase: true
},
password: {
type: String,
//trim: true
},
api_token: {
access_token: String,
expires_in: Number,
refresh_token: String,
created_at: Number
},
vehicles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Vehicle"
}
],
subscription: {
agreementId: String,
state: String,
plan: String,
billingAmount: String,
billingCurrency: String,
description: String,
startDate: Date,
expirationDate: Date,
payerInfo: {
id: String,
name: {
first: String,
last: String,
},
address: {
streetLine1: String,
streetLine2: String,
city: String,
state: String,
zipCode: String,
countryCode: String
}
}
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Наконец, вот файл register.js (маршруты маршрутов):
var express = require("express");
var router = express.Router({mergeParams: true});
var paypal = require('paypal-rest-sdk');
var User = require("../models/user.js");
var bodyParser = require('body-parser');
var passport = require("passport");
var urlencodedParser = bodyParser.urlencoded({ extended: true })
router.get("/success/:userId", function(req, res) {
var paymentToken = req.query.token;
//excecute the billing plan the paying user agreed to
paypal.billingAgreement.execute(paymentToken, {}, function (error, billingAgreement) {
if (error) {
console.log(error);
throw error;
} else {
console.log("INFO: Billing Agreement Executed");
//create subscription data that will be added to user information in db
var subscriptionUpdates = {
subscription: {
agreementId: billingAgreement.id,
state: billingAgreement.state,
plan: billingAgreement.plan.payment_definitions[0].frequency,
billingAmount: billingAgreement.plan.payment_definitions[0].amount.value,
billingCurrency: billingAgreement.plan.currency_code,
description: billingAgreement.description,
startDate: new Date(),
expirationDate: billingAgreement.agreement_details.next_billing_date,
payerInfo: {
id: billingAgreement.payer.payer_info.payer_id,
name: {
first: billingAgreement.payer.payer_info.first_name,
last: billingAgreement.payer.payer_info.last_name,
},
address: {
streetLine1: billingAgreement.payer.payer_info.shipping_address.line1,
streetLine2: billingAgreement.payer.payer_info.shipping_address.line2,
city: billingAgreement.payer.payer_info.shipping_address.city,
state: billingAgreement.payer.payer_info.shipping_address.state,
zipCode: billingAgreement.payer.payer_info.shipping_address.postal_code,
countryCode: billingAgreement.payer.payer_info.shipping_address.country_code
}
}
}
};
console.log("User ID is: " + req.params.userId);
User.findOne(req.params.userId, subscriptionUpdates, {new: true}, function(err, updatedUser){
console.log("User ID is: " + req.params.userId);
if(err){
console.log("ERROR: User subscription information not saved to user account");
console.log(err);
}
else{
console.log("INFO: " + updatedUser.subscription.plan + " subscription information added to user account");
console.log(updatedUser);
res.send(""); //need to redirect somewhere
}
});
}
});
});
router.get("/cancel/:userId", function(req, res) {
//get the date
var isoDate = new Date();
isoDate.setDate(isoDate.getDate() + 14);
isoDate.toISOString().slice(0, 19) + '-05:00';
//create subscription info as trial
var subscriptionUpdates = {
subscription: {
startDate: new Date(),
expirationDate: isoDate,
plan: "trial"
}
};
//find user that was registering and update subscription information
User.findOneAndUpdate(req.params.userId, subscriptionUpdates, {new: true}, function(err, updatedUser) {
if(err){
console.log("ERROR: User subscription information not saved to user account");
console.log(err);
}
else{
console.log("INFO: Trial subscription information added to user account");
console.log(updatedUser);
res.send(""); //need to redirect somewhere
}
});
});
router.post("/", urlencodedParser, function(req, res) {
//create new user account
User.register(new User({
"name": {
"first": req.body.register.firstName,
"last": req.body.register.lastName,
},
"username": req.body.username
}),
req.body.password,
function(err, newUser){
if(err){
console.log("ERROR: User account failed to create in database");
console.log(err);
}
else {
console.log("INFO: New user created:");
console.log(newUser);
passport.authenticate("local", function(req, res) {return res.redirect("/admin/console");});
//get the date
var isoDate = new Date();
isoDate.setDate(isoDate.getDate() + 13);
isoDate.toISOString().slice(0, 19) + '-05:00';
//check whic subscription plan user selected
if(req.body.register.subscriptionType === "trial"){
isoDate.setDate(isoDate.getDate() + 1);
isoDate.toISOString().slice(0, 19) + '-05:00';
console.log("INFO: New user selected trial subscription");
var subscriptionUpdates = {
"subscription": {
"startDate": new Date(),
"expirationDate": isoDate,
"plan": "trial"
}
};
//update subscription information for user that registered
User.findOneAndUpdate(newUser._id, subscriptionUpdates, function(err, updatedUser) {
if(err){
console.log("ERROR: User subscription information not saved to user account");
console.log(err);
}
else{
console.log("INFO: Trial subscription information added to user account");
console.log(updatedUser);
res.redirect("/admin/login"); //need to redirect somewhere
}
});
}
else {
//setup the blling plan depending on the option selected
if(req.body.register.subscriptionType === "monthly"){
var billingPlanAttributes = {
"name": "Monthly Billing Plan",
"description": "Monthly Billing Plan",
"type": "INFINITE",
"merchant_preferences": {
"auto_bill_amount": "yes",
"cancel_url": "http://" + req.get("host") + "/register/cancel/" + newUser._id,
"initial_fail_amount_action": "cancel",
"max_fail_attempts": "1",
"return_url": "http://" + req.get("host") + "/register/success/" + newUser._id
},
"payment_definitions": [
{
"name": "Monthly Recurring Charge",
"frequency_interval": "1",
"type": "REGULAR",
"cycles": "0",
"frequency": "MONTH",
"amount": {
"currency": "USD",
"value": "5"
},
},
]
};
}
else if(req.body.register.subscriptionType === "yearly"){
var billingPlanAttributes = {
"name": "Yearly Billing Plan",
"description": "Yearly Billing Plan",
"type": "INFINITE",
"merchant_preferences": {
"auto_bill_amount": "yes",
"cancel_url": "http://" + req.get("host") + "/register/cancel/" + newUser._id,
"initial_fail_amount_action": "cancel",
"max_fail_attempts": "1",
"return_url": "http://" + req.get("host") + "/register/success/" + newUser._id
},
"payment_definitions": [
{
"name": "Annual Recurring Charge",
"frequency_interval": "1",
"type": "REGULAR",
"cycles": "0",
"frequency": "YEAR",
"amount": {
"currency": "USD",
"value": "50"
},
},
]
};
}
//attributes needed to update the billing plan status to active
var billingPlanUpdateAttributes = [
{
"op": "replace",
"path": "/",
"value": {
"state": "ACTIVE"
}
}
];
//billing agreement attributes to setup individual agreements that will be sent to each paying user
var billingAgreementAttributes = {
"name": "CHANGE THIS WITH THE USER'S DB ID",
"description": "CHANGE WITH DB NAME + FREQUENCY + Billing Agreement",
"start_date": isoDate,
"plan": {
"id": "THIS VALUE WILL BE CHANGED"
},
"payer": {
"payment_method": "paypal"
},
};
// Create the billing plan
paypal.billingPlan.create(billingPlanAttributes, function (error, billingPlan) {
if (error) {
console.log(error);
throw error;
} else {
// Activate the plan by changing status to Active
paypal.billingPlan.update(billingPlan.id, billingPlanUpdateAttributes, function (error, response) {
if (error) {
console.log(error);
throw error;
} else {
billingAgreementAttributes.plan.id = billingPlan.id;
// Use activated billing plan to create agreement
paypal.billingAgreement.create(billingAgreementAttributes, function (error, billingAgreement) {
if (error) {
console.log(error);
throw error;
} else {
for (var index = 0; index < billingAgreement.links.length; index++) {
if (billingAgreement.links[index].rel === 'approval_url') {
var approval_url = billingAgreement.links[index].href;
res.redirect(approval_url);
}
}
}
});
}
});
}
});
}
}
}
);
});
module.exports = router;
Следующая строка в файле register.js несделать что-нибудь (возможно, из-за сбоя аутентификации)
passport.authenticate("local", function(req, res) {return res.redirect("/admin/console");});
Я ожидаю, что он перенаправит, но это не так.
Кроме того, моя аутентификация маршрута входа также не проходит.Он всегда перенаправляет на URL ошибки.Вот маршрут входа в систему:
router.post("/", passport.authenticate('local', {
failureRedirect: "/admin/login",
successRedirect: "/admin/console"}),
function(req, res) {
});
Любая помощь будет принята с благодарностью.Если вы также можете объяснить, почему то, что я делаю, не работает, я смогу лучше понять аутентификацию и избежать повторения этой проблемы.Мои извинения, если на этот вопрос уже был дан ответ, но я не смог найти тему, похожую на мою.