基于session的用户登录识别
框架express
依赖的session模块express-session
1 主页面app.js
var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes'); var session = require('express-session'); var index = require('./routes/index'); var flash = require('connect-flash'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(flash()); app.use(session({ name: 'kk',// 设置 cookie 中保存 session id 的字段名称 secret: 'kk',// 通过设置 secret 来计算 hash 值并放在 cookie 中,使产生的 signedCookie 防篡改 cookie: { maxAge: 2592000000// 过期时间,过期后 cookie 中的 session id 自动删除 }, resave: false, saveUninitialized: true, //本应用中是将session存储到内存中。 //store: new MongoStore({// 将 session 存储到 mongodb //url: 'mongodb://localhost:27017/kk'// mongodb 地址 //}) })); app.use(function (req, res, next) { res.locals.user = req.session.user; 应用变量 res.locals.showname = req.session.showname; res.locals.success = req.flash('success'); res.locals.error = req.flash('error'); next(); }); routes(app); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
2 路由文件index.js
module.exports = function (app) { app.get('/', function (req, res) { if (!req.session.user) { //如果未有用户登录,跳转至登录 res.redirect('/login'); } if (req.session.user) { res.redirect('/home'); //如果已经有用户登录,跳转至住页面 } }); app.use('/login', require('./login')); //登录界面路由 app.use('/home', require('./home')); // 主页面路由 app.use('/logout', require('./logout')); //登出路由 // 404 page app.use(function (req, res) { if (!res.headersSent) { res.render('404'); } }); };
3 登录文件 login.js
var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var md5 = require('md5'); var connection = mysql.createConnection({host: '10.0.6.14', user: 'root', password: '123456', database: 'cop_c'});
//连接数据库 connection.connect(); router.get('/', function(req, res, next) { key = req.query.key; if (!key || (key.length !== 32)) { //安全机制,为每一个登录用户分配一个32为的key,在登录时以 http://ip/login?key=12234...32进行登录,如果没有key或者key不是32位,显示空白页面。 res.send(''); } if (req.session.user) { //如果已有用户登录,则跳转至主页面。 res.redirect('/home'); } res.render('login'); }); router.post('/', function(req, res, next) { var user = req.body.user; var xx = req.body.passwd; var passwd = md5(xx); //数据库中存储的是经过md5加密的密码。 sql = 'select showname from o_users where username="' + user + '" ' + 'and passwd= "' + passwd + '"and `key`="' + key + '"';
//showname是显示在主页面的用户名,存储在数据库中。 connection.query(sql, function(err, rows, fields) { if (err) throw err; if (rows.length==0) { //如果查询到数据库中有相匹配的用户,则登录,否则重新登录 req.flash('error', '用户密码错误') res.redirect('/login?key='+key); }else { req.session.showname=rows[0].showname; req.session.user = user; req.flash('success', '登录成功') res.redirect('/home?key='+key); } }); }); module.exports = router;
4 主页面index.js
var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { if(req.session.user){ res.render('home',{name:req.session.showname}) }else{ res.redirect('/login') } }); module.exports = router;
5 登出文件logout.js
var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { req.session.user = null; req.session.showname = null; res.redirect('/login') }); module.exports = router;
6主页面模板 home.jade
extends layout block content h1 #{showname} h1 #{success} h1 #{error} a(href='/logout')登出 p 这是主页
7登录模板 login.jade
extends layout block content .container h1 #{error} h1 #{success} form.form-signin(method="post", action="/login") h2 请登陆 .form-group label.sr-only 用户名 input.form-control#inputUser(placeholder="用户名", name="user", required, autofocus ) label.sr-only 密码 input.form-control#inputPassword(placeholder="密码", name="passwd",type="password" required, autofocus) button.btn.btn-lg.btn-primary.btn-block(type="submit") Sign in