GithubHelp home page GithubHelp logo

sails-social-auth-example's Introduction

Sails.js Social Auth example with Passport and MongoDB Dependency Status

Requirements

  • sails >= 0.10.4
  • node >= 0.10.0
  • MongoDB

Setup

  1. Clone the repository git clone https://github.com/stefanbuck/sails-social-auth-example.git
  2. Navigate into the directory cd sails-social-auth-example
  3. Run npm install to install the dependencies
  4. Set up your MongoDB settings config/connections.js
  5. Start your MongoDB from the command line with sudo mongod
  6. Set up your strategies
  7. Start sails with sails lift
  8. Open http://localhost:1337 in your browser

Available authentication strategies

Google+

  1. Create a new app here
    • Name sails-social-auth-example
    • URL http://localhost:1337
    • Callback URL http://localhost:1337/auth/google/callback
  2. In the config/express.js replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the generated keys

GitHub

  1. Create a new app here
    • Name sails-social-auth-example
    • URL http://localhost:1337
    • Callback URL http://localhost:1337/auth/github/callback
  2. In the config/express.js replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the generated keys

Facebook

  1. Create a new app here
    • Name sails-social-auth-example
    • URL http://localhost:1337
    • Callback URL http://localhost:1337/auth/facebook/callback
  2. In the config/express.js replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the generated keys

Twitter

  1. Create a new app here
    • Name sails-social-auth-example
    • URL http://localhost:1337
    • Callback URL http://localhost:1337/auth/twitter/callback
  2. In the config/express.js replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the generated keys

License

The MIT License (MIT)

Copyright (c) 2014 Stefan Buck

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.

sails-social-auth-example's People

Contributors

bitdeli-chef avatar broud avatar brunocascio avatar calvertyang avatar jybleau avatar nmn avatar stefanbuck avatar zyadsherif 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sails-social-auth-example's Issues

Errors for missing policies in api/policies/

Immediately on start the console complains that the policies for basicAuth and passport are non-existant, and neither are in the api/policies/ dir as the command line describes.

Return URL problem when using path.join

In services/passport.js file you are using path.join method for creating the callback url, like this:

if (!callback) {
  callback = path.join('auth', key, 'callback');
 }

On Windows this results to this:

http://localhost:1337/auth\facebook\callback

which obviously does not work. Better solution for this might be something like this:

callback = ['auth', key, 'callback'].join("/")

Failed to login more than one person.

Hi, everythings works fine, but it seems to failed to log in from my friends accounts. It works only from my facebook profile. Why is that ? Do I have to change something else in my code besides this Setup which you explained here?

Instructions for adding new Strategies

Could someone please provide instructions for adding new strategies?

  1. I installed passport-instagram via npm
  2. in my config/express.js
  3. I added InstagramStrategy = require('passport-instagram').Strategy
  4. I added a new entry for the InstagramStrategy like so
passport.use(new InstagramStrategy({
      clientID: '---',
      clientSecret: '---',
      callbackURL: "http://localhost:1337/auth/instagram/callback"
    }, verifyHandler));
  1. In my AuthController.js i added an entry for Instagram
instagram: function(req, res) {
    passport.authenticate('instagram', { failureRedirect: '/login' }, function(err, user) {
      req.logIn(user, function(err) {
        console.log(err)
        if (err) {
          console.log(err);
          res.view('500');
          return;
        }

        res.redirect('/');
        return;
      });
    })(req, res);
  },

However when i try to go to /auth/instagram and I am redirected back to my app as i should but i get an error on the node saide saying: [TypeError: Cannot read property 'uid' of undefined]. What am I missing?

Getting username from the req.user

How do i get the username and other details of the logged in user. Now I am getting only the below by using "req.user"
{
email: '[email protected]',
createdAt: '2015-08-12T10:47:25.404Z',
updatedAt: '2015-08-12T10:47:25.405Z',
id: '55cb243d8bbd86d5237c2f7f'
}

Authentication for socket requests

I could not figure out how authentication is handled for socket requests. Any guidelines on how to wire up authentication for socket.io?

Google authentication callback never triggers

I'm calling this in my UserController , while the great Google login screen appears , and I can sign in , I never get my log statement .

