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

'use strict';
import Router from 'koa-router';
import md5 from 'md5';
import {User} from '../../models';
import Operation from '../../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);

export default r;