title: User Authentication with Node.js
body: <p>I'm making a User Authentication with passport. First I created a default Admin User. Now this Admin must able to create users but not any other users. For this I created a Admin user in Database. Now my Question is how to create the other users by the Admin and as well only this Admin should have access to all API's routes but not for any other Users how to protect the API's? In server.js file i created middleware function as </p>
  
  <pre><code>//Catch unauthorized errors
  app.use(function (err, req, res, next) {
      if(err.name === 'UnauthorizedError') {
          res.status(401);
          res.json({"message": err.name + ":" + err.message});
      }
  });
  </code></pre>
  
  <p>Please help with this. I hope you guys don't mind for posting such a long files.</p>
  
  <p>'authentication.js'</p>
  
  <pre><code>'use strict';
  var passport = require('passport'),
      mongoose = require('mongoose'),
      Users = mongoose.model('Users');
  
  
  var authentication = {
  
      register: function(req, res, name, email, password) {
          var userData = req.body;
  
          var user = new Users({
              email: userData.email,
              name: userData.name,
          });
  
          user.setPassword(userData.password);
  
          if(!user) {
              res.status(400).send({error: 'All fields required'});
          }
  
          user.save(function(err, result) {
              if(err) {
                  console.log('Could not save the User');
                  res.status(500).send({error: 'Could not save the User'});
              }else {
                  res.send('New User Created Successfully');
              }
          });
      },
  
      login: function (req, res) {
          if(!req.body.email || !req.body.password) { 
              res.status(400).send({"message": "All fields required"});
              return;    
          }
  
          passport.authenticate('local', function (err, user, info) { 
              var token;
  
              if (err) { 
          res.status(404).send({err: 'An Error Occured'});
                  return;
              }
  
              if(user) { 
                  token = user.generateJwt();
          res.status(300).send({"token": token});
              }else { 
          res.status(401).send('Unauthorized User');
              }
          });
      }
  
  };
  
  module.exports = authentication;
  </code></pre>
  
  <p>'user-model.js'</p>
  
  <pre><code>'use strict';
  var mongoose = require('mongoose'),
      crypto = require('crypto'),
      jwt = require('jsonwebtoken'),
      Schema = mongoose.Schema;
  
  var userSchema = new mongoose.Schema({
      email: { 
          type: String,
          required: true,
          unique: true
      },
      name: { 
          type: String,
          required: true
      },
      hash: String, 
      salt: String
  });
  
  
  
  userSchema.methods.setPassword = function (password) {
      this.salt = crypto.randomBytes(16).toString('hex'); 
      this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
  };
  
  //Validating a submitted password
  userSchema.methods.validPassword = function (password) {
      var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
      return this.hash === hash;
  };
  
  //Generating a JSON Web Token
  userSchema.methods.generateJwt = function () {
      var expiry = new Date();
      expiry.setDate(expiry.getDate() + 7);
  
      return jwt.sign({ 
          _id: this._id,
          email: this.email, 
          name: this.name,   
          exp: parseInt(expiry.getTime() / 1000) 
      }, process.env.JWT_SECRET); 
  };
  
  var User = mongoose.model('Users', userSchema);
  var user = new User();
  user.name = 'Arjun Kumar';
  user.email = 'arjun@kumar.com';
  user.setPassword('myPassword');
  user.save();
  </code></pre>
  
  <p>'user-route.js'</p>
  
  <pre><code>'use strict';
  var express = require('express'),
      userRoute = express.Router(),
      jwt = require('express-jwt'),
      authentication = require('../controllers/authentication');
  
  var auth = jwt({
      secret: process.env.JWT_SECRET,
      userProperty: 'payload'
  });
  
  userRoute.post('/:adminuserid/register', auth, authentication.register)
      .post('/login', authentication.login);
  
  module.exports = userRoute;
  </code></pre>
  
  <p>'passport.js'</p>
  
  <pre><code>var passport = require('passport'),
      LocalStrategy = require('passport-local').Strategy,
      mongoose = require('mongoose'),
      Users = mongoose.model('Users');
  
  passport.use(new LocalStrategy({usernameField: 'email'}, function (username, password, done) {
      Users.findOne({ email: username }, 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);
      });
  }));
  </code></pre>