GithubHelp home page GithubHelp logo

flatiron-passport's Introduction

Passport.js integration for FlatIron web framework.

This package allows Flatiron.js applications to easily use the Passport.js authentication framework.

There are only two things that are different between using this API and using the regular Passport API.

1.) Instead of calling...

var express = require('express');
var passport = require('passport');
var app = express();
// ... BOILERPLATE SETUP CODE GOES HERE ...
app.use(passport.initialize());
app.use(passport.session());

You simply need to call...

var flatiron =      require('flatiron');
var fipassport =    require('flatiron-passport');
var app =           flatiron.app;
// ... BOILERPLATE SETUP CODE GOES HERE ...
app.use(fipassport);

2.) Now anywhere you would use the variable passport, you replace that with fipassport in your app, like so...

passport.use(new LocalStrategy(function(username, password, done) {
  ...
  ...
});

passport.serializeUser(function(user, done) {
  ...
  ...
});

passport.deserializeUser(function(id, done) {
  ...
  ...
});

passport.authenticate(.....)

You simply call this instead...

fipassport.use(new LocalStrategy(function(username, password, done) {
  ...
  ...
});

fipassport.serializeUser(function(user, done) {
  ...
  ...
});

fipassport.deserializeUser(function(id, done) {
  ...
  ...
});

fipassport.authenticate(.....)

Please refer to the included example to get a better idea....

Install

npm install flatiron-passport

Example: From the example folder...

var fs =            require('fs')
var flatiron =      require('flatiron');
var LocalStrategy = require('passport-local').Strategy
var fipassport =    require('flatiron-passport');
var app =           flatiron.app;

// You would not usually have these lines...
// This is just to store the username in memory.
var global_user = '';
var global_pass = '';

// Use the passport strategy.
fipassport.use(new LocalStrategy(function(username, password, done) {

  // You would not normally have these lines...
  // This is just to store it in memory for use later.
  global_user = username;
  global_pass = password;

  // Use this as you normally would in Passport.js.
  // But for now just
  // hard-code the user object.
  done(null, {
    id: 1234,
    username: username,
    password: password
  });
}));

// Serialize based on the user ID.
fipassport.serializeUser(function(user, done) {

  // @todo: Save your user to the database using the ID as a key.
  done(null, user.id);
});

// Load the user and return it to passport.
fipassport.deserializeUser(function(id, done) {

  // @todo:  Load your user here based off of the ID, and call done with
  // that user object.
  done(null, {
    id:id,
    username:global_user,
    password:global_pass
  });
});

// Use http and flatiron-passport.
app.use(flatiron.plugins.http);
app.use(fipassport);

// Get the front page.
app.router.get('/', function() {
  if (this.req.isAuthenticated()) {
    this.res.end('Hello ' + this.req.user.username);
  }
  else {
    fs.readFile('index.html', (function(self) {
      return function(err, data) {
        if(err) {
          self.res.writeHead(404);
          self.res.end();
          return;
        }
        self.res.writeHead(200, {'Content-Type': 'text/html'});
        self.res.end(data);
      };
    })(this));
  }
});

/**
 * Here the API to fipassport.authenticate is the exact same as it would
 * be fore passport.authenticate.  It is just a simple wrapper around that
 * function.
 */
app.router.post('/login', fipassport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login'
}));

// Start our server at port 3000.
app.start(3000, function(){
  console.log('HTTP Server started on port 3000');
});

flatiron-passport's People

Contributors

joeybaker avatar pvorb avatar travist avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

flatiron-passport's Issues

req.user is never set (and therefore req.isAuthenticated never returns true)

While the following route is correctly handled:

// thanks to http://stackoverflow.com/questions/9885711/custom-returnurl-on-node-js-passports-google-strategy
app.router.get('/auth/google/callback', function (next) { 
  req = this.req;
  res = this.res;

  fipassport.authenticate('google', function(err, user, info){
    // This is the default destination upon successful login.
    var redirectUrl = '/';

    if (err) { return next(err); }
    if (!user) { return this.res.redirect('/'); }

    // If we have previously stored a redirectUrl, use that, 
    // otherwise, use the default.
    if (this.req.session.redirectUrl) {
      redirectUrl = this.req.session.redirectUrl;
      this.req.session.redirectUrl = null;
    }
    this.req.logIn(user, function(err) {
      if (err) { throw err; }
      console.log(this.req.isAuthenticated()); // returns true
      this.res.redirect(redirectUrl);
    });
  })(req, res, next)
});

