user.js 2.1 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 _ = require('lodash');

class UserController extends Context {
    constructor() {
        super();
        this.userService = this.instance(UserService);
    }
    login(req, res, next) {
        this.userService.login(req.body.username, req.body.password).then(user => {
            this.userService.getShops(user.pid).then(result => {
                if (result.code === 200) {
                    this.syncSession(req, Object.assign(user, {
                        shops: result.data
                    }));
                    let currentShop = _.first(result.data);

                    return res.json({
                        code: 200,
                        data: {
                            name: user.account,
                            email: user.email,
                            createDate: user.create_date,
                            shops: _.map(result.data, shop => {
                                return {
                                    id: shop.id,
                                    shopName: shop.shopName
                                };
                            }),
                            currentShop: {
                                shopName: currentShop.shopName,
                                id: currentShop.id
                            }
                        }
                    });
                } else {
                    return res.json(result);
                }
            });
        }, err => {
            return res.json(err);
        }).catch(next);
    }

    logout(req, res) {
        delete req.session.USER;
        delete req.session.LOGIN_UID;
        delete req.session.CURRENT_SHOP;
        return res.json({
            code: 200,
            data: '登出成功'
        });
    }

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

module.exports = UserController;