问题
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
回答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.
来源:https://stackoverflow.com/questions/62541651/setup-an-authentication-middleware-to-reduce-duplicate-code-in-express-js