users.js 1.98 KB
/**
 * 用户管理
 * @author: jiangfeng<jeff.jiang@yoho.cn>
 * @date: 16/8/16
 */

'use strict';
const Router = require('koa-router');
const md5 = require('md5');
const {User} = require('../../models');
const Operation = require('../../logger/operation');

const r = new Router;

const user = {
    async setting_page(ctx) {
        let users = await User.findAll();

        await ctx.render('action/users', {
            users: users
        });
    },
    async new_page(ctx) {
        await ctx.render('action/users_form');
    },
    async edit_page(ctx) {
        let id = ctx.query.id;
        let user = await User.findById(id);

        user.password = "******";
        await ctx.render('action/users_form', user);
    },
    async save(ctx) {
        let {_id, username, password, role, state} = ctx.request.body;
        let user = {
            username: username,
            role: role,
            state: state
        };

        if (password !== '******') {
            user.password = md5(password);
        }

        if (_id) {
            await User.update({
                _id: _id
            }, {
                $set: user
            });
            await Operation.action(ctx.session.user, 'EDIT_USER', '修改用户', {_id: _id, username: user.username});
        } else {
            await User.insert(user);
            await Operation.action(ctx.session.user, 'NEW_USER', '新增用户', {_id: _id, username: user.username});
        }
        ctx.redirect('/users/setting');
        ctx.status = 301;
    },
    async del(ctx) {
        let id = ctx.request.body.id;
        let u = await User.findById(id);
        await User.removeById(id);

        await Operation.action(ctx.session.user, 'DELETE_USER', '删除用户', {_id: id, username: u.username});
        ctx.body = {
            code: 200
        };
    }
};

r.get('/setting', user.setting_page);
r.get('/new', user.new_page);
r.get('/edit', user.edit_page);
r.post('/save', user.save);
r.post('/del', user.del);

module.exports = r;