Hier is een eenvoudige installatie met behulp van paspoort om de gebruikers in/uit te loggen:
In het hoofdbestand app.js
/* Auth config --------------------------------*/
// @see http://frederiknakstad.com/authentication-in-single-page-applications-with-angular-js/
var passport = require('passport');
var User = require('./app/models/User'),
passport.use(User.localStrategy);
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
// Default session handling. Won't explain it as there are a lot of resources out there
app.use(express.session({
secret: "mylittlesecret",
cookie: {maxAge: new Date(Date.now() + 3600000)}, // 1 hour
maxAge: new Date(Date.now() + 3600000), // 1 hour
store: new RedisStore(config.database.redis), // You can not use Redis
}));
// The important part. Must go AFTER the express session is initialized
app.use(passport.initialize());
app.use(passport.session());
// Set up your express routes
var auth = require('./app/controllers/authController.js');
app.post('/auth/login', auth.login);
app.post('/auth/logout', auth.logout);
app.get('/auth/login/success', auth.loginSuccess);
app.get('/auth/login/failure', auth.loginFailure);
Op uw gebruikersmodel (ej. app/models/User.js)
Ik gebruik de paspoort-lokale module, die de inloglogica verder vereenvoudigt:https://github.com/jaredhanson/passport-local
/* Your normal user model ----------------------*/
var mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId,
PassportLocalStrategy = require('passport-local').Strategy;
var schema = new mongoose.Schema({
name: {type:String, required:true, trim:true},
email: {type:String, required: true, trim: true, lowercase:true, unique: true},
image: {type:String},
password: {type:String, required: true },
created: {type: Date, default: Date.now}
});
/* Auth properties ---------------------------*/
/* (passport) ---------------------------*/
// This is your main login logic
schema.statics.localStrategy = new PassportLocalStrategy({
usernameField: 'email',
passwordField: 'password',
},
// @see https://github.com/jaredhanson/passport-local
function (username, password, done){
var User = require('./User');
User.findOne({email: username}, function(err, user){
if (err) { return done(err); }
if (!user){
return done(null, false, { message: 'User not found.'} );
}
if (!user.validPassword(password)){
return done(null, false, { message: 'Incorrect password.'} );
}
// I'm specifying the fields that I want to save into the user's session
// *I don't want to save the password in the session
return done(null, {
id: user._id,
name: user.name,
image: user.image,
email: user.email,
});
});
}
);
schema.methods.validPassword = function(password){
if (this.password == password){
return true;
}
return false;
}
schema.statics.serializeUser = function(user, done){
done(null, user);
};
schema.statics.deserializeUser = function(obj, done){
done(null, obj);
};
var model = mongoose.model('User', schema);
exports = module.exports = model;
Op app/controllers/authController.js
Ik gebruik een applicatie met één pagina, dus ik retourneer JSON bij inloggen / uitloggen. Als u naar ergens anders wilt omleiden, moet u de functies "aanmelden geslaagd" en "aanmelding mislukt" wijzigen (of res.render(...) of wat dan ook aanroepen).
var passport = require('passport');
var AuthController = {
// Login a user
login: passport.authenticate('local', {
successRedirect: '/auth/login/success',
failureRedirect: '/auth/login/failure'
}),
// on Login Success callback
loginSuccess: function(req, res){
res.json({
success: true,
user: req.session.passport.user
});
},
// on Login Failure callback
loginFailure: function(req, res){
res.json({
success:false,
message: 'Invalid username or password.'
});
},
// Log out a user
logout: function(req, res){
req.logout();
res.end();
},
};
exports = module.exports = AuthController;
Ten slotte moet u uw inlogformulier (dat de method="post"
. moet hebben attributenset) naar /auth/login. Als het inloggen is gelukt, wordt de callback "loginSuccess" uitgevoerd. Bij een mislukte aanmelding wordt de callback "loginFailure" uitgevoerd.
Bewerken:
U kunt nieuwe gebruikers in uw mongo-database maken door iets uit te voeren als:
// On your main app.js file
app.post('/auth/register', auth.register);
// On your authController.js file, as per the previous example
var User = require('./app/models/User'); // The model we defined in the previous example
...
register: function(req, res){
User.create({name: req.body.name, email: req.body.email, password: req.body.password}, function(err){
if (err) {
console.log(err);
... // Your register error logic here
res.redirect('/* Your error redirection path */');
return;
}
res.redirect('/* Your success redirection path */');
});
},
...
Verwijs vervolgens een registratieformulier naar /auth/register. Ik heb de gegevens niet gevalideerd, maar u moet deze valideren voordat u probeert de gebruiker op te slaan.