Sunday, February 18, 2018

Node Authentication

For allowing users to sign up & login we will use Authentication method using node, express & mongoose. We have to include Facebook, Twitter & Google Authentication also.

So,that we have to create a new folder to do this authentication & execute. The following is the tree diagram of how the folder looks..

- app
------ models
---------- user.js <!-- our user model -->
 ------ routes.js <!-- all the routes for our application -->
- config
------ auth.js <!-- will hold all our client secret keys (facebook, twitter, google) --> ------ database.js <!-- will hold our database connection settings -->
------ passport.js <!-- configuring the strategies for passport -->
- views
------ index.ejs <!-- show our home page with login links -->
------ login.ejs <!-- show our login form -->
------ signup.ejs <!-- show our signup form -->
------ profile.ejs <!-- after a user logs in, they will see their profile -->

- package.json <!-- handle our npm packages -->
- server.js <!-- setup our application -->

We will use some dependencies of Node to do this authentication
  1. passport - To authenticate local sign in & sign up & social media oAuth
  2. bcrypt Node - To hash the password (Then only, the password will be stored as an encrypted form in database.
  3. connect-flash - To flash messages in the login & sign up forms to show the user that he/she input wrong email/password
  4. express - framework of nodejs
  5. mongoose - Object modelling for mongo DB
  6. ejs - templating engine
  7.  
Now we have to create package.json to require our dependencies..

{
"name": "node-authentication",
"main": "server.js",
"dependencies" :
{
 "express" : "~4.14.0",
"ejs" : "~2.5.2",
"mongoose" : "~4.13.1",
"passport" : "~0.3.2",
"passport-local" : "~1.0.0",
"passport-facebook" : "~2.1.1",
"passport-twitter" : "~1.0.4",
"passport-google-oauth" : "~1.0.0",
"connect-flash" : "~0.1.1",
"bcrypt-nodejs" : "latest",
"morgan": "~1.7.0",
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"method-override": "~2.3.6",
"express-session": "~1.14.1"
}
}

now we have to install the above dependencies in our app folder
to do type
npm install

Now Server.js

// set up ============================================ // get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js'); // configuration ============================================ mongoose.connect(configDB.url); // connect to our database //
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions app.use(flash()); // use connect-flash for flash messages stored in session // routes =========================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport // launch =============================================== app.listen(port); console.log('The magic happens on port ' + port);

In config/database.js we have to add this code

module.exports = {
 'url' : 'your-settings-here' // looks like mongodb://<user>:<pass>@mongo.onmodulus.net:27017/Mikha4ot };
};

We will include the routing code


In app/routes.js
module.exports = function(app, passport) {

    // =====================================
    // HOME PAGE (with login links) ========
    // =====================================
    app.get('/', function(req, res) {
        res.render('index.ejs'); // load the index.ejs file
    });

    // =====================================
    // LOGIN ===============================
    // =====================================
    // show the login form
    app.get('/login', function(req, res) {

        // render the page and pass in any flash data if it exists
        res.render('login.ejs', { message: req.flash('loginMessage') }); 
    });

    // process the login form
    // app.post('/login', do all our passport stuff here);

    // =====================================
    // SIGNUP ==============================
    // =====================================
    // show the signup form
    app.get('/signup', function(req, res) {

        // render the page and pass in any flash data if it exists
        res.render('signup.ejs', { message: req.flash('signupMessage') });
    });

    // process the signup form
    // app.post('/signup', do all our passport stuff here);

    // =====================================
    // PROFILE SECTION =====================
    // =====================================
    // we will want this protected so you have to be logged in to visit
    // we will use route middleware to verify this (the isLoggedIn function)
    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user : req.user // get the user out of session and pass to template
        });
    });

    // =====================================
    // LOGOUT ==============================
    // =====================================
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
};

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

No comments:

Post a Comment