Sessions, Authentication och Login för REST-klassen

Kodexemplen nedan utgår från https://lernia.nodebite.se/rest-routing/

Notera att Mongoose-schemat för User måste uppdateras med email och password för att REST-klassen nedan ska kunna fungera:

// Create a new mongoose schema
var Schema = m.mongoose.Schema({
  firstname: {type: String, required: false},
  lastname: {type: String, required: false},
  email: {type: String, required: true},
  password: {type: String, required: true}
});

module.exports = m.mongoose.model("User", Schema);

Dessutom måste sessions slås på i Server-klassen:

  // start sessions
  this.app.use(m.expresssession({secret: '1234567890QWERTY'}));

En uppdaterad version av REST-klassen med sessions, authentications och login:

  • Notera användningen av auth och dess callback i POST
'use strict';
var s = g.settings;

module.exports = class REST {
  constructor(express) {
    this.settings = s.REST;
    this.DB = new g.classes.DB(); // DB connection & models
    this.app = express;
    this.router();
  }

  // setup standard CRUD for route
  router() {
    var me = this;

  //['GET','PUT','..'] , any_route, request

    this.app.all(this.settings.route, function(req, res) {

      // custom login route with a fake model
      if(req.params.model == 'login'){
        me.login(req, res);
        return; // exit - will not continue below
      }


      var model = me.DB.getModel(req.params.model);
      // do we have a 404?
      if (!me[req.method] || !model) {
        res.sendStatus(404);
        res.end();
        return;
      }

  //  this.GET      (Apple, {id:4}, {}, req, res)
      me[req.method](model, req.params, req.body, req, res);

    });

  }

  // CREATE
  //  (Apple, ..)
  POST(model, params, body, req, res) {

    this.auth(req.session, function(authenticated){

      if(!authenticated){
        // respond with 401 Unauthorized (as in not logged in)
        res.sendStatus(401);
        return;
      }

      var me = this,
          toSave = new model(body); // new model instance with data

      // write data to DB
      toSave.save(function(err, result) {
        if (err) { me.error(err, res); return; }
        res.json(result); // respond with result
      });

    });


  }

  // READ
  // (Apple, {id: 4}, ..)
  GET(model, params, body, req, res) {
    // pick a mongoose query function and parameters for it
    var me = this,
        func = params.modelID ? 'findById' : 'find',
        q = params.modelID ? params.modelID : {};

    // call the query function (find || findById)
    model[func](q, function(err, result) {
      if (err) { me.error(err, res); return; }
      res.json(result); // respond with result
    });
  }

  // UPDATE
  // (Apple, {id: 4}, ..)
  PUT(model, params, body, req, res) {
    if (!params.modelID) { this.error({error: 'Missing ID!'}, res); return; }

    var me = this;
    model.findByIdAndUpdate(params.modelID, body, {new: true}, function (err, result) {
      if (err) { me.error(err, res); return; }
      res.json(result); // respond with result
    });
  }

  // DELETE
  // (Apple, {id: 4}, ..)
  DELETE(model, params, body, req, res) {
    if (!params.modelID) { this.error({error: 'Missing ID!'}, res); return; }

    var me = this;
    model.findByIdAndRemove(params.modelID, function(err, result) {
      if (err) { me.error(err, res); return; }
      res.json(true); // respond with result
    });
  }


  error(err, res) {
    res.status(400);
    res.json(err);
  }

  auth(session, cb){
    var model = this.DB.getModel('User');

    if(session.user){
      model.find({
        email: session.user.email,
        password: session.user.password
      }, function(err, result){
        if(result && result[0].email){
          cb(true);
        }else{
          cb(false);
        }
      });
    }else{
      cb(false);
    }
  }

  login(req, res){
    var model = this.DB.getModel('User');
    model.find({
      email: req.body.email,
      password: req.body.password
    }, function(err, result){
      if(err){
        console.log(err);
        res.sendStatus(401);
        return;
      }
      result = result[0];
      if(result && result.email){
        req.session.user = result;
        res.json({loggedIn: req.session.user.email});
      }else{
        // respond with 401 Unauthorized (as in not logged in)
        res.sendStatus(401);
      }
    });
  }

};
0 votes