设置身份验证中间件以减少Express.js中的重复代码 [英] Setup an authentication middleware to reduce duplicate code in Express.js

查看:46
本文介绍了设置身份验证中间件以减少Express.js中的重复代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想减少我呼叫的每条新路线的重复授权代码.我的问题是完全一样的,因为我们显然是从GitHub存储库下载了同一个项目.

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.

代码如下:

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!

来源:如何在Express.js中设置身份验证中间件

推荐答案

在您引用的答案中,似乎用户已安装并正在使用Sequelize存储个人的用户数据.如果您想使用这种方法,我将研究Sequelize.正如您在另一个线程上提到的,未定义用户.对于另一个问题,询问者最有可能建立了一个称为用户"的模型.

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.

在Sequelize中,每个模型(如 User )定义一个具有自己的行和列的表.每列代表一个字段,适用于单独的数据行.例如,对于用户模型,一个用户可能具有用户名,电子邮件和密码.您将指定这些列应为哪种数据类型,以及Sequelize模型定义的每个列的任何其他必要信息.每一行代表一个数据条目,或者在这种情况下代表一个用户.之前,我已经构建了一个示例Web应用程序,可将学生映射到特定班级.下面,我复制了我为该项目编写的Sequelize模型定义.这很简单,如果您不熟悉该库,我建议您观看一些YouTube教程或在sequelize.org上查看Sequelize文档.

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;

一般来说,检查PostgreSQL或SQL也可能有助于了解Sequelize位于其之上的基本框架.

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.

这篇关于设置身份验证中间件以减少Express.js中的重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