google: function(req, res) {
passport.authenticate('google', { failureRedirect: '/login', scope: ['email'] }, function(err, user) {

    sails.log(user) ; 
  req.logIn(user, function(err) {
    if (err) {
      console.log(err);
      res.view('500');
      return;
    }

    res.redirect('/');
    return;
  });
})(req, res);

},

Here's a copy of my express.js file with my keys taken out , I'm trying to run a basic log statement here too...

var passport = require('passport')

,  GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

var verifyHandler = function(token, tokenSecret, profile, done) {
sails.log("p" ) ;
process.nextTick(function() {

User.findOne({uid: profile.id}, function(err, user) {
  if (user) {
    return done(null, user);
  } else {

    var data = {
      provider: profile.provider,
      uid: profile.id,
      name: profile.displayName
    };

    if (profile.emails && profile.emails[0] && profile.emails[0].value) {
      data.email = profile.emails[0].value;
    }
    if (profile.name && profile.name.givenName) {
      data.firstname = profile.name.givenName;
    }
    if (profile.name && profile.name.familyName) {
      data.lastname = profile.name.familyName;
    }

    User.create(data, function(err, user) {
      return done(err, user);
    });
  }
});

});
};

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

passport.deserializeUser(function(uid, done) {
User.findOne({uid: uid}, function(err, user) {
done(err, user);
});
});

/**

  • Configure advanced options for the Express server inside of Sails.
    *

  • For more information on configuration, check out:

  • http://sailsjs.org/#documentation
    */
    module.exports.http = {

    customMiddleware: function(app) {

    passport.use(new GoogleStrategy({
    clientID: 'actualID',
    clientSecret: 'actualSecret',
    returnURL: 'http://localhost:1337/auth/google/callback',
    callbackURL: 'http://localhost:1337/auth/google/callback',
    onSuccess:verifyHandler
    }, verifyHandler));

    app.use(passport.initialize());
    app.use(passport.session());
    }

    // Completely override Express middleware loading.
    // If you only want to override the bodyParser, cookieParser
    // or methodOverride middleware, see the appropriate keys below.
    // If you only want to override one or more of the default middleware,
    // but keep the order the same, use the middleware key.
    // See the http hook in the Sails core for the default loading order.
    //
    // loadMiddleware: function( app, defaultMiddleware, sails ) { ... }

    // Override one or more of the default middleware (besides bodyParser, cookieParser)
    //
    // middleware: {
    // session: false, // turn off session completely for HTTP requests
    // 404: function ( req, res, next ) { ... your custom 404 middleware ... }
    // }

    // The middleware function used for parsing the HTTP request body.
    // (this most commonly comes up in the context of file uploads)
    //
    // Defaults to a slightly modified version of express.bodyParser, i.e.:
    // If the Connect bodyParser doesn't understand the HTTP body request
    // data, Sails runs it again with an artificial header, forcing it to try
    // and parse the request body as JSON. (this allows JSON to be used as your
    // request data without the need to specify a 'Content-type: application/json'
    // header)
    //
    // If you want to change any of that, you can override the bodyParser with
    // your own custom middleware:
    // bodyParser: function customBodyParser (options) { ... return function(req, res, next) {...}; }
    //
    // Or you can always revert back to the vanilla parser built-in to Connect/Express:
    // bodyParser: require('express').bodyParser,
    //
    // Or to disable the body parser completely:
    // bodyParser: false,
    // (useful for streaming file uploads-- to disk or S3 or wherever you like)
    //
    // WARNING
    // ======================================================================
    // Multipart bodyParser (i.e. express.multipart() ) will be removed
    // in Connect 3 / Express 4.
    // Why?
    //
    // The multipart component of this parser will be replaced
    // in a subsequent version of Sails (after v0.10, probably v0.11) with:
    // file-parser
    // (or something comparable)
    //
    // If you understand the risks of using the multipart bodyParser,
    // and would like to disable the warning log messages, uncomment:
    // silenceMultipartWarning: true,
    // ======================================================================

    // Cookie parser middleware to use
    // (or false to disable)
    //
    // Defaults to express.cookieParser
    //
    // Example override:
    // cookieParser: (function customMethodOverride (req, res, next) {})(),

    // HTTP method override middleware
    // (or false to disable)
    //
    // This option allows artificial query params to be passed to trick
    // Sails into thinking a different HTTP verb was used.
    // Useful when supporting an API for user-agents which don't allow
    // PUT or DELETE requests
    //
    // Defaults to express.methodOverride
    //
    // Example override:
    // methodOverride: (function customMethodOverride (req, res, next) {})()
    };

