auth-helper.js 2.42 KB
'use strict';
const _ = require('lodash');
const aes = require('./aes-pwd');
const logger = global.yoho.logger;
const api = global.yoho.API;

class Auth {

    static signin(area, profile, password, shoppingKey) {
        let param = {
            method: 'app.passport.signin',
            area: area,
            profile: profile,
            password: password
        };

        if (shoppingKey) {
            param.shopping_key = shoppingKey;
        }

        return api.post('', param);
    }

    static signinAes(area, profile, password, shoppingKey, ip, isSkip) {
        let param = {
            method: 'app.passport.signinAES',
            area: area,
            profile: profile,
            password: aes.aesPwd(password),
            isSkip: isSkip ? isSkip : 'N'
        };

        if (shoppingKey) {
            param.shopping_key = shoppingKey;
        }

        logger.info(`${profile}, login from ${ip}`);

        return api.post('', param, {
            headers: {
                'user-agent': 'yoho/nodejs',
                'X-YOHO-IP': ip,
                'X-Forwarded-For': ip
            }
        });
    }

    static signinByOpenID(nickname, openId, sourceType, shoppingKey) {
        let param = {
            nickname: nickname,
            openId: openId,
            source_type: sourceType, // esline-disable-line
            method: 'app.passport.signinByOpenID',
            shoppingKey: shoppingKey
        };

        if (shoppingKey) {
            param.shopping_key = shoppingKey;
        }

        return api.get('', param);
    }

    static profile(uid) {
        let param = {
            uid: uid,
            method: 'app.passport.profile'
        };

        return api.get('', param);
    }

    static syncUserSession(uid, req, res, sessionKey) {
        let userId = {
            toString: () => {
                return uid;
            }
        };

        if (sessionKey) {
            req.session.SESSION_KEY = sessionKey;
            userId.sessionKey = sessionKey;
        }

        return Auth.profile(userId).then((userInfo) => {
            let data = userInfo.data;

            if (data) {
                data.profile_name = (data.profile_name || '').replace(/::/g, '');
                _.set(req.session, 'user.avatar', data.head_ico);
                _.set(req.session, 'user.name', data.profile_name);
            }
            req.session.LOGIN_UID = uid;
        });
    }
}

module.exports = Auth;