user-service.js 2.56 KB
/**
 * Created by TaoHuang on 2017/4/17.
 */

'use strict';

const _ = require('lodash');
const Context = require('../framework/context');
const rp = require('request-promise');
const Api = require('../common/api');
const config = global.yoho.config;
const logger = global.yoho.logger;

const regSession = '${0}=([^;]+);';

class UserService extends Context {
  constructor() {
    super();
    this.api = this.instance(Api);
  }
  login(account, password) {
    return this.api
      .post(config.apiDomain.erp.login, {
        account,
        password,
        platform: config.platform,
      })
      .then(userInfo => {
        if (userInfo.code !== 200 || !userInfo.data.pid) {
          logger.error('[apiDomain.erp.login]', userInfo);
          return Promise.reject({ code: 500, message: '用户名密码错误' });
        }
        return userInfo.data;
      });
  }
  updatePwd(pid, password) {
    return this.api.post(config.apiDomain.erp.update, {
      pid,
      password,
    });
  }
  shopLogin(account, password) {
    return rp
      .get({
        url: config.apiDomain.shop.login,
        resolveWithFullResponse: true,
        qs: {
          user: account,
          password,
        },
      })
      .then(response => {
        return this._getShopsSession(response.rawHeaders);
      });
  }
  _getShopsSession(rawHeaders) {
    let sessId = '',
      sid = '';

    _.each(rawHeaders, header => {
      const sessIdMatched = header.match(new RegExp(regSession.replace('${0}', 'PHPSESSID')));
      const sidMatched = header.match(new RegExp(regSession.replace('${0}', 'connect.sid')));

      if (sessIdMatched) {
        sessId = sessIdMatched[1];
      }
      if (sidMatched) {
        sid = sidMatched[1];
      }
    });
    return {
      PHPSESSID: sessId,
      'connect.sid': sid,
    };
  }
  getShops(pid) {
    return this.api
      .get(config.apiDomain.platform.queryShopsByAdminPid, {
        userId: pid,
        platform: 4,
      })
      .then(result => {
        return result;
      });
  }
  switchShop(opts) {
    const options = {
      url: `${config.apiDomain.shop.switchShop}?shops_id=${opts.shopId}`,
      resolveWithFullResponse: true,
    };
    const jar = rp.jar();

    _.each(opts.cookies, (val, key) => {
      jar.setCookie(rp.cookie(`${key}=${val}`), options.url);
    });
    options.jar = jar;
    return rp.get(options).then(response => {
      return this._getShopsSession(response.rawHeaders);
    });
  }
  profile(pid) {
    return this.instance(Api).get(config.apiDomain.shop.profile.url, { userId: pid });
  }
}

module.exports = UserService;