/**

  • HTTP Flat-File Cache
    *

  • These settings are for Express' static middleware- the part that serves

  • flat-files like images, css, client-side templates, favicons, etc.
    *

  • In Sails, this affects the files in your app's assets directory.

  • By default, Sails uses your project's Gruntfile to compile/copy those

  • assets to .tmp/public, where they're accessible to Express.
    *

  • The HTTP static cache is only active in a 'production' environment,

  • since that's the only time Express will cache flat-files.
    *

  • For more information on configuration, check out:

  • http://sailsjs.org/#documentation
    */
    module.exports.cache = {

    // The number of seconds to cache files being served from disk
    // (only works in production mode)
    maxAge: 31557600000
    };

Add license

Having an explicit licensing of your code is a Good Idea, because it allows others to modify it to suit their own needs.

iFixit/pulldash#13 cannot, unfortunately, be satisfied until a license is added to this repo. Even more unfortunately, this is a modification of yet another repository, so I've got to go file an issue there first, so you know under what terms you can make your modifications available, so we can know under what terms we can make our modifications of your modifications available.

how can i enable sail's default CRUD operations?

first of all, thanks for this great package! you really gave me a kick-start - much appreciated.

second, when i try to access http://localhost:1337/user/, or http://localhost:1337/user/find?gender=male
i get an The page you were trying to reach doesn't exist. error...

i tried fixing the policies to accept
'user' : true,
for testing purposes, and when trying to lift the sails i get -

'user' : true,
^^^^^^
SyntaxError: Unexpected string

in the console.
any idea how can overcome this, and enable them?
i really hope you could help me figure this out, i am trying to wrap my head around this and could use some help...
and again - thanks a lot again for this great repo, you sure did helped me out already!...

Cannot find module 'express/node_modules/cookie'

I followed the instructions and when I run the program I get this error:

info: Starting app...

module.js:487
throw err;
^

Error: Cannot find module 'express/node_modules/cookie'
at Function.Module._resolveFilename (module.js:485:15)...

sails 0.10.x

Add the following to config\models
module.exports.models = {

// Your app's default connection.
// i.e. the name of one of your app's connections (see config/connections.js)
//
// (defaults to localDiskDb)
migrate:safe, // add
connection: 'localDiskDb'
};

auth/google/callback never gets called

I was playing around with your great example and tried to extend / customize especially the callback route that is defined for the google passport strategy. But it seems that the route never gets called.

So I debugged it and found out, that the starting route "google" is called twice. Once for the initial request and also for the callback from google. The request object also tells me that the url in the second call is "xyz/auth/google/callback?code123..." which should be routed to the "google/callback" action I hoped.

Am I missing something? Is the callback action working for you or have there been some changes in sails.js since you tested last time?

However your example is working perfectly fine and I've just started with sails.js - but it's very confusing that the callback route (or lets call it sub-action-route) never gets activated.

Best,
Bastian

MySQL Database

Hello!.,
I am trying to follow the implementation of passport using facebook authentication following your pattern,but using MySQL.The problem is that the verifyHandler is allowing the creation of a user,but is not able to find the user to block their creation if they exist.
Do you have an idea how to go about that.

Twitter auth stopped working

Hi

I got the Twitter auth working couple of weeks ago. Now suddenly I am landing on /auth/twitter and getting 500 Internal server error.

In sails console:
[TypeError: Cannot read property 'uid' of undefined]

Google and Facebook are still working.

I tried also freshly checked out sails-social-auth-example with node 0.10.5 and 0.10.4.
Only changes I did were:

  • configure the twitter tokens and url
  • use sails-disk as default connection in models
  • disable mongo store on User.js
  • disable the mongo sessionstore (also on my project it was disabled when twitter auth was working)

I got the same error.

Any help and input is welcomed.

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.