At the end of this activity you should have successfully implemented Authentication with passport Local Strategy (username and password) by completing the TODOs in server.js
and routes/index.js
.
To install this starter code on your computer, clone the repository and install dependencies with
npm install
-
Create a
.env
file and include the values for port and private key. Check the.env-sample
file for reference. -
In
server.js
on line 15 inside the thepassport.use()
method, configure passport local strategy.- instantiate the LocalStrategy object -
new LocalStrategy()
. - pass an anonymous function as its only argument -
new LocalStrategy(()=>{})
- pass username, password and cb(callback function) as the arguments in the anonymous function -
new LocalStrategy((username, password, cb) =>{})
- put the database query method implementation (
db.findByUsername()
) in the block of the localstrategy object. - Your code should end up looking like this:
passport.use(new LocalStrategy((username, password, cb) => { db.findByUsername(username, (err, user) => { //code to verify user with password here // return callback function invoked with a user object - cb(null, user) }));
- instantiate the LocalStrategy object -
-
In
server.js
, withpassport.serializeUser()
function and using theuser.id
object, configure passport to serialize users. -
In
server.js
on line 46, withpassport.serializeUser()
function and using theuser.id
object, configure passport to serialize users. -
In
server.js
line 82, initialize passport with thepassport.initialize()
function. -
In
server.js
line 83, include thepassport.session()
function to restore authentication state from the session. -
Complete the logout route in
routes/index.js
. Use thereq.logout()
method passport provides. See reference here. -
Start the server. Make sure you are in the project's directory in our terminal:
npm start
Open a web browser and navigate to http://localhost:3000/ to see the code in action.
Log in with either of these details:
username: amy, password: strings
OR
username: anne, password: secret
- Try out using passport-github to do github oauth authentication with passport. See reference here