passport-taobao.js 1.57 KB
/**
 * Module dependencies.
 */
const util = require('util');
const TopClient = require('topsdk');
const { OAuth2Strategy, InternalOAuthError } = require('passport-oauth');

let client;

/**
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
    options = options || {};
    options.authorizationURL = options.authorizationURL || 'https://oauth.taobao.com/authorize?view=wap';
    options.tokenURL = options.tokenURL || 'https://oauth.taobao.com/token';
    options.scopeSeparator = options.scopeSeparator || ',';
    options.customHeaders = options.customHeaders || {};

    client = new TopClient(options.clientID, options.clientSecret, {
        endpoint: 'https://eco.taobao.com/router/rest',
        useValidators: true,
        rawResponse: false
    });

    if (!options.customHeaders['User-Agent']) {
        options.customHeaders['User-Agent'] = options.userAgent || 'passport-taobao';
    }

    OAuth2Strategy.call(this, options, verify);
    this.name = 'taobao';
    this._userProfileURL = options.userProfileURL || 'https://eco.taobao.com/router/rest';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);


/**
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function (accessToken, done) {
    client.execute('taobao.openuid.get', {
        session: accessToken
    }).then(res => {
        done(null, res);
    }).catch(e => {
        done(new InternalOAuthError('failed to fetch open uid', e));
    });
}

module.exports = Strategy;