Wednesday, 17 May 2017

Where and how do I write code for login and register the user using mongoose so that I can save it to the database

I am doing a hands on to understand the passport strategy of passport-local So I have degined this much of code.I need to know what all logic should I code here. I am using Angular2 ionic2 node.js express.js and mongoose.

passport.js

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./user');


passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

The above file contaions the code to implement passport strategy i.e passport-local.

user.js

var mongoose = require('mongoose');
var Schema = moongoose.Schema;

var UserSchema = new Schema({
    email: String,
    password: String,
});
module.exports = mongoose.model('User',UserSchema);

The above is my user schema which contains my user model.

routes.js

var passport = require('passport');
var Service = require('./app/passport');
var authController  = require('./app/controllers/authentication');//this file is empty.

var requireLogin = passport.authenticate('local',{session:false});

module.exports = function(app){

    var auth = express.Router();

    app.use('/api/auth', auth);

    auth.post('/register',function(req, res){
        authController.register(req,res);
    } );

    auth.post('/login', requireLogin, function(req, res){
        authController.login(req, res);
    });
};

The above contains the routes.



via Aditya Jain

No comments:

Post a Comment