Git Product home page Git Product logo

koa-passport-example's Introduction

koa-passport-example

Example for koa-passport

koa-passport version koa version branch
1.x 1.x [email protected]
2.x 2.x [email protected]
3.x 2.x master

Other Examples

Note

  • If your node version greater than or equal 8.4.0 then replace "start": "node --harmony-async-await server.js" with "start": "node server.js"

Integrating with databases

koa-router

koa-passport-example's People

Contributors

foadyousefi avatar ilyasemenov avatar mapmeld avatar mbehtemam avatar mjhea0 avatar peny avatar rashed-jitu avatar rkusa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

koa-passport-example's Issues

Doesn't run "TypeError" exception

Hi,
Trying to run the example and an exception is raised on line 15:

app.use(bodyParser())

Error trace:

TypeError: Support for generators has been removed.

I run Koa2-alpha3.

ctx.req.user being called by a dependency

With the latest update to koa-passport, I get a koa-passport deprecated setting ctx.req.user is deprecated in favour of ctx.state.user warning when I log in

This codebase doesn't use ctx.req or ctx.state, so my best guess is that it's coming from koa-route or another dependency.

checking if user is logged in in strategy callback

As part of the strategy options, there is normally a passReqToCallback option. When this is flagged as true, you will get the request object. In express, the request object contains everything related to request and also includes things like the logged in user by req.user

In Koa though, this is not the case. What are the options to finding if the user is logged or not?

[question] function based authentication route

// Require authentication for now
app.use(function(ctx, next) {
  if (ctx.isAuthenticated()) {
    return next()
  } else {
    ctx.redirect('/')
  }
})

is there a way to require authentication per route ? like this:

app.use(isAuthenticated(), async ctx => { ctx.body = 'this is restricted'; })

Getting redirect loop while dooing facebook authentication

Hi ,
I was trying to test the facebook integration but I get redirect loop when I try to login using facebook(after I successfully login)
My routes are :
//=============================================
// route for facebook authentication and login
//=============================================

    default_router.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

    //=============================profile=================================
    // handle the callback after facebook has authenticated the user
    //==============================================================

        default_router.get('/auth/facebook/callback', parse,
            passport.authenticate('facebook', {
                successRedirect : '/app',
                failureRedirect : '/'
            }));

and my authenticate function is :

     passport.use(new FacebookStrategy({
clientID: authconfig.facebookAuth.clientID,
clientSecret: authconfig.facebookAuth.clientSecret,
callbackURL: authconfig.facebookAuth.callbackURL

},

// facebook will send back the token and profile
function(token, refreshToken, profile, done) {

    // asynchronous
    process.nextTick(function() {

        // find the user in the database based on their facebook id
        User.findOne({ 'facebook.id' : profile.id }, function(err, user) {

            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
                return done(err);

            // if the user is found, then log them in
            if (user) {
                return done(null, user); // user found, return that user
            } else {
                // if there is no user found with that facebook id, create them
                var newUser            = new User();

                // set all of the facebook information in our user model
                newUser.facebook.id    = profile.id; // set the users facebook id                   
                newUser.facebook.token = token; // we will save the token that facebook provides to the user                    
                newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first

                // save our user to the database
                newUser.save(function(err) {
                    if (err)
                        throw err;

                    // if successful, return the new user
                    return done(null, newUser);
                });
            }

        });
    });

}));

yield* passport.authenticate throws TypeError

Hi,

Throwing together a quick sample of this application -

'use strict';
const koa = require('koa')
const passport = require('koa-passport')
const LocalStrategy = require('passport-local').Strategy
const Router = require('koa-router')

passport.serializeUser(function(user, done) {
  done(null, user.id)
})

passport.deserializeUser(function(id, done) {
  done(null, { id: id })
})

passport.use('local', new LocalStrategy(function(username, password, done) {
  done(null, {})
}))

const app = koa()
app.use(passport.initialize())

const router = new Router()
router.get('/protected', function* protectedPage() {
  yield* passport.authenticate('local', function* passportCallback(error, user) { 
    this.status = 200
  })
})
app.use(router.routes())

app.listen(3000)

The call to yield* passport.authenticate throws an exception -

  TypeError: undefined is not a function
      at Object.protectedPage (c:\projects\dash\index.js:25:19)
      at GeneratorFunctionPrototype.next (native)
      at Object.dispatch (c:\projects\dash\node_modules\koa-router\lib\router.js:297:14)
      at GeneratorFunctionPrototype.next (native)
      at onFulfilled (c:\projects\dash\node_modules\koa\node_modules\co\index.js:64:19)
      at c:\projects\dash\node_modules\koa\node_modules\co\index.js:53:5
      at Object.co (c:\projects\dash\node_modules\koa\node_modules\co\index.js:49:10)
      at Object.toPromise (c:\projects\dash\node_modules\koa\node_modules\co\index.js:117:63)
      at next (c:\projects\dash\node_modules\koa\node_modules\co\index.js:98:29)
      at onFulfilled (c:\projects\dash\node_modules\koa\node_modules\co\index.js:68:7)

