Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added the api example

  • Loading branch information...
commit e7e3569b849af461673cc2e85cea7d57c63ccc77 1 parent 057bdef
@cholalabs authored
View
21 examples/express3/app.js
@@ -109,15 +109,15 @@ app.configure(function() {
app.get('/', function(req, res){
- res.render('index', { user: req.user });
+ res.json({ message: "Authenticated" })
});
-app.get('/account', ensureAuthenticated, function(req, res){
- res.render('account', { user: req.user });
+app.get('/api/account', ensureAuthenticated, function(req, res){
+ res.json({ message: "Authenticated" })
});
-app.get('/login', function(req, res){
- res.render('login', { user: req.user, message: req.flash('error') });
+app.get('/api/unauthorized', function(req, res){
+ res.json({ message: "Authentication Error" })
});
// POST /login
@@ -126,11 +126,11 @@ app.get('/login', function(req, res){
// 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 }),
+// curl -v -d "apikey=asdasjsdgfjkjhg" http://127.0.0.1:3000/api/authenticate
+app.post('/api/authenticate',
+ passport.authenticate('localapikey', { failureRedirect: '/api/unauthorized', failureFlash: true }),
function(req, res) {
- res.redirect('/');
+ res.json({ message: "Authenticated" })
});
// POST /login
@@ -159,6 +159,7 @@ app.get('/logout', function(req, res){
app.listen(3000);
+console.log("Server running on port 3000");
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
@@ -167,5 +168,5 @@ app.listen(3000);
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
- res.redirect('/login')
+ res.redirect('/api/unauthorized')
}
View
155 examples/login/app.js
@@ -1,155 +0,0 @@
-var express = require('express')
- , passport = require('passport')
- , util = require('util')
- , LocalStrategy = require('passport-local').Strategy;
-
-
-var users = [
- { id: 1, username: 'bob', password: 'secret', email: 'bob@example.com' }
- , { id: 2, username: 'joe', password: 'birthday', email: 'joe@example.com' }
-];
-
-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);
-}
-
-
-// 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(username, password, 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`.
- findByUsername(username, function(err, user) {
- if (err) { return done(err); }
- if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
- if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
- return done(null, user);
- })
- });
- }
-));
-
-
-
-
-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, 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('local', { 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')
-}
View
10 examples/login/package.json
@@ -1,10 +0,0 @@
-{
- "name": "passport-local-examples-login",
- "version": "0.0.0",
- "dependencies": {
- "express": ">= 0.0.0",
- "ejs": ">= 0.0.0",
- "passport": ">= 0.0.0",
- "passport-local": ">= 0.0.0"
- }
-}
View
3  examples/login/views/account.ejs
@@ -1,3 +0,0 @@
-<p>Username: <%= user.username %></p>
-<p>Email: <%= user.email %></p>
-
View
5 examples/login/views/index.ejs
@@ -1,5 +0,0 @@
-<% if (!user) { %>
- <h2>Welcome! Please log in.</h2>
-<% } else { %>
- <h2>Hello, <%= user.username %>.</h2>
-<% } %>
View
21 examples/login/views/layout.ejs
@@ -1,21 +0,0 @@
-<!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>
View
17 examples/login/views/login.ejs
@@ -1,17 +0,0 @@
-<% 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>
Please sign in to comment.
Something went wrong with that request. Please try again.