javascript - 如何在nodejs中使用express进行身份验证后授予对文件夹的访问权限?
问题描述
我是nodejs的新手,我一直在寻找解决方案很长一段时间,不幸的是没有一个解决我的具体问题。或者至少我只是不明白。
在我的 nodejs 项目中,我使用了一个公共文件夹,其中存储了我的所有 html 和 js 文件。
在我做的公共文件夹之外的 server.js 中:
app.use(express.static(__dirname + '/public'));
一个特定的用户,我们称他为 Tom,将访问 tom-page.html。另一个用户,我们称他为 Fred,将访问 fred-page.html。这些文件及其脚本 (javascript) 都在该公用文件夹中。
现在我要做的是用静态密码保护公用文件夹。如果 Tom 登录,那么他应该被重定向到 /public/tom-page.html,而对于 Fred,它应该是 /public/fred-page.html。他们应该有权访问该文件夹中的所有其他文件。
到目前为止我做了什么:
const express = require('express');
const app = express();
var basicAuth = require('basic-auth');
var is_tom = false;
var auth = function(req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'fred' && user.pass === 'fred-pwd') {
is_tom = false;
return next();
} else if (user.name === 'tom' && user.pass === 'tom-pwd') {
is_tom = true;
return next();
} else {
return unauthorized(res);
}
};
const http = require('http');
server = http.createServer(app);
app.get('/', auth, function(req, res) {
if (is_tom) {
res.send('hi tom');
} else {
res.send('hi fred');
}
});
这行得通。但我不知道如何授予他们访问公用文件夹的权限,app.use(express.static(__dirname + '/public'));
并将他们重定向到他们的页面。
有人可以帮忙吗?
解决方案
我刚刚找到了一个可行的解决方案:
app.use(auth, express.static(__dirname + '/public'));
我刚刚在指定我正在使用的静态文件夹之前放置了身份验证。还有其他人有更好的建议吗?
推荐阅读
- amazon-web-services - 如何确定哪些 AMI 可用于选定的 AZ
- performance - 大内存使用会减慢不相关的代码
- django - 如何在 Django 中从购物车中删除产品?
- c - 当用户在 C 中输入“#”时,停止将字符串连接到动态数组
- jquery - jQuery jqgrid 不执行服务器调用
- android - 安装位置 2.3.5 包时出现 Flutter 编译器错误
- elasticsearch - 在弹性搜索的子聚合中过滤
- swift - 发布图像对象 Clarifai rest api swift
- swift - 从 Array Swift 的 Array 中删除元素
- c# - 如何使用交换方法交换类列表中存在的长变量