user.js 1.36 KB
/**
 * 用户controller
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2017/04/13
 */
'use strict';

const Context = require('../common/context');
const UserService = require('../service/user-service');
const config = global.yoho.config;

class UserController extends Context {
    login(req, res, next) {
        this.instance(UserService).login(req.body.username, req.body.password).then(result => {
            if (result.code === 200) {
                this.syncSession(req, res, result.data);

                return res.json({
                    code: 200,
                    data: {
                        name: result.data.account
                    }
                });
            } else {
                return res.json({
                    code: 400,
                    message: '登录错误'
                });
            }
        }).catch(next);
    }
    logout(req, res) {
        delete res.session.LOGIN_UID;
        delete res.session.USER;
        res.clearCookie('USER_NAME');

        return res.json({
            code: 200,
            data: '登出成功'
        });
    }

    syncSession(req, res, user) {
        req.session.USER = user;
        req.session.LOGIN_UID = user.pid; // pid 为用户名

        res.cookie('USER_NAME', user.account, {
            domain: config.cookieDomain
        });
    }
}

module.exports = UserController;