Last active
January 3, 2016 19:38
-
-
Save biggora/8509314 to your computer and use it in GitHub Desktop.
Local Authorization in TrinteJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Local Authorization manager | |
* | |
* | |
* Created by init script | |
* App based on TrinteJS MVC framework | |
* TrinteJS homepage http://www.trintejs.com | |
**/ | |
var auth = require( 'trinte-auth' ); | |
var config = require( '../configuration' ); | |
var passport = require( 'passport' ); | |
var LocalStrategy = require( 'passport-local' ).Strategy; | |
/** | |
* Example LocalStrategy | |
*/ | |
passport.use( new LocalStrategy( { | |
usernameField: 'login', | |
passwordField: 'password' | |
}, function(username, password, done) { | |
if (!username || username === "") { | |
return done(null, false, {message: 'Required username.'}); | |
} | |
if (!password || password === "") { | |
return done(null, false, {message: 'Required password.'}); | |
} | |
User.findOne( { | |
username: username | |
}).exec(function(err, user) { | |
if( err ) { | |
return done( err ); | |
} | |
if( !user ) { | |
return done( null, false, { message: 'Incorrect username.' } ); | |
} | |
if( !user.validPassword( password ) ) { | |
return done( null, false,{ message: 'Incorrect password.' } ); | |
} | |
return done( null, user ); | |
} ); | |
} | |
) ); | |
passport.serializeUser( function(user, done) { | |
done( null, user.id ); | |
} ); | |
passport.deserializeUser( function(id, done) { | |
User.findById( id, function(err, user) { | |
done( err, user ); | |
} ); | |
} ); | |
/** | |
* localAuth is authenticate middleware | |
* @param {String} path | |
*/ | |
auth.localAuth = function localAuth(path) { | |
return passport.authenticate( 'local', { | |
successReturnToOrRedirect: '/', | |
failureRedirect: path || '/login', | |
failureFlash: true, | |
successFlash: 'Welcome!' | |
} ); | |
}; | |
/** | |
* isAdmin is admin authenticate middleware | |
* @param {String} path | |
*/ | |
auth.isAdmin = function isAdmin(path) { | |
return function(req, res, next){ | |
// your code here | |
next(); | |
}; | |
}; | |
auth.passport = passport; | |
module.exports = auth; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment