Node.js + Express 4.x + MongoDB 构建登录注册-简易用户管理(四)

  登录和注册的功能算实现了,下面封装DBHelp和增加一个简单的用户管理,这样增删查改就集齐了。

  在routes文件夹下面新建DBHelp.js,代码如下:

const MongoClient=require('mongodb').MongoClient;
const DB_CONN_STR='mongodb://localhost:27017/userinfo';

function DBHelp(){}

/**************************
*
* 功能:条件查询,返回遇到的第一条符合条件的数据
* 参数:tableName(查询的表名)、selectStr(查询条件)、callback(回调函数)
*
**************************/
DBHelp.prototype.FindOne=function(tableName,selectStr,callback)
{
    MongoClient.connect(DB_CONN_STR,function(err,db)
    {
        db.collection(tableName).findOne(selectStr,function(err,result)
        {
            if(err)
            {
                console.log(err);
                return;
            }
            callback(result);
        });
        db.close();
    });
};

/**************************
*
* 功能:条件查询
* 参数:tableName(查询的表名)、selectStr(查询条件)、callback(回调函数)
*
**************************/
DBHelp.prototype.Find=function(tableName,selectStr,callback)
{
    MongoClient.connect(DB_CONN_STR,function(err,db)
    {
        db.collection(tableName).find(selectStr).toArray(function(err,result)
        {
            if(err)
            {
                console.log(err);
                return;
            }
            callback(result);
        });
        db.close();
    });
};

/**************************
*
* 功能:查询所有数据,显示指定字段
* 参数:tableName(查询的表名)、selectStr(查询条件)、callback(回调函数)
*
**************************/
DBHelp.prototype.FindAll=function(tableName,selectStr,callback)
{
    MongoClient.connect(DB_CONN_STR,function(err,db)
    {
        db.collection(tableName).find({},selectStr).toArray(function(err,result)
        {
            if(err)
            {
                console.log(err);
                return;
            }
            callback(result);
        });
        db.close();
    });
};

/**************************
*
* 功能:添加
* 参数:tableName(查询的表名)、dataStr(添加的数据)、callback(回调函数)
*
**************************/
DBHelp.prototype.Add=function(tableName,dataStr,callback)
{
    MongoClient.connect(DB_CONN_STR,function(err,db)
    {
        db.collection(tableName).insert(dataStr,function(err)
        {
            if(err)
            {
                console.log(err);
                return false;
            }
            else
            {
                callback();
            }
        });
        db.close();
    });
};

/**************************
*
* 功能:删除
* 参数:tableName(查询的表名)、delStr(删除条件)、callback(回调函数)
*
**************************/
DBHelp.prototype.Delete=function(tableName,delStr,callback)
{
    MongoClient.connect(DB_CONN_STR,function(err,db)
    {
        db.collection(tableName).remove(delStr,function(err)
        {
            if(err)
            {
                console.log(err);
                return false;
            }
            else
            {
                callback();
            }
        });
        db.close();
    });
};

/**************************
*
* 功能:修改
* 参数:tableName(查询的表名)、whereStr(修改条件)、updateStr(修改数据)、callback(回调函数)
*
**************************/
DBHelp.prototype.Update=function(tableName,whereStr,updateStr,callback)
{
    MongoClient.connect(DB_CONN_STR,function(err,db)
    {
        db.collection(tableName).update(whereStr,updateStr,function(err)
        {
            if(err)
            {
                console.log(err);
                return false;
            }
            else
            {
                callback();
            }
        });
        db.close();
    });
};

module.exports=DBHelp;

  修改index.js文件,代码如下:

var express = require('express');
var router = express.Router();
const DBHelp=require('./DBHelp');

/* GET home page. */
router.get('/', function(req, res, next)
{
  res.render('index', { title: 'Index' });
});


//登录
router.route('/login').all(Logined).get(function(req,res)
{
    res.render('login',{title:'Login'});
}).post(function(req,res)
{
    //从前端获取到的用户填写的数据
    let user={username:req.body.username,password:req.body.password};
    //用于查询用户名是否存在的条件
    let selectStr={username:user.username};
    let dbhelp=new DBHelp();
    dbhelp.FindOne('users',selectStr,function(result)
    {
        if(result)
        {
            if(result.password===user.password)
            {
                //出于安全,只把包含用户名的对象存入session
                req.session.user=selectStr;
                return res.redirect('/home');
            }
            else
            {
                req.session.error='用户名或者密码错误!';
                return res.redirect('/login');
            }
        }
        else
        {
            req.session.error='账号不存在!';
            return res.redirect('/login');
        }
    });
});


//注册
router.route('/register').all(Logined).get(function(req,res)
{
    res.render('register',{title:'Register123'});
}).post(function(req,res)
{
    //从前端获取到的用户填写的数据
    let newUser={username:req.body.username,password:req.body.password,passwordSec:req.body.passwordSec};
    //准备添加到数据库的数据(数组格式)
    let addStr=[{username:newUser.username,password:newUser.password}];
    //用于查询用户名是否存在的条件
    // let selectStr={username:newUser.username};
    let dbhelp=new DBHelp();
    dbhelp.FindOne('users',{username:newUser.username},function(result)
    {
        if(!result)
        {
            if(newUser.password===newUser.passwordSec)
            {
                dbhelp.Add('users',addStr,function()
                {
                    req.session.error='注册成功,请登录!';
                    return res.redirect('/login');
                });
            }
            else
            {
                req.session.error='两次密码不一致!';
                return res.redirect('/register');
            }
        }
        else
        {
            req.session.error='用户名已存在!';
            return res.redirect('/register');
        }
    });
});


//Home用户管理
router.route('/home').all(LoginFirst).get(function(req,res)
{
    let selectStr={username:1,_id:0}
    let dbhelp=new DBHelp();
    dbhelp.FindAll('users',selectStr,function(result)
    {
        if(result)
        {
            res.render('home',{title:'Home',Allusers:result});
        }
        else
        {
            res.render('home',{title:'Home'});
        }
    });
});

//删除
router.route('/delete/:URLusername').get(function(req,res)
{
    if(req.params.URLusername!==req.session.user.username)
    {
        let whereStr={username:req.params.URLusername};
        let dbhelp=new DBHelp();
        dbhelp.Delete('users',whereStr,function()
        {
            req.session.error='移除用户 '+whereStr.username+' 成功!';
            return res.redirect('/home');
        });
    }
    else
    {
        req.session.error="不能操作当前登录用户!";
        return res.redirect('/home');
    }
});

//重置密码
router.get('/resetPwd/:URLusername',function(req,res)
{
    if(req.params.URLusername!==req.session.user.username)
    {
        let whereStr={username:req.params.URLusername};
        let update={$set:{password:'123456'}};
        let dbhelp=new DBHelp();
        dbhelp.Update('users',whereStr,update,function()
        {
            req.session.error=whereStr.username+' 的密码已重置为 123456!';
            return res.redirect('/home');
        });
    }
    else
    {
        req.session.error="不能操作当前登录用户!";
        return res.redirect('/home');
    }
});

//注销
router.get('/logout',function(req,res)
{
    req.session.user=null;
    return res.redirect('/');
});

function Logined(req,res,next)
{
    if(req.session.user)
    {
        req.session.error='您已登录!';
        return res.redirect('/home');
    }
    next();
}

function LoginFirst(req,res,next)
{
    if(!req.session.user)
    {
        req.session.error='请先登录!';
        return res.redirect('/login');
    }
    next();
}

module.exports = router;

  在home.html中展示简单的用户列表,代码如下:

  使用了简单的ejs语法,简单明了,想深入了解的可以自行百度。

<% include header.html %>
<%-message%>
<h1><%= title %></h1>
<p>Welcome<span class="fuzq_home_name"><%= user.username %></span>to <%= title %></p>
<a href="/logout">注销</a>
<div class="fuzq_home_manage">
    <h3>用户管理</h3>
    <table class="fuzq_home_manage_table">
        <tr>
            <th>用户名</th>
            <th>操作</th>
        </tr>
        <% Allusers.forEach(function(u){
            if(u.username===user.username){%>
            <tr>
                <td style="color:#3c3;"><%-u.username%></td>
                <td>
                    <span style="color:#3c3;">当前用户</span>
                </td>
            </tr>
            <%}
            else{%>
            <tr>
                <td><%-u.username%></td>
                <td>
                    <span><a href="/delete/<%-u.username%>">删除</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/resetPwd/<%-u.username%>">重置密码</a></span>
                </td>
            </tr>
            <%}
        })%>
    </table>
</div>
<% include footer.html %>

  home.html页面的头部和尾部也分开了,分别在views文件夹下新建header.html和footer.html,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  </body>
</html>

 

posted @ 2017-04-21 15:04  子非魚87  阅读(490)  评论(0编辑  收藏  举报