├── .gitignore ├── lib ├── index.js ├── errors │ └── badrequesterror.js └── strategy.js ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | npm-debug.log 3 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | var Strategy = require('./strategy') 5 | , BadRequestError = require('./errors/badrequesterror'); 6 | 7 | 8 | /** 9 | * Expose constructors. 10 | */ 11 | exports.Strategy = Strategy; 12 | 13 | exports.BadRequestError = BadRequestError; 14 | -------------------------------------------------------------------------------- /lib/errors/badrequesterror.js: -------------------------------------------------------------------------------- 1 | /** 2 | * `BadRequestError` error. 3 | * 4 | * @api public 5 | */ 6 | function BadRequestError(message) { 7 | Error.call(this); 8 | Error.captureStackTrace(this, arguments.callee); 9 | this.name = 'BadRequestError'; 10 | this.message = message || null; 11 | }; 12 | 13 | /** 14 | * Inherit from `Error`. 15 | */ 16 | BadRequestError.prototype.__proto__ = Error.prototype; 17 | 18 | 19 | /** 20 | * Expose `BadRequestError`. 21 | */ 22 | module.exports = BadRequestError; 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "passport-token", 3 | "version": "0.2.0", 4 | "description": "Username and token authentication strategy for Passport - modified from passport-local.", 5 | "author": { 6 | "name": "Lee Powell" 7 | }, 8 | "main": "./lib/index.js", 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/leepowellcouk/passport-token" 12 | }, 13 | "dependencies": { 14 | "passport-strategy": "^1.0.0" 15 | }, 16 | "engines": { 17 | "node": ">= 0.4.0" 18 | }, 19 | "licenses": [ 20 | { 21 | "type": "MIT", 22 | "url": "http://www.opensource.org/licenses/MIT" 23 | } 24 | ], 25 | "keywords": [ 26 | "passport", 27 | "token", 28 | "auth", 29 | "authn", 30 | "authentication" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /lib/strategy.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | var PassportStrategy = require('passport-strategy') 5 | , util = require('util') 6 | , BadRequestError = require('./errors/badrequesterror'); 7 | 8 | 9 | /** 10 | * `Strategy` constructor. 11 | * 12 | * The token authentication strategy authenticates requests based on the 13 | * credentials submitted through standard request headers or body. 14 | * 15 | * Applications must supply a `verify` callback which accepts `username` and 16 | * `token` credentials, and then calls the `done` callback supplying a 17 | * `user`, which should be set to `false` if the credentials are not valid. 18 | * If an exception occured, `err` should be set. 19 | * 20 | * Optionally, `options` can be used to change the fields in which the 21 | * credentials are found. 22 | * 23 | * Options: 24 | * 25 | * - `usernameHeader` header name where the username is found, defaults to 'x-username' 26 | * - `tokenHeader` header name where the token is found, defaults to 'x-token' 27 | * - `usernameField` field name where the username is found, defaults to 'username' 28 | * - `tokenField` field name where the password is found, defaults to 'password' 29 | * - `usernameQuery` query string name where the username is found, defaults to 'username' 30 | * - `tokenQuery` query string name where the password is found, defaults to 'password' 31 | * - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`) 32 | * 33 | * Examples: 34 | * 35 | * passport.use(new TokenStrategy( 36 | * function(username, token, done) { 37 | * User.findOne({ username: username, token: token }, function (err, user) { 38 | * done(err, user); 39 | * }); 40 | * } 41 | * )); 42 | * 43 | * @param {Object} options 44 | * @param {Function} verify 45 | * @api public 46 | */ 47 | function Strategy(options, verify) { 48 | if (typeof options == 'function') { 49 | verify = options; 50 | options = {}; 51 | } 52 | 53 | if (!verify) throw new Error('token authentication strategy requires a verify function'); 54 | 55 | this._usernameHeader = options.usernameHeader ? options.usernameHeader.toLowerCase() : 'x-username'; 56 | this._tokenHeader = options.tokenHeader ? options.tokenHeader.toLowerCase() : 'x-token'; 57 | 58 | this._usernameField = options.usernameField ? options.usernameField.toLowerCase() : 'username'; 59 | this._tokenField = options.tokenField ? options.tokenField.toLowerCase() : 'token'; 60 | 61 | this._usernameQuery = options.usernameQuery ? options.usernameQuery.toLowerCase() : this._usernameField; 62 | this._tokenQuery = options.tokenQuery ? options.tokenQuery.toLowerCase() : this._tokenField; 63 | 64 | PassportStrategy.call(this); 65 | this.name = 'token'; 66 | this._verify = verify; 67 | this._passReqToCallback = options.passReqToCallback; 68 | } 69 | 70 | /** 71 | * Inherit from `passport-strategy`. 72 | */ 73 | util.inherits(Strategy, PassportStrategy); 74 | 75 | /** 76 | * Authenticate request based on the contents of a form submission. 77 | * 78 | * @param {Object} req 79 | * @api protected 80 | */ 81 | Strategy.prototype.authenticate = function(req, options) { 82 | options = options || {}; 83 | var self = this; 84 | var username = req.headers[this._usernameHeader] || lookup(req.body, this._usernameField) || lookup(req.query, this._usernameQuery); 85 | var token = req.headers[this._tokenHeader] || lookup(req.body, this._tokenField) || lookup(req.query, this._tokenQuery); 86 | 87 | if (!username || !token) { 88 | return this.fail(new BadRequestError(options.badRequestMessage || 'Missing credentials')); 89 | } 90 | 91 | function verified(err, user, info) { 92 | if (err) { return self.error(err); } 93 | if (!user) { return self.fail(info); } 94 | self.success(user, info); 95 | } 96 | 97 | if (self._passReqToCallback) { 98 | this._verify(req, username, token, verified); 99 | } else { 100 | this._verify(username, token, verified); 101 | } 102 | 103 | function lookup(obj, field) { 104 | if (!obj) { return null; } 105 | var chain = field.split(']').join('').split('['); 106 | for (var i = 0, len = chain.length; i < len; i++) { 107 | var prop = obj[chain[i]]; 108 | if (typeof(prop) === 'undefined') { return null; } 109 | if (typeof(prop) !== 'object') { return prop; } 110 | obj = prop; 111 | } 112 | return null; 113 | } 114 | } 115 | 116 | 117 | /** 118 | * Expose `Strategy`. 119 | */ 120 | module.exports = Strategy; 121 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | passport-token 2 | ============== 3 | 4 | Username and token authentication strategy for Passport - modified from [passport-local](https://github.com/jaredhanson/passport-local). 5 | 6 | ## Installation 7 | $ npm install passport-token 8 | 9 | ## Usage 10 | 11 | The token authentication strategy authenticates users using a username and token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user. 12 | 13 | var TokenStrategy = require('passport-token').Strategy; 14 | 15 | passport.use(new TokenStrategy( 16 | function (username, token, done) { 17 | User.findOne({username: username}, function (err, user) { 18 | if (err) { 19 | return done(err); 20 | } 21 | 22 | if (!user) { 23 | return done(null, false); 24 | } 25 | 26 | if (!user.verifyToken(token)) { 27 | return done(null, false); 28 | } 29 | 30 | return done(null, user); 31 | }); 32 | } 33 | )); 34 | 35 | By default, passport-token checks for `username` and `token` credentials in either the header or request body in these locations: 36 | 37 | ### Headers 38 | 39 | x-username 40 | x-token 41 | 42 | ### Body fields 43 | 44 | username 45 | token 46 | 47 | ### Configure 48 | 49 | These credential locations can be configured when defining the strategy as follows: 50 | 51 | var TokenStrategy = require('passport-token').Strategy; 52 | var strategyOptions = { 53 | usernameHeader: 'x-custom-username', 54 | tokenHeader: 'x-custom-token', 55 | usernameField: 'custom-username', 56 | tokenField: 'custom-token' 57 | }; 58 | 59 | passport.use(new TokenStrategy(strategyOptions, 60 | function (username, token, done) { 61 | User.findOne({username: username}, function (err, user) { 62 | if (err) { 63 | return done(err); 64 | } 65 | 66 | if (!user) { 67 | return done(null, false); 68 | } 69 | 70 | if (!user.verifyToken(token)) { 71 | return done(null, false); 72 | } 73 | 74 | return done(null, user); 75 | }); 76 | } 77 | 78 | 79 | ## Authenticate 80 | 81 | Use `passport.authenticate()`, specifying the `token` strategy to authenticate requests. 82 | 83 | For example, as route middleware in an [Express](http://expressjs.com/) application: 84 | 85 | app.put('/animals/dogs', passport.authenticate('token'), function (req, res) { 86 | // User authenticated and can be found in req.user 87 | }); 88 | 89 | If authentication fails in the above example then a 401 response will be given. However there may be times you wish a bit more control and delegate the failure to your application: 90 | 91 | app.put('/animals/dogs', authenticate, function (req, res) { 92 | // User authenticated and can be found in req.user 93 | }); 94 | 95 | function authenticate(req, res, next) { 96 | passport.authenticate('token', function (err, user, info) { 97 | if (err) { 98 | return next(err); 99 | } 100 | 101 | if (!user) { 102 | return res.status(401).json({message: "Incorrect token credentials"}); 103 | } 104 | 105 | req.user = user; 106 | next(); 107 | }); 108 | } 109 | 110 | ## Credits 111 | [Jared Hanson](http://github.com/jaredhanson) 112 | 113 | ## License 114 | (The MIT License) 115 | 116 | Copyright (c) 2011 Jared Hanson 117 | 118 | 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: 119 | 120 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 121 | 122 | 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. 123 | --------------------------------------------------------------------------------