📅  最后修改于: 2020-10-25 11:10:25             🧑  作者: Mango
身份验证是一个过程,其中将提供的凭据与本地操作系统上或身份验证服务器内授权用户信息数据库中的凭据进行比较。如果凭据匹配,则过程完成,并且授予用户访问权限。
为了创建身份验证系统,我们需要创建一个注册页面和一个用户密码存储区。以下代码为我们创建了一个帐户并将其存储在内存中。这只是出于演示的目的;建议始终使用持久性存储(数据库或文件)来存储用户信息。
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret: "Your secret key"}));
var Users = [];
app.get('/signup', function(req, res){
res.render('signup');
});
app.post('/signup', function(req, res){
if(!req.body.id || !req.body.password){
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user){
if(user.id === req.body.id){
res.render('signup', {
message: "User Already Exists! Login or choose another user id"});
}
});
var newUser = {id: req.body.id, password: req.body.password};
Users.push(newUser);
req.session.user = newUser;
res.redirect('/protected_page');
}
});
app.listen(3000);
现在,对于注册表单,创建一个名为signup.jade的新视图。
html
head
title Signup
body
if(message)
h4 #{message}
form(action = "/signup" method = "POST")
input(name = "id" type = "text" required placeholder = "User ID")
input(name = "password" type = "password" required placeholder = "Password")
button(type = "Submit") Sign me up!
通过访问localhost:3000 / signup检查此页面是否加载。
我们为两个字段都设置了必填属性,因此启用HTML5的浏览器将不允许我们提交此表单,除非我们提供ID和密码。如果有人尝试使用不带用户ID或密码的卷曲请求进行注册,则会显示错误。在具有以下内容的视图中创建一个名为protected_page.pug的新文件-
html
head
title Protected page
body
div Hey #{id}, How are you doing today?
div Want to log out?
div Logout
仅当用户刚刚注册或登录时,此页面才可见。让我们现在定义其路由以及登录和注销的路由-
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret: "Your secret key"}));
var Users = [];
app.get('/signup', function(req, res){
res.render('signup');
});
app.post('/signup', function(req, res){
if(!req.body.id || !req.body.password){
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user){
if(user.id === req.body.id){
res.render('signup', {
message: "User Already Exists! Login or choose another user id"});
}
});
var newUser = {id: req.body.id, password: req.body.password};
Users.push(newUser);
req.session.user = newUser;
res.redirect('/protected_page');
}
});
function checkSignIn(req, res){
if(req.session.user){
next(); //If session exists, proceed to page
} else {
var err = new Error("Not logged in!");
console.log(req.session.user);
next(err); //Error, trying to access unauthorized page!
}
}
app.get('/protected_page', checkSignIn, function(req, res){
res.render('protected_page', {id: req.session.user.id})
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/login', function(req, res){
console.log(Users);
if(!req.body.id || !req.body.password){
res.render('login', {message: "Please enter both id and password"});
} else {
Users.filter(function(user){
if(user.id === req.body.id && user.password === req.body.password){
req.session.user = user;
res.redirect('/protected_page');
}
});
res.render('login', {message: "Invalid credentials!"});
}
});
app.get('/logout', function(req, res){
req.session.destroy(function(){
console.log("user logged out.")
});
res.redirect('/login');
});
app.use('/protected_page', function(err, req, res, next){
console.log(err);
//User should be authenticated! Redirect him to log in.
res.redirect('/login');
});
app.listen(3000);
我们创建了一个中间件函数checkSignIn检查,如果用户在签署该protected_page使用此函数。为了注销用户,我们销毁了会话。
现在让我们创建登录页面。将视图命名为login.pug并输入内容-
html
head
title Signup
body
if(message)
h4 #{message}
form(action = "/login" method = "POST")
input(name = "id" type = "text" required placeholder = "User ID")
input(name = "password" type = "password" required placeholder = "Password")
button(type = "Submit") Log in
我们的简单身份验证应用程序现已完成;现在让我们测试该应用程序。使用nodemon index.js运行该应用程序,然后继续进行localhost:3000 / signup。
输入用户名和密码,然后单击注册。如果详细信息有效/唯一,您将被重定向到protected_page-
现在退出该应用程序。这会将我们重定向到登录页面-
该路由受到保护,因此,如果未经身份验证的人尝试访问它,则将其重定向到我们的登录页面。这全部与基本用户身份验证有关。始终建议我们使用持久性会话系统,并使用散列进行密码传输。现在,利用JSON令牌,有更好的方法来对用户进行身份验证。