passport-typcn-account
Version:
typcn account authentication strategy for Passport.
77 lines (67 loc) • 2.38 kB
JavaScript
/**
* Module dependencies.
*/
const util = require('util')
, OAuth2Strategy = require('passport-oauth').OAuth2Strategy
, InternalOAuthError = require('passport-oauth').InternalOAuthError;
const qs = require('querystring');
function Strategy(options, verify) {
OAuth2Strategy.prototype.authorizationParams = function(opt) {
return {
appid:options.clientID
};
};
options = options || {};
options.authorizationURL = options.authorizationURL || 'https://accounts.typcn.com/api/oauth/start';
options.tokenURL = options.tokenURL || 'https://accounts.typcn.com/api/oauth/access_token';
options.scopeSeparator = options.scopeSeparator || ',';
OAuth2Strategy.call(this, options, verify);
this.name = 'typaccount';
let _request = this._oauth2._request.bind(this._oauth2);
this._oauth2._request = function(method, url, headers, post_body, access_token, callback) {
if(post_body){
if(headers['Content-Type'] == 'application/x-www-form-urlencoded'){
headers['Content-Type'] = 'application/json';
}
post_body = post_body.replace('client_id','appid').replace('client_secret','appsecret');
let post_json = qs.parse(post_body);
post_body = JSON.stringify(post_json);
}
return _request(method, url, headers, post_body, access_token, callback);
}
this._oauth2.get = function(url, access_token, callback) {
return this._request('GET', url, {'Authorization':access_token}, null, null, callback );
};
}
util.inherits(Strategy, OAuth2Strategy);
Strategy.prototype.userProfile = function(accessToken, done) {
if(!accessToken){
return done(new Error(400));
}
let oauth2 = this._oauth2;
console.log('userProfile',accessToken);
oauth2.get('https://accounts.typcn.com/api/user/info', accessToken, function (err, body, res) {
if(err){
return done(err);
}
let json = JSON.parse(body);
if(json.code !== 0){
return done(new Error(body.code));
}
let user = json.data.user;
let profile = { provider: 'typaccount' };
profile.id = user._id;
profile.nickname = user.name;
profile.email = user.email;
profile.phone = user.phone;
profile.permission = user.type;
profile.avatar = user.avatar;
profile._raw = body;
profile._json = json;
done(null, profile);
});
}
/**
* Expose `Strategy`.
*/
module.exports = Strategy;