user.js 1.8 KB
const moment = require('moment');
const _ = require('lodash');
const {yoho} = global.yoho.utils;
const {yohoSecret} = global.yoho.config;
const UserModel = require('../models/user');
const isProd = process.env.NODE_ENV === 'production';

const user = {
    getLoginUrl(req, res) {
        const url = req.query.url;

        if (!url) {
            return res.json({
                code: 400,
                loginUrl: '#'
            });
        }
        let params = {
            yh_type: 'activity',
            yh_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            yh_backurl: url
        };

        params.yh_sign = yoho.getSign(params, yohoSecret);
        let queryStr = _.join(_.map(params, (v, k) => {
            return `${k}=${encodeURIComponent(v)}`;
        }), '&');

        return res.json({
            code: 200,
            loginUrl: `http${isProd ? 's' : ''}://m.yohobuy.com/signin.html?${queryStr}`
        });
    },
    loginLog(req, res, next) {
        const uid = req.body.uid;

        if (!uid) {
            return res.json({
                code: 400
            });
        }
        const ip = req.get['X-Forwarded-For'] || req.ip || req.connection.remoteAddress;
        const loginTime = Date.now();
        let platform;
        const ua = req.get('user-agent');
        const referer = req.get('referer');


        if (/Android/.test(ua)) {
            platform = 'Android';
        } else if (/(iPhone)|(iPad)|(iPod)/.test(ua)) {
            platform = 'iPhone';
        } else {
            platform = 'Other';
        }

        return req.ctx(UserModel).loginLog({
            uid,
            ip,
            loginTime,
            platform,
            referer
        }).then(() => {
            return res.json({code: 200});
        }).catch(next);

    }
};

module.exports = user;