使用express+mongoDB搭建多人博客 学习(5)权限控制

时间:2020-12-02 02:37:56

修改index.js如下:

var express = require('express');
var router = express.Router();
var crypto=require('crypto');
var User=require("../models/user.js");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: '主页',error:req.flash("error").toString(),
      success:req.flash("success").toString(), user:req.session.user });
});

router.get('/reg',checkNotLogin);
router.get('/reg',function(req,res,next){
    res.render('reg', { title: '注册' });
});

router.post('/reg',checkNotLogin);
router.post('/reg',function(req,res,next){
    var name=req.body.name,
    password=req.body.password,
    repassword=req.body.repassword;

    if(repassword!==password){
        req.flash("error","两次输入的密码不一致");
        return res.redirect("/reg");
    }

    var md5=crypto.createHash('md5');
    password=md5.update(req.body.password).digest('hex');
    var newUser=new User({
        name:req.body.name,
        password:password,
        email:req.body.email
    });
    User.get(newUser.name,function(err,user){
        if(user){
            req.flash('error',"用户名已存在");
            return res.redirect("/reg");
        }
        newUser.save(function(err,user){
            if(err){
                req.flash("error",err);
                return res.redirect("/reg");
            }
            req.session.user=user;
            req.flash("success","注册成功");
            res.redirect("/");
        });
    });
});

router.get('/login',checkNotLogin);
router.get('/login',function(req,res,next){
    res.render('login', { title: '登录' });
});

router.post('/login',checkNotLogin);
router.post('/login',function(req,res,next){
    var md5=crypto.createHash("md5");
    password=md5.update(req.body.password).digest('hex');
    User.get(req.body.name,function(err,user){
        if(!user){
            req.flash('error',"用户不存在");
            return res.redirect("/login");
        }
        if(user.password!==password){
            req.flash("error","密码错误");
            return res.redirect("/login");
        }
        req.flash("user",req.session.user=user);
        req.flash('success',"登录成功");
        res.redirect("/");
    })
});

router.get('/logout',checkLogin);
router.get("/logout",function(req,res){
    req.flash("user",req.session.user=null);
    req.flash("success","登出成功");
    res.redirect("/");
});

router.get('/post',checkLogin);
router.get('/post',function(req,res,next){
    res.render('post', { title: '发表' });
});

router.post('/post',checkLogin);
router.post('/post',function(req,res,next){
});



function checkLogin(req,res,next){
    if(!req.session.user){
        req.flash("error","未登录");
        return res.redirect("/login");
    }
    next();
}

function checkNotLogin(req,res,next){
    if(req.session.user){
        req.flash("error","已登录");
        return res.redirect("back"); } next(); }

module.exports = router;