【发布时间】:2021-03-06 15:47:53
【问题描述】:
我有一个名为authorized 的全局变量,最初设置为false。然后应该在名为isAuth(..) 的函数中将其设置为true。这样可以正常工作。
但最初,用户会看到form,他应该在其中输入用户名、密码和密码,正如您在form(其中显示if(req.url == "/"))中看到的那样。然后form 有一个调用TwoFA 的动作。问题在于这个。我检查if((req.url == "/TwoFA" && !authorized) {,此时authorized 应该设置为true,因为它是在isAuth(...) 函数中设置的。当用户按下提交按钮时,它会将 url 更改为“/TwoFA”,然后首先将 authorized 变量更改为 true。
我该怎么办?我希望它在执行/TwoFA 函数之前运行检查isAuth(...)。
这是我的代码
var authorized = false;
function isAuth(name, pass, pin) {
if(name === nameOK && pass === passOK && pin === pinOK) {
authorized = true;
return true;
} else {
return false;
}
}
var server = http.createServer(function(req, resp) {
if(req.method == "POST") {
collectRequestData(req, result => {
let uName = result.uName;
let pwd = result.pwd;
let pin = result.pin;
let tlf = result.tlf;
if(isAuth(uName, pwd, pin)) {
sendMail(token);
} else {
print("Wrong credentials");
return;
}
});
if(req.url == "/") {
resp.writeHead(200, { 'Content-Type': 'text/html'});
var html = "<!DOCTYPE html>\n<html>"+
"<head>"+
"<title>Webproj</title>"+
"</head>"+
"<body>" +
"<div id='cDiv'>"+
"<h2> Welcome.</h2>"+
"<form action='TwoFA' method='post'>"+
"<p>Username <input type='text' id='uName' name='uName' /></p>"+
"<p>Password<input type='password' id='pwd' name='pwd' /></p>"+
"<p>Pin code<input type='password' pattern='[0-9]*' inputmode='numeric' id='pin' name='pin' /></p>"+
"<p>Your phone number (for the token)</p><p><input type='number' id='tlf' name='tlf' /></p>"+
"<p><input type='submit' value='Login'>"+
"</form>"+
"</div>"+
"</body>"+
"</html>";
resp.write(html);
return;
}
if((req.url == "/TwoFA" && !authorized) {
resp.writeHead(200, { 'Content-Type': 'text/html'});
resp.write('<html><body><p>You are not authorized to see this page</p></html>');
return;
}
});
function TwoFA(user, pwd) {
var html = "<!DOCTYPE html>\n<html>"+
"<head>"+
"<title>Webproj</title>"+
"</head>"+
"<body>" +
"<div id='cDiv'>"+
"<h2> Enter token.</h2>"+
"<form action='finalPage' method='post'>"+
"<p>Username <input type='text' id='uName' name='uName' value='"+user+"' /></p>"+
"<p>Password<input type='password' id='pwd' name='pwd' value='"+pwd+"' /></p>"+
"<div id='token' style='visibility: visible;'>Token<input type='number' name='token' /></div>"+
"<p><input type='submit' value='Login'>"+
"</form>"+
"</div>"+
"</body>"+
"</html>";
return html;
}
server.listen(1110);
我找到了一个问题几乎相似的主题,但我没有找到解决方案 Executing code before any action
【问题讨论】:
-
为什么不将您的 isAuth 检查添加到此逻辑发生的位置:当用户按下提交按钮时,它会将 url 更改为“/TwoFA” 您拥有它的方式,这看起来并不局限于服务器。 我希望它在执行 /TwoFA 函数之前运行检查 isAuth(...) 您的 isAuth 似乎在服务器端运行,TwoFA 似乎在客户端运行。
标签: javascript node.js