...and the isAuthenticated returns true, the following does not:

ensureAuthenticated = function (next) {
  if (this.req.isAuthenticated()) { return next(); } // returns false :(

  this.req.session.redirectUrl = this.req.url;
  this.res.redirect('/auth/google');
}

app.router.get('/', [
    ensureAuthenticated,
    routes.index
  ]);

The result is a redirect loop, where ensureAuthenticated swears the user isn't logged in, but /auth/google succeeds with no user intervention and redirects to /auth/google/callback, and then back to / again.

what about csrf suppport

I thought about adding to the attach function something like

app.http.before.push(connect.csrf());

but than i also need to take care of the session, let me know if someone already was working on it?

Callback Options?

Is it possible, instead of defining succes and failure redirects, to response something directly? I want to have an ajax login and don't need to redirect.

isAuthenticated() returns false after login.

I used the example you provided in the README.md. But I can't get any authentication. Here is the log of req before and after login:

BEFORE:

secret: 'keyboard cat',
cookies: { gs_u: '1052469230:3663:28119:1358525911905' },
signedCookies: { 'connect.sid': '/N/ZxhdoWBbqFfCej00/tCgG' },
sessionStore:
{ sessions: {},
generate: [Function],
_events: { disconnect: [Function], connect: [Function] } },
sessionID: 'a2Fpg3ggaa+Gb1vz5Jo9sE43',
ended: true,
session:
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: {} },
_passport:
{ instance:
{ _key: 'passport',
_strategies: [Object],
_serializers: [Object],
_deserializers: [Object],
_infoTransformers: [],
_userProperty: 'user',
version: '0.1.15',
Passport: [Function: Passport],
Strategy: [Function: Strategy],
strategies: [Object] },
session: {} },
isAuthenticated: [Function],
isUnauthenticated: [Function],
logIn: [Function],
login: [Function],
logOut: [Function],
logout: [Function] }

AFTER

secret: 'keyboard cat',
cookies: { gs_u: '1052469230:3663:28119:1358525911905' },
signedCookies: { 'connect.sid': 'a2Fpg3ggaa+Gb1vz5Jo9sE43' },
sessionStore:
{ sessions: { 'a2Fpg3ggaa+Gb1vz5Jo9sE43': '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{}}' },
generate: [Function],
_events: { disconnect: [Function], connect: [Function] } },
sessionID: 'a2Fpg3ggaa+Gb1vz5Jo9sE43',
ended: true,
session:
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: {} },
_passport:
{ instance:
{ _key: 'passport',
_strategies: [Object],
_serializers: [Object],
_deserializers: [Object],
_infoTransformers: [],
_userProperty: 'user',
version: '0.1.15',
Passport: [Function: Passport],
Strategy: [Function: Strategy],
strategies: [Object] },
session: {} },
isAuthenticated: [Function],
isUnauthenticated: [Function],
logIn: [Function],
login: [Function],
logOut: [Function],
logout: [Function] }

Only the sessionStore object gets changed. I don't get an user object or any value out of session object. And as I said, isAuthenticated returns false after login.

Does not work if buffer: false is used on flatiron.plugins.http

Hi, a great module!
I'm currently using it and spent 2h finding out, why it would not work in my project.
Result was that if union is configured to not buffer using the option buffer: false,
then the module is not working.
Maybe this is worth mentioning it in the docs.
Greets

Understanding goal of this project: doesn't Flatiron just support Connect middleware (through Union) including OAuth-clients?

I'm very new to Flatiron and consider using it. One of the features that appeals to me is that Flatiron/union should be 100% backwards compatible with Connect.

This would mean that Connect middleware should just run on Flatiron/Union right? Among which https://github.com/ciaranj/connect-auth and others.

So why the need for this project? Or am I completely missing something?

Doesn't work if flatiron.plugins.http buffer: false

I need to have a file upload and thus buffer: false and stream: true. It doesn't seem to work otherwise. But with those settings flatiron-passport doesn't work. Without them just fine. I guess I will start a second server for the file upload.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.