我是不是PLATINENT.JS的新手,我在使用护照,本地护照和本地猫鼬进行身份验证时遇到了麻烦。它每次都会失败,我不知道为什么会这样。
我在这里和其他地方阅读了许多主题,以寻求解决方案。我还将关注一个视频教程,并以相同的方式设置所有内容。出于某种原因,我认为这与我的重构有关,但是我花了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) {
});
任何帮助将不胜感激。如果您还可以解释为什么我在做什么不起作用,那么对于我更好地理解身份验证以及如何不再遇到此问题将大有帮助。我很抱歉,如果以前已经回答了这个问题,但是找不到与我类似的话题。