login-service.js 2.4 KB
/**
 * Created by TaoHuang on 2016/7/25.
 */

'use strict';
const md5 = require('md5');
const _ = require('lodash');

const cache = global.yoho.cache;
const sign = global.yoho.sign;
const config = global.yoho.config;
const crypto = global.yoho.crypto;

const api = require('./login-api');
const UserService = require('./user-service');

/**
 * 登录,包括微信和其它第三方
 */
const signinByOpenIDAsync = (nickname, openId, sourceType, shoppingKey, unionId) => {
    let signinFunc = {
        other: api.signinByOtherOpenIDAsync,
        wechat: api.signinByWechatAsync
    };

    // PC 的微信登录之前使用了 open_id, 所以需要特别的接口处理
    let type = sourceType !== 'wechat' ? 'other' : sourceType;

    return signinFunc[type](nickname, openId, sourceType, shoppingKey, unionId);
};

/**
 * 同步用户信息到session
 */
const syncUserSession = (uid, req, res) => {
    return UserService.profileAsync(uid).then((userInfo) => {
        let token = sign.makeToken(uid);
        let user = userInfo.data;

        if (!_.isEmpty(user)) {
            let uidCookie = `${user.profile_name}::${crypto.encryption('', user.uid + '')}::${user.username}::${token}`;

            req.session._TOKEN = token;
            req.session._LOGIN_UID = uid;
            req.session._USERNAME = user.username;

            res.cookie('_UID', uidCookie, {
                domain: config.cookieDomain
            });

            res.cookie('_USERNAME', user.username, {
                domain: config.cookieDomain
            });
        }

        req.session._TOKEN = token; // esline-disable-line
        req.session._LOGIN_UID = uid; // esline-disable-line
        res.cookie('_TOKEN', token, {
            domain: config.cookieDomain
        }); // esline-disable-line

    });
};

/**
 * 把个人信息保存在缓存
 */
const rememberAccountAsync = (accountInfo, req, res) => {
    let aWeek = (new Date()).getTime() / 1000 + 504000; // 504000-一周
    let rememKey = md5(md5(accountInfo.account + accountInfo.password + accountInfo.area));

    res.cookie('isRemember', true, {
        maxAge: aWeek,
        domain: config.cookieDomain
    });
    res.cookie('remem', rememKey, {
        maxAge: aWeek,
        domain: config.cookieDomain
    });

    return cache.set(rememKey, accountInfo);

};

module.exports = {
    signinAsync: api.signinAsync,
    signinByOpenIDAsync,
    syncUserSession,
    rememberAccountAsync
};