npm install --save
passportpassport-localbcrypt-node.jsFor some reasonbcryptdoesn't hashcryptomongooseconnect-mongoexpress-session
- config >
passport.js(set up authentication strategies here - localStrategy will usecomparePasswordmethod defined inUser.js) - routes >
auth.js(http requests GET, POST for login and signup) - models >
User.js(include at least email and password)
app.js
import passport from 'passport'import auth from './routes/auth''const passportConfig = require('./config/passport')app.use(passport.initialize())app.use(passport.session())This is invoked on every http request. It will check whether there is an authenticated user object inreq.session.passport.userloaded bypassport.serializeUser(). If there is, load additional user information toreq.userviapassport.deserializeUser()in passport.jsapp.use('/auth', auth)This makes the authentication routes available to app
auth.js
-
To sign up a new user, the route is:
router.post('/signup', function(req, res, next) { User.findOne(..
1.1 InLogin.js, inthis.state, email, username and password keys are updated on input entry.
1.2 On ajax call, find existing user usingreq.body.emailorreq.body.username, if not createnew User()and populate withreq.bodyattributes
1.3 Invokereq.logInwhich updatesreq.session.passport.userviapassport.serializeUser() -
To login an existing user, the route is:
router.post('/login', function(req, res, next) { passport.authenticate('local', function(error, user, info) {..
2.1 InLogin.js, inthis.state, email, username and password keys are updated on input entry.
2.2 On ajax call, use passport.js strategylocalto authenticate user. If password matches, invokereq.logInwhich updatesreq.session.passport.userviapassport.serializeUser()
index.js
store.dispatch(getUser())is the function that updatesstate.userin the global app state. It dispatches thegetUser()action which fires the ajax GET request/auth/user. If user is authenticated, it returnsreq.userwhich has been populated bypassport.deserializeUser()
App.js
state.useris exposed viamapStatetoPropsasthis.props.user. If exists, isLoggedIn is updated and<Secret/>component is loaded. Else,<Login/>component is loaded.