altering this yield* call to a simple yield allows the application to work as intended.

This code is running on iojs v1.8.1, with latest versions of koa-passport, koa-router, koa and passport-local as of writing.

I'm only mentioning this because the sample application in this repo uses yield* as opposed to yield.

Incompatible with koa-mount - TypeError: Cannot read property 'store' of undefined at session

I'm working with koa-mount, looks like the problem is koa-session but I'm completely lost with this implementation with koa-passport. My code is like :
server.js:

'use strict';

const koa = require("koa");
const application = require('./application.js')
const app = new koa();
const appPort = 3000;

// Mount application
const mount = require('koa-mount');
app.use(mount('/application', application));

// serve index.html
const serve = require('koa-static-server');
app.use(serve({rootDir: __dirname+'/test', rootPath: '/'}));

// init server
app.listen(appPort, function() {
	console.log(`Ready at port: ${appPort}`)
});

application.js:

// use strict code
"use strict";

const fs = require('fs');

// appFactory
const appFactory = () => {
	const Koa = require('koa')
	const app = new Koa()
	const serve = require('koa-static-server')
	const router = require('koa-router')();
	const session = require('koa-session')
	const bodyParser = require('koa-bodyparser')
	const passport = require('koa-passport')

	// trust proxy
	app.proxy = true

	// session
	app.keys = ['your-session-secret']
	app.use(session({}, app)) // <-- _problem occurs here_

	// body parser
	app.use(bodyParser())

	// passport
	require('./auth')
	app.use(passport.initialize())
	app.use(passport.session())

	// post login
	router.post('/login', passport.authenticate('local', {
		successRedirect: '/',
		failureRedirect: '/eos/'
	}));

	// post logout
	router.get('/logout', function(ctx) {
		if (ctx.isAuthenticated()) {
			ctx.logout()
		}
		ctx.redirect('/')
	});

	// admin route
	router.get('/', async(ctx) => {
		ctx.type = 'html'
		if (ctx.isAuthenticated()) {
			ctx.body = fs.createReadStream('views/log-out.html')
		} else {
			ctx.body = fs.createReadStream('views/log-in.html')
		}
	});

	// post update
	router.post('/', async(ctx, next) => {
		if (ctx.isAuthenticated()) {
			// Attach db to context
			ctx.langDB = db
			for (var keypath in ctx.request.body) {
				const content = ctx.request.body[keypath]
				// Frontend EOS has to convert . to / to avoid being broken up by bodyparser
				keypath = keypath.replace(/\//g, '.')
				ctx.langDB.set(keypath, content).write()
			}
			ctx.status = 200
		} else {
			ctx.status = 401
		}
	});

	// sample route
	router.get('/sample.js', async(ctx) => {
		ctx.type = 'application/json'
		if (ctx.isAuthenticated()) {
			ctx.body = fs.createReadStream('views/sample.js')
		} else {
			ctx.body = fs.createReadStream('views/sample-blank.js')
		}
	});

	// use routes
	app.use(router.routes()).use(router.allowedMethods());

	// serve public
	app.use(serve({
		rootDir: __dirname + '/public',
		rootPath: '/'
	}));
	return app
}

// export module
module.exports = () => {
	return appFactory()
}

the error I'm getting is

TypeError: Cannot read property 'store' of undefined
      at session (/Users/sysuser/Desktop/eos/node_modules/koa-session/index.js:41:13)
      at dispatch (/Users/sysuser/Desktop/eos/node_modules/koa-mount/node_modules/koa-compose/index.js:44:32)
      at /Users/sysuser/Desktop/eos/node_modules/koa-mount/node_modules/koa-compose/index.js:36:12
      at /Users/sysuser/Desktop/eos/node_modules/koa-mount/index.js:58:11
      at dispatch (/Users/sysuser/Desktop/eos/node_modules/koa-compose/index.js:42:32)
      at /Users/sysuser/Desktop/eos/node_modules/koa-compose/index.js:34:12
      at Server.handleRequest (/Users/sysuser/Desktop/eos/node_modules/koa/lib/application.js:136:14)
      at emitTwo (events.js:106:13)
      at Server.emit (events.js:194:7)
      at parserOnIncoming (_http_server.js:563:12)

I've tried using your package.json as a base - still the same. it doesn't matter what router module i use - it breaks at app.use(session({}, app)) - Any suggestions?

How to create signup method

I want to create something like

    passport.use('local-signup', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'email',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, email, password, done) {

            // asynchronous
            // User.findOne wont fire unless data is sent back
            process.nextTick(function() {

            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ 'local.email' :  email }, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // check to see if theres already a user with that email
                if (user) {
                    return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
                } else {

                    // if there is no user with that email
                    // create the user
                    var newUser            = new User();

                    // set the user's local credentials
                    newUser.local.email    = email;
                    newUser.local.password = newUser.generateHash(password);

                    // save the user
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }

            });    

            });

        }));

    };
            });


        }));

    };
    ser
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }

            });    

            });

        }));

    };


        }));

    };
    ser
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }

            });    

            });

        }));

    };

