0

As the title suggests, I want to reduce duplicate authorization code for each new route I call. My problem is exactly the same as the user in this post, because apparently we downloaded the same project from GitHub repository.

I tried both of the solutions suggested in the answers, however it restricts me from accessing those routes even if I'm logged in.

Here's the code:

router.js

// GET route for reading data
router.get("/", function (req, res, next) {
  return res.sendFile(path.join(__dirname + "/login"));
});

//Export authorization module
 var auth = require("../auth");
//Verify if user is authorized to access this route
 router.get("/complete-profile", auth.isAuthorized, function (req, res, next) {
   return res.sendFile(path.join(__dirname, "../public", "image.html"));
 });

//READ THE IMAGE UPLOAD FOLDER
router.use(express.static("public"));
// GET route after login, verify if user logged in
router.get("/complete-profile", function (req, res, next) {
  User.findById(req.session.userId).exec(function (error, user) {
    if (error) {
      return next(error);
    } else {
      if (user === null) {
        var err = new Error("Not authorized! Go back!");
        err.status = 400;
        return next(err);
      } else {
        //SEND NEW USERS TO IMAGE UPLOAD PAGE
        return res.sendFile(path.join(__dirname, "../public", "image.html"));
      }
    }
  });
});

As suggested, I tried declaring all of this as a middleware, so here is the middleware:

auth.js

module.exports.isAuthorized  = function(req, res, next) {

    User.findById(req.session.userId).exec(function (error, user) {
        if (error) {
            return next(error);
        } else {      
            if (user === null) {     
                var err = new Error('Not authorized! Go back!');
                err.status = 400;
                return next(err);
            } else {
                return next();
            }
        }
    });
}

Any help is gladly appreciated!

Source: How to setup an authentication middleware in Express.js

suigetsuh17
  • 55
  • 1
  • 7

1 Answers1

1

In the answer you referenced, it appears that user installed and is using Sequelize to store an individual's user data. If you would like to utilize that approach, I would look into Sequelize. As you mentioned on the other thread, User is not defined. For the other question, the asker most likely set up a model called User.

In Sequelize, each model (like User) defines a table that has its own rows and columns. Each column represents a field that applies to an individual row of data. For example, for a User model, one user may have a username, an email, and a password. You would specify what data types these columns should be and any other necessary information for each column of the Sequelize model definition. Each row represents one data-entry, or in this case, one user. I had previously built a sample web app that maps students to specific classes; below I have copied the Sequelize model definition I wrote for that project. It's quite simple and I would recommend watching some YouTube tutorials or checking out the Sequelize documentation at sequelize.org if this library is foreign to you.

Student.js

'use strict';

const Sequelize = require('sequelize');
const db = require('./_db');

const Student = db.define('student', {
    name: {
        type: Sequelize.STRING,
        allowNull: false,
        validate: {
            notEmpty: true
        }
    },
    phase: {
        type: Sequelize.STRING,
        allowNull: true,
        validate: {
            isIn: [['junior', 'senior', null]]
        }
    }
});

Student.findByPhase = async function(phase) {
    const students = await Student.findAll({
        where: {
            phase: phase
        }
    })
    return students
}

module.exports = Student;

It may also help to check out PostgreSQL or SQL in general as well to understand the basic framework that Sequelize lies on top of.

mbicknese
  • 11
  • 1
  • Thanks for the answer! I don;t mean to be rude, but I didn't see any sequelize on the other user question. I forgot to mention the db used is Mongo and not SQL, sorry about that. I already declared a user schema, and I'm just looking to reduce duplicate code, it's just some weird fetish I have – suigetsuh17 Jun 23 '20 at 19:08