Logout / destroy session för REST-klassen

Kodexemplen nedan utgår från: https://lernia.nodebite.se/sessions-authentication-och-login-for-rest-klassen/

(som i sin tur bygger på): https://lernia.nodebite.se/rest-routing/

Nedan finns en uppdaterad version av REST-klassen.

  • Notera den nya metoden logout och användningen av session.destroy() för att logga ut / invalidera (tömma) en session.
  • Notera också våra två custom routes för login och logout.
'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
      }

      // custom logout route with a fake model
      if(req.params.model == 'logout'){
        me.logout(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, callback){
    var User = this.DB.getModel('User');

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


  login(req, res){
    var me = this,
        User = this.DB.getModel('User');
    User.find({
      email: req.body.email,
      password: req.body.password
    }, function(err, user){
      if(err){
        console.log(err);
        res.sendStatus(401);
        return;
      }
      user = user.length>0 ? user[0] : null;
      if(user && user.email){
        req.session.user = user;
        res.json({loggedIn: req.session.user.email});
      }else{
        // logga ut! ( = se till att session förstörs)
        me.logout(req, res);
      }
    });
  }


  logout(req, res){
    // tar död på session (=släpper identifieringen av anslutningen)
    req.session.destroy(function(err){
      res.status(401);
      res.json({loggedOut: true});
    });
  }

};
0 votes