Permalink
Browse files

Initial Commit

  • Loading branch information...
1 parent 80388b7 commit d16487737080b1ca91198bea4d5ad71dcdc37b94 @cholalabs committed Dec 8, 2012
View
@@ -0,0 +1,2 @@
+.DS_Store
+node_modules
View
@@ -0,0 +1,8 @@
+*.md
+.DS_Store
+.git*
+Makefile
+docs/
+examples/
+support/
+test/
View
@@ -0,0 +1,4 @@
+language: "node_js"
+node_js:
+ - 0.4
+ - 0.6
View
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.
View
@@ -0,0 +1,19 @@
+NODE = node
+TEST = ./node_modules/.bin/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-localapikey/*.js
+ dox \
+ --title Passport-Localapikey \
+ --desc "Local apikey authentication strategy for Passport" \
+ $(shell find lib/passport-localapikey/* -type f) > $@
+
+docclean:
+ rm -f docs/*.{1,html}
+
+.PHONY: test docs docclean
View
@@ -1,2 +1,84 @@
-passport-localapikey
-====================
+# Passport-LocalAPIKey
+
+[Passport](http://passportjs.org/) strategy for authenticating with a apikey.
+
+This module lets you authenticate using a apikey in your Node.js
+applications. By plugging into Passport, local apikey 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-localapikey
+
+## Usage
+
+#### Configure Strategy
+
+The local api key authentication strategy authenticates users using a apikey.
+The strategy requires a `verify` callback, which accepts these
+credentials and calls `done` providing a user.
+
+ passport.use(new LocalAPIKeyStrategy(
+ function(username, password, done) {
+ User.findOne({ username: username }, function (err, user) {
+ if (err) { return done(err); }
+ if (!user) { return done(null, false); }
+ if (!user.verifyPassword(password)) { return done(null, false); }
+ return done(null, user);
+ });
+ }
+ ));
+
+#### Authenticate Requests
+
+Use `passport.authenticate()`, specifying the `'local apikey'` strategy, to
+authenticate requests.
+
+For example, as route middleware in an [Express](http://expressjs.com/)
+application:
+
+ app.post('/login',
+ passport.authenticate('localapikey', { failureRedirect: '/login' }),
+ function(req, res) {
+ res.redirect('/');
+ });
+
+## Examples
+
+
+
+## Tests
+
+ $ npm install --dev
+ $ make test
+
+[![Build Status](https://secure.travis-ci.org/cholalabs/passport-localapikey.png)](http://travis-ci.org/cholalabs/passport-localapikey)
+
+## Credits
+
+ - [Sudhakar Mani](http://twitter.com/sudhakarmani)
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2012 Sudhakar Mani
+
+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.
@@ -0,0 +1 @@
+#test
View
@@ -0,0 +1,171 @@
+var express = require('express')
+ , passport = require('passport')
+ , flash = require('connect-flash')
+ , util = require('util')
+ , LocalStrategy = require('passport-localapikey').Strategy;
+
+
+var users = [
+ { id: 1, username: 'bob', password: 'secret', email: 'bob@example.com',apikey: 'asdasjsdgfjkjhg' }
+ , { id: 2, username: 'joe', password: 'birthday', email: 'joe@example.com',apikey: 'gfsdgsfgsfg' }
+];
+
+function findById(id, fn) {
+ var idx = id - 1;
+ if (users[idx]) {
+ fn(null, users[idx]);
+ } else {
+ fn(new Error('User ' + id + ' does not exist'));
+ }
+}
+
+function findByUsername(username, fn) {
+ for (var i = 0, len = users.length; i < len; i++) {
+ var user = users[i];
+ if (user.username === username) {
+ return fn(null, user);
+ }
+ }
+ return fn(null, null);
+}
+
+
+function findByApiKey(apikey, fn) {
+ for (var i = 0, len = users.length; i < len; i++) {
+ var user = users[i];
+ if (user.apikey === apikey) {
+ return fn(null, user);
+ }
+ }
+ return fn(null, null);
+}
+
+
+
+
+// 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.
+passport.serializeUser(function(user, done) {
+ done(null, user.id);
+});
+
+passport.deserializeUser(function(id, done) {
+ findById(id, function (err, user) {
+ done(err, user);
+ });
+});
+
+
+// Use the LocalStrategy within Passport.
+// Strategies in passport require a `verify` function, which accept
+// credentials (in this case, a username and password), and invoke a callback
+// with a user object. In the real world, this would query a database;
+// however, in this example we are using a baked-in set of users.
+passport.use(new LocalStrategy(
+ function(apikey, done) {
+ // asynchronous verification, for effect...
+ process.nextTick(function () {
+
+ // Find the user by username. If there is no user with the given
+ // username, or the password is not correct, set the user to `false` to
+ // indicate failure and set a flash message. Otherwise, return the
+ // authenticated `user`.
+ findByApiKey(apikey, function(err, user) {
+ if (err) { return done(err); }
+ if (!user) { return done(null, false, { message: 'Unknown apikey : ' + apikey }); }
+ // if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
+ return done(null, user);
+ })
+ });
+ }
+));
+
+
+
+
+var app = express();
+
+// configure Express
+app.configure(function() {
+ app.set('views', __dirname + '/views');
+ app.set('view engine', 'ejs');
+ app.engine('ejs', require('ejs-locals'));
+ app.use(express.logger());
+ app.use(express.cookieParser());
+ app.use(express.bodyParser());
+ app.use(express.methodOverride());
+ app.use(express.session({ secret: 'keyboard cat' }));
+ app.use(flash());
+ // 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, message: req.flash('error') });
+});
+
+// POST /login
+// 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.
+//
+// curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
+app.post('/login',
+ passport.authenticate('localapikey', { failureRedirect: '/login', failureFlash: true }),
+ function(req, res) {
+ res.redirect('/');
+ });
+
+// POST /login
+// This is an alternative implementation that uses a custom callback to
+// acheive the same functionality.
+/*
+app.post('/login', function(req, res, next) {
+ passport.authenticate('local', function(err, user, info) {
+ if (err) { return next(err) }
+ if (!user) {
+ req.flash('error', info.message);
+ return res.redirect('/login')
+ }
+ req.logIn(user, function(err) {
+ if (err) { return next(err); }
+ return res.redirect('/users/' + user.username);
+ });
+ })(req, res, next);
+});
+*/
+
+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')
+}
@@ -0,0 +1,13 @@
+{
+ "name": "passport-local-examples-login",
+ "version": "0.0.0",
+ "dependencies": {
+ "express": "3.x.x",
+ "connect-flash": "0.1.x",
+ "ejs": ">= 0.0.0",
+ "ejs-locals": ">= 0.0.0",
+ "passport": ">= 0.0.0",
+ "passport-localapikey": ">= 0.0.0",
+ "passport-local": ">= 0.0.0"
+ }
+}
@@ -0,0 +1,4 @@
+<% layout('layout') -%>
+<p>Username: <%= user.username %></p>
+<p>Email: <%= user.email %></p>
+
@@ -0,0 +1,6 @@
+<% layout('layout') -%>
+<% if (!user) { %>
+ <h2>Welcome! Please log in.</h2>
+<% } else { %>
+ <h2>Hello, <%= user.username %>.</h2>
+<% } %>
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Passport-Local 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>
@@ -0,0 +1,18 @@
+<% layout('layout') -%>
+<% if (message) { %>
+<p><%= message %></p>
+<% } %>
+<form action="/login" method="post">
+ <div>
+ <label>Username:</label>
+ <input type="text" name="username"/><br/>
+ </div>
+ <div>
+ <label>Password:</label>
+ <input type="password" name="password"/>
+ </div>
+ <div>
+ <input type="submit" value="Submit"/>
+ </div>
+</form>
+<p><small>Hint - bob:secret</small></p>
Oops, something went wrong.

0 comments on commit d164877

Please sign in to comment.