How do I implement this and what do I write in route code. Thanks

[question] async function on Strategy example

Is there any example of how to use an async function for a Strategy, like:

passport.use(new LocalStrategy(async (username, password, done) => {
   const user = await User.findOne({username: username})

   if (user) {
      done(null, user)
   } else {
       done(null, false)
   }
}))

Facebook oauth: where is the oauthed user object?

Hey, great job!
I just migrated from express to koa but I cannot access the authenticated user object from the successRedirect.
I can only find "this.passport.user" in the success callback.
What is missing here? I'm using [email protected] and [email protected], no sessions!

let passport = require('koa-passport');
let FacebookStrategy = require('passport-facebook');

let Router = require('koa-router');
const router = module.exports = new Router();

let oauthed = (accessToken, refreshToken, profile, done) => {
    if(!profile.emails || !profile.emails.length)
        done(null, false);
    done(null, profile);
};

let facebookStrategy = new FacebookStrategy({
    clientID: config.facebook.clientID,
    clientSecret: config.facebook.clientSecret,
    callbackURL: config.facebook.callbackURL,
    profileFields: config.facebook.profileFields,
}, oauthed);
passport.use(facebookStrategy);

router.all('/facebook/oauth', passport.authenticate('facebook', { authType: 'rerequest', scope: ['email', 'public_profile'] }));

/** WORKING **/
router.all('/facebook/oauthed', passport.authenticate('facebook', { /*successRedirect: '/api/auth/success',*/ failureRedirect: '/api/auth/failure', session: false }), function *(next){
    this.body = this.passport.user;
});

/** NOT WORKING **/
router.all('/facebook/oauthed', passport.authenticate('facebook', { successRedirect: '/api/auth/success', failureRedirect: '/api/auth/failure', session: false }));
router.all('/success', function *(ctx, next) {
    //no user object anywhere, just undefined and nulls around here!
    this.body = [this.request.user, this.passport.user, this.req.user, this.user, ctx.user];
});

Issue with "passport-google-auth"

If you got at least one of below things when making google sign in...

1. Failed to retrieve user profile Legacy People API has not been used in project... (in console)
2. Failed to obtain access token invalid_grant... (in console)
3. Internal server error (on browser)

I recommend you change dependency module "passport-google-auth" to "passport-google-oauth".
Then modify parts that the module used like this.
const GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
and follow here http://www.passportjs.org/docs/google/

Include / link to example using a database

Hi Markus,

I'm using Koa 2.0 and koa-passport in my app now and it's awesome. The most difficult part was translating the example code and scripts into workable examples, where there are users stored in the database, potentially multiple users, csrf protection, sessions, etc. I understand the point of keeping this example code simple, but this simplified code proved unhelpful when I wanted to implement koa-passport in a real app.

Can this repo include or link to real-world examples of koa-passport? My own mongodb code is available here https://github.com/mapmeld/koa-passport-example

I'm writing a more detailed example app at https://github.com/mapmeld/1batch/wiki though I just moved it from Express to Koa v2, so that's not complete yet

-- Nick

help with passport-twitter

