import passport from 'passport' ; import passportLocal from 'passport-local' ; import bcrypt from 'bcrypt-nodejs' ; import { Request , Response , NextFunction } from 'express' ; import User , { UserModel } from '../models/user' ; passport . serializeUser < UserModel , string > ( ( user , done ) => { done ( undefined , user . _id ) ; } ) ; passport . deserializeUser ( ( id , done ) => { User . findById ( id , ( err , user ) => { done ( err , user ) ; } ) ; } ) ; passport . use ( new passportLocal . Strategy ( { usernameField : 'username' } , ( username , password , done ) => { User . findOne ( { username : username . toLowerCase ( ) } , ( err , user ) => { if ( err ) { return done ( err ) ; } if ( ! user ) { return done ( undefined , false , { message : 'invalid username or password' } ) ; } bcrypt . compare ( password , user . password , ( bcryptErr , isMatch ) => { if ( bcryptErr ) { return done ( bcryptErr ) ; } if ( isMatch ) { return done ( undefined , user ) ; } return done ( undefined , false , { message : 'invalid username or password' } ) ; } ) ; } ) ; } ) ) ; export const isAuthenticated = ( req , res , next ) => { if ( req . isAuthenticated ( ) ) { return next ( ) ; } return res . status ( 401 ) . send ( 'login required' ) ; } ;