-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathstrategy.js
212 lines (192 loc) · 6.72 KB
/
strategy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Load modules.
var OAuthStrategy = require('passport-oauth1')
, util = require('util')
, uri = require('url')
, XML = require('xtraverse')
, Profile = require('./profile')
, InternalOAuthError = require('passport-oauth1').InternalOAuthError
, APIError = require('./errors/apierror');
/**
* `Strategy` constructor.
*
* The Twitter authentication strategy authenticates requests by delegating to
* Twitter using the OAuth protocol.
*
* Applications must supply a `verify` callback which accepts a `token`,
* `tokenSecret` and service-specific `profile`, and then calls the `cb`
* callback supplying a `user`, which should be set to `false` if the
* credentials are not valid. If an exception occured, `err` should be set.
*
* Options:
* - `consumerKey` identifies client to Twitter
* - `consumerSecret` secret used to establish ownership of the consumer key
* - `callbackURL` URL to which Twitter will redirect the user after obtaining authorization
*
* Examples:
*
* passport.use(new TwitterStrategy({
* consumerKey: '123-456-789',
* consumerSecret: 'shhh-its-a-secret'
* callbackURL: 'https://www.example.net/auth/twitter/callback'
* },
* function(token, tokenSecret, profile, cb) {
* User.findOrCreate(..., function (err, user) {
* cb(err, user);
* });
* }
* ));
*
* @constructor
* @param {object} options
* @param {function} verify
* @access public
*/
function Strategy(options, verify) {
options = options || {};
options.requestTokenURL = options.requestTokenURL || 'https://api.twitter.com/oauth/request_token';
options.accessTokenURL = options.accessTokenURL || 'https://api.twitter.com/oauth/access_token';
options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.twitter.com/oauth/authenticate';
options.sessionKey = options.sessionKey || 'oauth:twitter';
OAuthStrategy.call(this, options, verify);
this.name = 'twitter';
this._userProfileURL = options.userProfileURL || 'https://api.twitter.com/1.1/account/verify_credentials.json';
this._skipExtendedUserProfile = (options.skipExtendedUserProfile !== undefined) ? options.skipExtendedUserProfile : false;
this._includeEmail = (options.includeEmail !== undefined) ? options.includeEmail : false;
this._includeStatus = (options.includeStatus !== undefined) ? options.includeStatus : true;
this._includeEntities = (options.includeEntities !== undefined) ? options.includeEntities : true;
}
// Inherit from `OAuthStrategy`.
util.inherits(Strategy, OAuthStrategy);
/**
* Authenticate request by delegating to Twitter using OAuth.
*
* @param {http.IncomingMessage} req
* @param {object} [options]
* @access protected
*/
Strategy.prototype.authenticate = function(req, options) {
// When a user denies authorization on Twitter, they are presented with a link
// to return to the application in the following format (where xxx is the
// value of the request token):
//
// http://www.example.com/auth/twitter/callback?denied=xxx
//
// Following the link back to the application is interpreted as an
// authentication failure.
if (req.query && req.query.denied) {
return this.fail();
}
// Call the base class for standard OAuth authentication.
OAuthStrategy.prototype.authenticate.call(this, req, options);
};
/**
* Retrieve user profile from Twitter.
*
* This function constructs a normalized profile, with the following properties:
*
* - `id` (equivalent to `user_id`)
* - `username` (equivalent to `screen_name`)
*
* Note that because Twitter supplies basic profile information in query
* parameters when redirecting back to the application, loading of Twitter
* profiles *does not* result in an additional HTTP request, when the
* `skipExtendedUserProfile` option is enabled.
*
* @param {string} token
* @param {string} tokenSecret
* @param {object} params
* @param {function} done
* @access protected
*/
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
if (!this._skipExtendedUserProfile) {
var json;
var url = uri.parse(this._userProfileURL);
url.query = url.query || {};
if (url.pathname.indexOf('/users/show.json') == (url.pathname.length - '/users/show.json'.length)) {
url.query.user_id = params.user_id;
}
if (this._includeEmail == true) {
url.query.include_email = true;
}
if (this._includeStatus == false) {
url.query.skip_status = true;
}
if (this._includeEntities == false) {
url.query.include_entities = false;
}
this._oauth.get(uri.format(url), token, tokenSecret, function (err, body, res) {
if (err) {
if (err.data) {
try {
json = JSON.parse(err.data);
} catch (_) {}
}
if (json && json.errors && json.errors.length) {
var e = json.errors[0];
return done(new APIError(e.message, e.code));
}
return done(new InternalOAuthError('Failed to fetch user profile', err));
}
try {
json = JSON.parse(body);
} catch (ex) {
return done(new Error('Failed to parse user profile'));
}
var profile = Profile.parse(json);
profile.provider = 'twitter';
profile._raw = body;
profile._json = json;
// NOTE: The "X-Access-Level" header is described here:
// https://dev.twitter.com/oauth/overview/application-permission-model
// https://dev.twitter.com/oauth/overview/application-permission-model-faq
profile._accessLevel = res.headers['x-access-level'];
done(null, profile);
});
} else {
var profile = { provider: 'twitter' };
profile.id = params.user_id;
profile.username = params.screen_name;
done(null, profile);
}
};
/**
* Return extra Twitter-specific parameters to be included in the user
* authorization request.
*
* @param {object} options
* @return {object}
* @access protected
*/
Strategy.prototype.userAuthorizationParams = function(options) {
var params = {};
if (options.forceLogin) {
params.force_login = options.forceLogin;
}
if (options.screenName) {
params.screen_name = options.screenName;
}
return params;
};
/**
* Parse error response from Twitter OAuth endpoint.
*
* @param {string} body
* @param {number} status
* @return {Error}
* @access protected
*/
Strategy.prototype.parseErrorResponse = function(body, status) {
var json, xml;
try {
json = JSON.parse(body);
if (Array.isArray(json.errors) && json.errors.length > 0) {
return new Error(json.errors[0].message);
}
} catch (ex) {
xml = XML(body)
return new Error(xml.children('error').t() || body);
}
};
// Expose constructor.
module.exports = Strategy;