Hi there, im attempting to transplant your twitter example ( which works for me in the example ) into a pre-existent project. when I hit the initial /auth/twitter, i get a 500 and this error (the route is being arrived at, I can log messages when it is hit )

  TypeError: Object prototype may only be an Object or null: undefined
      at Function.create (native)
      at createReqMock (/Users/basiclaser/work/databird/node_modules/koa-passport/lib/framework/koa.js:187:22)
      at /Users/basiclaser/work/databird/node_modules/koa-passport/lib/framework/koa.js:108:19
      at new Promise (/Users/basiclaser/work/databird/node_modules/core-js/modules/es6.promise.js:197:7)
      at Object.passportAuthenticate (/Users/basiclaser/work/databird/node_modules/koa-passport/lib/framework/koa.js:106:15)
      at Object.dispatch (/Users/basiclaser/work/databird/node_modules/koa-router/lib/router.js:324:52)
      at [object Generator].next (native)
      at Object.<anonymous> (/Users/basiclaser/work/databird/node_modules/koa-compose/index.js:29:5)
      at [object Generator].next (native)
      at onFulfilled (/Users/basiclaser/work/databird/node_modules/co/index.js:65:19)
      at /Users/basiclaser/work/databird/node_modules/co/index.js:54:5
      at new Promise (/Users/basiclaser/work/databird/node_modules/core-js/modules/es6.promise.js:197:7)
      at Object.co (/Users/basiclaser/work/databird/node_modules/co/index.js:50:10)
      at Object.createPromise (/Users/basiclaser/work/databird/node_modules/co/index.js:30:15)
      at Server.<anonymous> (/Users/basiclaser/work/databird/node_modules/koa/lib/application.js:132:8)
      at emitTwo (events.js:100:13)

and here's my current router/auth file

const appDir = require('path').dirname(require.main.filename);
import App from 'koa';
const app = App();
import views from 'co-views';
import publicRoute from 'koa-static'
import {initialTweets} from './initialTweets';
import {searchTweets} from './search';

import Router from 'koa-router';
const router = Router();
import Passport from 'koa-passport';
const passport = Passport;


export function setUpRoutes(){
  var TwitterStrategy = require('passport-twitter').Strategy
  var user = { id: 1, username: 'test' }
  passport.serializeUser(function(user, done) {
    done(null, user.id)
  })
  passport.deserializeUser(function(id, done) {
    done(null, user)
  })
  passport.use(new TwitterStrategy({
      consumerKey: 'sYwaHTFjXlPSUqic9',
      consumerSecret: 'Ka9Ds05LO88SFPf8f7zJwROMasgN6ixzAhlPBKSl7kV',
      callbackURL: 'http://127.0.0.1:4000/auth/twitter/callback'
    },
    function(token, tokenSecret, profile, done) {
      console.log("authentication occured");
      done(null, user)
    }
  ))

  const render = views(appDir + '/views', { ext: 'ejs' });
  app
    .use(router.routes())
    .use(router.allowedMethods())
    .use(publicRoute(appDir + '/public'))
  router
    // new & unauthenticated users
    .get('/', function *(next) {
      this.body = yield render('landing');
    })
    // authenticate users with Twitter
    .get('/auth/twitter',
      passport.authenticate('twitter')
    )
    // redirect users after attempting to authenticate with Twitter
    .get('/auth/twitter/callback',
      passport.authenticate('twitter', {
        successRedirect: '/app',
        failureRedirect: '/'
    }))
    // logged in users
    .get('/app', function *(next) {
      this.body = yield render('index');
    })

    app.listen(4000);
}

If you can shed any light on why you think it might be happening, i would really appreciate it. Thanks!

Update for Async/Await

I've seen the comments in koa-passport #63, but I was wondering if there was any movement towards getting this example updated with async/await now that it's been available in Node 7 for a few releases.

Not able to login using local strategy.

I copied the koa-passport-example folder as it is. Npm installed. I also added koa-logger for logging. POST /login is returning 302. What could be the reason?

<-- POST /login
--> POST /login 302 88ms -
<-- GET /app

Doesn't seem to work with BasicStrategy (passport-http)

Hi.
While this works perfectly with the local strategy, I can't make it work with Basic.
The verify function defined in passport.use doesn't seem to be called at all.
I'll post my code

import Passport from './auth'
app.use(Passport.initialize())
app.use(Passport.session())
app.use(Route.post('/login', function* (next){
  var ctx = this
   yield Passport.authenticate('local', {session: false}, function*(err, user, info) {
    if (err) throw err
    if (user === false) {
      ctx.status = 401
      console.log(err)
    } else {
      ctx.body = user
    }
  }).call(this, next)
}
))

and this is auth.js:

import Passport from 'koa-passport'
import db from './db'
import "babel-polyfill"
var BasicStrategy = require('passport-http').BasicStrategy


Passport.use(new BasicStrategy((username, password, done)=> {
  db.models.parent.findOne({
    where: {
      email: username
    }
  }).then(user => {
    if(!user){
      return done(null, false, { message: 'Unknown user' })
    } else if(password != user.password){
      return done(null, false, { message: 'Invalid password'});
    } else {
      return done(null, user)
    }
  })
}))

export default Passport

If I use local with this same code, it works perfectly.

thanks!

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.