Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
drudge committed Nov 9, 2012
0 parents commit 9f97a70
Show file tree
Hide file tree
Showing 8 changed files with 328 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
.DS_Store
node_modules
8 changes: 8 additions & 0 deletions .npmignore
@@ -0,0 +1,8 @@
*.md
.DS_Store
.git*
Makefile
docs/
examples/
support/
test/
5 changes: 5 additions & 0 deletions .travis.yml
@@ -0,0 +1,5 @@
language: "node_js"
node_js:
- 0.4
- 0.6
- 0.8
20 changes: 20 additions & 0 deletions LICENSE
@@ -0,0 +1,20 @@
(The MIT License)

Copyright (c) 2012 Nicholas Penree

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
79 changes: 79 additions & 0 deletions README.md
@@ -0,0 +1,79 @@
# Passport-Twitter-Token

[Passport](http://passportjs.org/) strategy for authenticating with [Twitter](http://twitter.com/) tokens
using the OAuth 1.0a API.

This module lets you authenticate using Twitter in your Node.js applications.
By plugging into Passport, Twitter authentication can be easily and
unobtrusively integrated into any application or framework that supports
[Connect](http://www.senchalabs.org/connect/)-style middleware, including
[Express](http://expressjs.com/).

## Installation

$ npm install passport-twitter-token

## Usage

#### Configure Strategy

The Twitter authentication strategy authenticates users using a Twitter account
and OAuth tokens. The strategy requires a `verify` callback, which receives the
access token and corresponding secret as arguments, as well as `profile` which
contains the authenticated user's Twitter profile. The `verify` callback must
call `done` providing a user to complete authentication.

In order to identify your application to Twitter, specify the consumer key,
consumer secret, and callback URL within `options`. The consumer key and secret
are obtained by [creating an application](https://dev.twitter.com/apps) at
Twitter's [developer](https://dev.twitter.com/) site.

passport.use(new TwitterTokenStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET
},
function(token, tokenSecret, profile, done) {
User.findOrCreate({ twitterId: profile.id }, function (err, user) {
return done(err, user);
});
}
));

#### Authenticate Requests

Use `passport.authenticate()`, specifying the `'twitter-token'` strategy, to
authenticate requests.

For example, as route middleware in an [Express](http://expressjs.com/)
application:

app.post('/auth/twitter/token',
passport.authenticate('twitter-token'));

## Credits

- [Nicholas Penree](http://github.com/drudge)
- [Jared Hanson](http://github.com/jaredhanson)

## License

(The MIT License)

Copyright (c) 2012 Nicholas Penree

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15 changes: 15 additions & 0 deletions lib/passport-twitter-token/index.js
@@ -0,0 +1,15 @@
/**
* Module dependencies.
*/
var Strategy = require('./strategy');


/**
* Framework version.
*/
require('pkginfo')(module, 'version');

/**
* Expose constructors.
*/
exports.Strategy = Strategy;
175 changes: 175 additions & 0 deletions lib/passport-twitter-token/strategy.js
@@ -0,0 +1,175 @@
/**
* Module dependencies.
*/
var util = require('util')
, OAuthStrategy = require('passport-oauth').OAuthStrategy
, InternalOAuthError = require('passport-oauth').InternalOAuthError;


/**
* `TwitterTokenStrategy` 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 `done`
* 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
*
* Examples:
*
* passport.use(new TwitterTokenStrategy({
* consumerKey: '123-456-789',
* consumerSecret: 'shhh-its-a-secret'
* },
* function(token, tokenSecret, profile, done) {
* User.findOrCreate(..., function (err, user) {
* done(err, user);
* });
* }
* ));
*
* @param {Object} options
* @param {Function} verify
* @api public
*/
function TwitterTokenStrategy(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-token';

this._skipExtendedUserProfile = (options.skipExtendedUserProfile === undefined) ? false : options.skipExtendedUserProfile;
}

/**
* Inherit from `OAuthTwitterTokenStrategy`.
*/
util.inherits(TwitterTokenStrategy, OAuthStrategy);


/**
* Authenticate request by delegating to Twitter using OAuth.
*
* @param {Object} req
* @api protected
*/
TwitterTokenStrategy.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();
}

var token = req.body.token || req.query.token;
var tokenSecret = req.body.token_secret || req.query.token_secret;
var userId = req.body.user_id || req.query.user_id;
var params = { user_id: userId };

self._loadUserProfile(token, tokenSecret, params, function(err, profile) {
if (err) { return self.error(err); };

function verified(err, user, info) {
if (err) { return self.error(err); }
if (!user) { return self.fail(info); }
self.success(user, info);
}

var arity = self._verify.length;
if (arity == 5) {
self._verify(token, tokenSecret, params, profile, verified);
} else { // arity == 4
self._verify(token, tokenSecret, profile, verified);
}
});
}

/**
* 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` is enabled.
*
* @param {String} token
* @param {String} tokenSecret
* @param {Object} params
* @param {Function} done
* @api protected
*/
TwitterTokenStrategy.prototype.userProfile = function(token, tokenSecret, params, done) {
if (!this._skipExtendedUserProfile) {
this._oauth.get('https://api.twitter.com/1/users/show.json?user_id=' + params.user_id, token, tokenSecret, function (err, body, res) {
if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); }

try {
var json = JSON.parse(body);

var profile = { provider: 'twitter' };
profile.id = json.id;
profile.username = json.screen_name;
profile.displayName = json.name;
profile.photos = [{ value: json.profile_image_url_https }];

profile._raw = body;
profile._json = json;

done(null, profile);
} catch(e) {
done(e);
}
});
} 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}
* @api protected
*/
TwitterTokenStrategy.prototype.userAuthorizationParams = function(options) {
var params = {};
if (options.forceLogin) {
params['force_login'] = options.forceLogin;
}
if (options.screenName) {
params['screen_name'] = options.screenName;
}
return params;
}


/**
* Expose `TwitterTokenStrategy`.
*/
module.exports = TwitterTokenStrategy;
24 changes: 24 additions & 0 deletions package.json
@@ -0,0 +1,24 @@
{
"name": "passport-twitter-token",
"version": "0.1.0",
"description": "Twitter token authentication strategy for Passport.",
"author": { "name": "Nicholas Penree", "email": "nick@penree.com", "url": "http://penree.com" },
"repository": {
"type": "git",
"url": "git://github.com/drudge/passport-twitter-token.git"
},
"bugs": {
"url": "http://github.com/drudge/passport-twitter-token/issues"
},
"main": "./lib/passport-twitter-token",
"dependencies": {
"pkginfo": "0.2.x",
"passport-oauth": "0.1.x"
},
"engines": { "node": ">= 0.4.0" },
"licenses": [ {
"type": "MIT",
"url": "http://www.opensource.org/licenses/MIT"
} ],
"keywords": ["passport", "twitter", "auth", "authn", "authentication", "identity"]
}

0 comments on commit 9f97a70

Please sign in to comment.