Permalink
Browse files

Initial commit.

  • Loading branch information...
0 parents commit 2d36ab6ce32cbab5d17ddce0fd867c29ddcc2f08 @jaredhanson committed Nov 29, 2011
2 .gitignore
@@ -0,0 +1,2 @@
+.DS_Store
+node_modules
8 .npmignore
@@ -0,0 +1,8 @@
+*.md
+.DS_Store
+.git*
+Makefile
+docs/
+examples/
+support/
+test/
20 LICENSE
@@ -0,0 +1,20 @@
+(The MIT License)
+
+Copyright (c) 2011 Jared Hanson
+
+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.
19 Makefile
@@ -0,0 +1,19 @@
+NODE = node
+TEST = vows
+TESTS ?= test/*-test.js
+
+test:
+ @NODE_ENV=test NODE_PATH=lib $(TEST) $(TEST_FLAGS) $(TESTS)
+
+docs: docs/api.html
+
+docs/api.html: lib/passport-tumblr/*.js
+ dox \
+ --title Passport-Tumblr \
+ --desc "Tumblr authentication strategy for Passport" \
+ $(shell find lib/passport-tumblr/* -type f) > $@
+
+docclean:
+ rm -f docs/*.{1,html}
+
+.PHONY: test docs docclean
31 README.md
@@ -0,0 +1,31 @@
+# Passport-Tumblr
+
+[Passport](https://github.com/jaredhanson/passport) strategy for authenticating
+with Tumblr using the OAuth 1.0a API.
+
+## Credits
+
+ - [Jared Hanson](http://github.com/jaredhanson)
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2011 Jared Hanson
+
+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.
122 examples/login/app.js
@@ -0,0 +1,122 @@
+var express = require('express')
+ , passport = require('passport')
+ , util = require('util')
+ , TumblrStrategy = require('passport-tumblr').Strategy;
+
+var TUMBLR_CONSUMER_KEY = "--insert-tumblr-consumer-key-here--"
+var TUMBLR_SECRET_KEY = "--insert-tumblr-secret-key-here--";
+
+
+// Passport session setup.
+// To support persistent login sessions, Passport needs to be able to
+// serialize users into and deserialize users out of the session. Typically,
+// this will be as simple as storing the user ID when serializing, and finding
+// the user by ID when deserializing. However, since this example does not
+// have a database of user records, the complete Tumblr profile is serialized
+// and deserialized.
+passport.serializeUser(function(user, done) {
+ done(null, user);
+});
+
+passport.deserializeUser(function(obj, done) {
+ done(null, obj);
+});
+
+
+// Use the TumblrStrategy within Passport.
+// Strategies in passport require a `verify` function, which accept
+// credentials (in this case, a token, tokenSecret, and Tumblr profile), and
+// invoke a callback with a user object.
+passport.use(new TumblrStrategy({
+ consumerKey: TUMBLR_CONSUMER_KEY,
+ consumerSecret: TUMBLR_SECRET_KEY,
+ callbackURL: "http://127.0.0.1:3000/auth/tumblr/callback"
+ },
+ function(token, tokenSecret, profile, done) {
+ // asynchronous verification, for effect...
+ process.nextTick(function () {
+
+ // To keep the example simple, the user's Tumblr profile is returned to
+ // represent the logged-in user. In a typical application, you would want
+ // to associate the Tumblr account with a user record in your database,
+ // and return that user instead.
+ return done(null, profile);
+ });
+ }
+));
+
+
+
+
+var app = express.createServer();
+
+// configure Express
+app.configure(function() {
+ app.set('views', __dirname + '/views');
+ app.set('view engine', 'ejs');
+ app.use(express.logger());
+ app.use(express.cookieParser());
+ app.use(express.bodyParser());
+ app.use(express.methodOverride());
+ app.use(express.session({ secret: 'keyboard cat' }));
+ // Initialize Passport! Also use passport.session() middleware, to support
+ // persistent login sessions (recommended).
+ app.use(passport.initialize());
+ app.use(passport.session());
+ app.use(app.router);
+ app.use(express.static(__dirname + '/public'));
+});
+
+
+app.get('/', function(req, res){
+ res.render('index', { user: req.user });
+});
+
+app.get('/account', ensureAuthenticated, function(req, res){
+ res.render('account', { user: req.user });
+});
+
+app.get('/login', function(req, res){
+ res.render('login', { user: req.user });
+});
+
+// GET /auth/tumblr
+// Use passport.authenticate() as route middleware to authenticate the
+// request. The first step in Tumblr authentication will involve redirecting
+// the user to tumblr.com. After authorization, Tumblr will redirect the user
+// back to this application at /auth/tumblr/callback
+app.get('/auth/tumblr',
+ passport.authenticate('tumblr'),
+ function(req, res){
+ // The request will be redirected to Tumblr for authentication, so this
+ // function will not be called.
+ });
+
+// GET /auth/tumblr/callback
+// Use passport.authenticate() as route middleware to authenticate the
+// request. If authentication fails, the user will be redirected back to the
+// login page. Otherwise, the primary route function function will be called,
+// which, in this example, will redirect the user to the home page.
+app.get('/auth/tumblr/callback',
+ passport.authenticate('tumblr', { failureRedirect: '/login' }),
+ function(req, res) {
+ res.redirect('/');
+ });
+
+app.get('/logout', function(req, res){
+ req.logout();
+ res.redirect('/');
+});
+
+app.listen(3000);
+
+
+// Simple route middleware to ensure user is authenticated.
+// Use this route middleware on any resource that needs to be protected. If
+// the request is authenticated (typically via a persistent login session),
+// the request will proceed. Otherwise, the user will be redirected to the
+// login page.
+function ensureAuthenticated(req, res, next) {
+ if (req.isAuthenticated()) { return next(); }
+ res.redirect('/login')
+}
10 examples/login/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "passport-tumblr-examples-login",
+ "version": "0.0.0",
+ "dependencies": {
+ "express": ">= 0.0.0",
+ "ejs": ">= 0.0.0",
+ "passport": ">= 0.0.0",
+ "passport-tumblr": ">= 0.0.0"
+ }
+}
1 examples/login/views/account.ejs
@@ -0,0 +1 @@
+<p>Username: <%= user.username %></p>
5 examples/login/views/index.ejs
@@ -0,0 +1,5 @@
+<% if (!user) { %>
+ <h2>Welcome! Please log in.</h2>
+<% } else { %>
+ <h2>Hello, <%= user.username %>.</h2>
+<% } %>
21 examples/login/views/layout.ejs
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Passport-Tumblr Example</title>
+ </head>
+ <body>
+ <% if (!user) { %>
+ <p>
+ <a href="/">Home</a> |
+ <a href="/login">Log In</a>
+ </p>
+ <% } else { %>
+ <p>
+ <a href="/">Home</a> |
+ <a href="/account">Account</a> |
+ <a href="/logout">Log Out</a>
+ </p>
+ <% } %>
+ <%- body %>
+ </body>
+</html>
1 examples/login/views/login.ejs
@@ -0,0 +1 @@
+<a href="/auth/tumblr">Login with Tumblr</a>
15 lib/passport-tumblr/index.js
@@ -0,0 +1,15 @@
+/**
+ * Module dependencies.
+ */
+var Strategy = require('./strategy');
+
+
+/**
+ * Framework version.
+ */
+exports.version = '0.1.0';
+
+/**
+ * Expose constructors.
+ */
+exports.Strategy = Strategy;
92 lib/passport-tumblr/strategy.js
@@ -0,0 +1,92 @@
+/**
+ * Module dependencies.
+ */
+var util = require('util')
+ , OAuthStrategy = require('passport-oauth').OAuthStrategy;
+
+
+/**
+ * `Strategy` constructor.
+ *
+ * The Tumblr authentication strategy authenticates requests by delegating to
+ * Tumblr 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 Tumblr
+ * - `consumerSecret` secret used to establish ownership of the consumer key
+ * - `callbackURL` URL to which Tumblr will redirect the user after obtaining authorization
+ *
+ * Examples:
+ *
+ * passport.use(new TumblrStrategy({
+ * consumerKey: '123-456-789',
+ * consumerSecret: 'shhh-its-a-secret'
+ * callbackURL: 'https://www.example.net/auth/tumblr/callback'
+ * },
+ * function(token, tokenSecret, profile, done) {
+ * User.findOrCreate(..., function (err, user) {
+ * done(err, user);
+ * });
+ * }
+ * ));
+ *
+ * @param {Object} options
+ * @param {Function} verify
+ * @api public
+ */
+function Strategy(options, verify) {
+ options = options || {};
+ options.requestTokenURL = options.requestTokenURL || 'http://www.tumblr.com/oauth/request_token';
+ options.accessTokenURL = options.accessTokenURL || 'http://www.tumblr.com/oauth/access_token';
+ options.userAuthorizationURL = options.userAuthorizationURL || 'http://www.tumblr.com/oauth/authorize';
+ options.sessionKey = options.sessionKey || 'oauth:tumblr';
+
+ OAuthStrategy.call(this, options, verify);
+ this.name = 'tumblr';
+}
+
+/**
+ * Inherit from `OAuthStrategy`.
+ */
+util.inherits(Strategy, OAuthStrategy);
+
+/**
+ * Retrieve user profile from Tumblr.
+ *
+ * This function constructs a normalized profile, with the following properties:
+ *
+ * - `username`
+ *
+ * @param {String} token
+ * @param {String} tokenSecret
+ * @param {Object} params
+ * @param {Function} done
+ * @api protected
+ */
+Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
+ this._oauth.get('http://api.tumblr.com/v2/user/info', token, tokenSecret, function (err, body, res) {
+ if (err) { return done(err); }
+
+ try {
+ o = JSON.parse(body);
+
+ var profile = { provider: 'tumblr' };
+ profile.username = o.response.user.name;
+
+ done(null, profile);
+ } catch(e) {
+ done(e);
+ }
+ });
+}
+
+
+/**
+ * Expose `Strategy`.
+ */
+module.exports = Strategy;
16 package.json
@@ -0,0 +1,16 @@
+{
+ "name": "passport-tumblr",
+ "version": "0.1.0",
+ "description": "Tumblr authentication strategy for Passport.",
+ "author": "Jared Hanson <jaredhanson@gmail.com> (http://www.jaredhanson.net/)",
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/jaredhanson/passport-tumblr.git"
+ },
+ "main": "./lib/passport-tumblr",
+ "dependencies": {
+ "passport-oauth": ">= 0.1.0"
+ },
+ "engines": { "node": ">= 0.4.0" },
+ "keywords": ["passport", "tumblr", "auth", "authn", "authentication", "identity"]
+}
15 test/index-test.js
@@ -0,0 +1,15 @@
+var vows = require('vows');
+var assert = require('assert');
+var util = require('util');
+var tumblr = require('passport-tumblr');
+
+
+vows.describe('passport-tumblr').addBatch({
+
+ 'module': {
+ 'should report a version': function (x) {
+ assert.isString(tumblr.version);
+ },
+ },
+
+}).export(module);
127 test/strategy-test.js
@@ -0,0 +1,127 @@
+var vows = require('vows');
+var assert = require('assert');
+var util = require('util');
+var TumblrStrategy = require('passport-tumblr/strategy');
+
+
+vows.describe('TumblrStrategy').addBatch({
+
+ 'strategy': {
+ topic: function() {
+ return new TumblrStrategy({
+ consumerKey: 'ABC123',
+ consumerSecret: 'secret'
+ },
+ function() {});
+ },
+
+ 'should be named tumblr': function (strategy) {
+ assert.equal(strategy.name, 'tumblr');
+ },
+ },
+
+ 'strategy when loading user profile': {
+ topic: function() {
+ var strategy = new TumblrStrategy({
+ consumerKey: 'ABC123',
+ consumerSecret: 'secret'
+ },
+ function() {});
+
+ // mock
+ strategy._oauth.get = function(url, token, tokenSecret, callback) {
+ var body = '{ \
+ "meta": { \
+ "status": 200, \
+ "msg": "OK" \
+ }, \
+ "response": { \
+ "user": { \
+ "following": 263, \
+ "default_post_format": "html", \
+ "name": "derekg", \
+ "likes": 606, \
+ "blogs": [ \
+ { \
+ "name": "derekg", \
+ "title": "Derek Gottfrid", \
+ "url": "http://derekg.org/", \
+ "tweet": "auto", \
+ "primary": true, \
+ "followers": 33004929 \
+ }, \
+ { \
+ "name": "ihatehipstrz", \
+ "title": "I Hate Hipstrz" \
+ } \
+ ] \
+ } \
+ } \
+ }';
+
+ callback(null, body, undefined);
+ }
+
+ return strategy;
+ },
+
+ 'when told to load user profile': {
+ topic: function(strategy) {
+ var self = this;
+ function done(err, profile) {
+ self.callback(err, profile);
+ }
+
+ process.nextTick(function () {
+ strategy.userProfile('token', 'token-secret', {}, done);
+ });
+ },
+
+ 'should not error' : function(err, req) {
+ assert.isNull(err);
+ },
+ 'should load profile' : function(err, profile) {
+ assert.equal(profile.provider, 'tumblr');
+ assert.equal(profile.username, 'derekg');
+ },
+ },
+ },
+
+ 'strategy when loading user profile and encountering an error': {
+ topic: function() {
+ var strategy = new TumblrStrategy({
+ consumerKey: 'ABC123',
+ consumerSecret: 'secret'
+ },
+ function() {});
+
+ // mock
+ strategy._oauth.get = function(url, token, tokenSecret, callback) {
+ callback(new Error('something went wrong'));
+ }
+
+ return strategy;
+ },
+
+ 'when told to load user profile': {
+ topic: function(strategy) {
+ var self = this;
+ function done(err, profile) {
+ self.callback(err, profile);
+ }
+
+ process.nextTick(function () {
+ strategy.userProfile('token', 'token-secret', {}, done);
+ });
+ },
+
+ 'should error' : function(err, req) {
+ assert.isNotNull(err);
+ },
+ 'should not load profile' : function(err, profile) {
+ assert.isUndefined(profile);
+ },
+ },
+ },
+
+}).export(module);

0 comments on commit 2d36ab6

Please sign in to comment.