Coder Social home page Coder Social logo

trailsjs / sails-auth Goto Github PK

View Code? Open in Web Editor NEW
265.0 265.0 141.0 219 KB

Passport-based User Authentication system for sails.js applications. Designed to work well with the sails-permissions module.

Home Page: https://www.npmjs.org/package/sails-auth

License: MIT License

JavaScript 100.00%

sails-auth's People

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

sails-auth's Issues

Passport Policy Suggestion

@tjwebb I've been digging around a lot of different implementations of Passport.js into sails, and I've found this really useful. By updating policies/passport.js to this, it will allow socket passport authentication which I am seeing more and more of.

// policies/passport.js
var http = require('http');
var methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
module.exports = function (req, res, next) {
  // Initialize Passport
  passport.initialize()(req, res, function () {
    // Use the built-in sessions
    passport.session()(req, res, function () {
      // Make the user available throughout the frontend
      res.locals.user = req.user;
      // Make the request's passport methods available for socket
      if (req.isSocket) {
        for (var i = 0; i < methods.length; i++) {
          req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
        }
      }
      next();
    });
  });
};

I've just tested this using:
Sails: 0.11.0
sails-auth: 1.0.8

Email not transferred to SailsJS

I implemented sails-auth using the below in the passports.js file

passport : {
        twitter : {
            name : 'twitter',
            protocol:'oauth',
            strategy:require('passport-twitter').Strategy,
            options:{
                consumerKey:'...',
                consumerSecret:'...'
            }
        }
    }

The twitter app has read/write permissions on my twitter profile. The auth also works, but then Sails crashes, because in User.js it tries to generate the Gravatar URL with 'this.email' which is not set at all. The generated user looks like this

{
  "owner": 3,
  "username": "WillemMulder",
  "id": 3,
  "createdAt": "2015-04-07T17:05:04.120Z",
  "updatedAt": "2015-04-07T17:05:04.212Z"
}

Any clue why the email might not be filled?

Documentation would be greatly appreciated

I've been trying to bring sails-auth into an existing project and I have to say this is more painful due to the lack of documentation. There's good promise in sails-auth but can the project in its current state to really be used? If so, what exact steps does one need to do, what exactly needs to be implemented by hand and what does sails-auth implement.

  1. How to get registration and login working with simple local auth. I'm basically just hitting 404s and from /auth/local/register for example. Yeah, clearly templates are not provided but the feeling I have right now is: "is anything else either"?
  2. How to implement simple bearer authentication. Whether with oauth2 or just raw passport-http-bearer, what needs to be implemented to just authenticate the user.

I'm fine with manually adding tokens to users. All I want is to validate that this thing is going to work and to do that I need to know what templates / callbacks etc. need to be implemented and where.

PS. A note about the need to add "auth-api": "sails-auth" to .sailsrc would be good.

after fresh install, a visit to /auth/google produces error

/Users/jeff/www/test-sails/node_modules/sails-auth/node_modules/passport/lib/http/request.js:44
    if (!this._passport) { throw new Error('passport.initialize() middleware n
                                 ^
Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn (/Users/jeff/www/test-sails/node_modules/sails-auth/node_modules/passport/lib/http/request.js:44:34)
    at /Users/jeff/www/test-sails/node_modules/sails-auth/api/controllers/AuthController.js:93:11
    at Strategy.strategy.success (/Users/jeff/www/test-sails/node_modules/sails-auth/node_modules/passport/lib/middleware/authenticate.js:194:18)
    at verified (/Users/jeff/www/test-sails/node_modules/sails-auth/node_modules/passport-google/node_modules/passport-openid/lib/passport-openid/strategy.js:194:14)
    at /Users/jeff/www/test-sails/node_modules/sails-auth/api/services/passport.js:135:13
    at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:241:9
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:157:25
    at null.<anonymous> (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/schema.js:151:44)

Can't unit test Passport.beforeCreate to ensure the password is hashed

I have written the following unit test below for the passport module and it is failing. I am able to get the unit test passing if I update the following line in sails-auth/api/models/Passport.js: line 20

changed:
     next(err);
to:
     next(null, passport);

var assert = require('assert');

describe('Passport Model', function () {

  describe('before the passport is created', function () {

    it ('should hash the password', function (done) {
        Passport.beforeCreate({ password: 'password' }, function (err, passport) {
             assert.notEqual(passport.password, 'password');
             done();
      });
    });
  });
});

No generator called `auth-api` found

Hi,

I'm following the steps on Sails v0.10.5 and auth-api can't be found. Here is the log:

$ npm install sails-auth --save
npm WARN unmet dependency ./node_modules/sails-disk/node_modules/waterline-cursor requires lodash@'~2.4.1' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
[email protected] node_modules/sails-auth
├── [email protected]
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected])
$ sails generate auth-api
error: No generator called `auth-api` found; perhaps you meant `sails generate api auth-api`?

Google Sign in Issues

New to Sails, spent many hours trying to get Google Sign-in via Passport. Here are issues I have encountered

  1. It seems like I have to overwrite the google credentials in /node_modules/sails-auth/config/passport.js rather than my own config/passport.js. I am sure this is incorrect, but could not get it work by copying / pasting what was in the node module passport.js into my own. How do I make this work with my own config/passport.js? Currently trying

    // config/passport.js
    
         var _ = require('lodash');
      var _super = require('sails-permissions/config/passport');
         _.merge(exports, _super);
         _.merge(exports, {
         // Extend with custom logic here by adding additional fields, methods, etc.
    
     google: {
           name: 'Google',
            protocol: 'oauth2',
               strategy: require('passport-google-oauth').OAuth2Strategy,
             options: {
                clientID: 'my_id',
                 clientSecret: 'my_secret',
                scope: ['profile', 'email']
             }
            }
       });
    
  2. Using default permissions after following instructions on sails-permissions, I can't properly create a user. The is stuck behind permissions it seems, and there is no clear way to enable it. I can get to /auth/google but not to /auth/google/callback. How do I easily disable permissions for now?

  3. I had to manually install the passport-google-oauth package. But yet it seems like it should be it is already included as a dependency. I am using NVM. Encountered this with lodash as well. Does this seem right?

    npm install passport-google-oauth --save
    
  4. It is not clear how I would use Sails Js with Googles iOS native cocoa pod that handles sign-ins. Can I pass in an access_token/refresh_token here instead of using the web redirect? If not, do I need another passport strategy?

  5. I was able to create a user via web sign-in, but I don't see where the Google specific info is stored in my database. I see the user in the users table, but I don't see the refresh token stored anywhere. My passport table is empty. Where is this info stored?

  6. When I authenticate with same email address many times I get a warning about a user already existing. Similar to #64 Do I need to do something special to handle this situation?

How to redirect user after passport login?

Hello!

I'm using passport login and google provider. After logging in, Sails returns JSON document with profile information. How do I redirect client to the page of my choice instead (e.g. homepage or profile page)?

Thank you.

Local login doesn't work.

Hello! I try to login and post user's email and pass to /auth/local/ but it get 403 response. Method exports.login from sails-auth/api/services/protocols/local.js (123) doesn't called. Then i made some fix in sails-auth/api/services/passport.js (256):

this.authenticate(provider, next)(req, res, req.next);

to

this.protocols.local.login(req, req.body.email, req.body.password, next);

It works alright, but looks bad. Can somebody help me use sails-auth in the right way?

Need "user profile" info in passport or user object

Please see #63 for more details. Can I get an update on this issue? Seems to be closed but what is the plan of implementing it? I would like to access all the fields available for google + facebook. It is not currently available and neither is there any hook or configuration where we could access the profile information.

Invalid email address in user creation throws 500

Trying to create a User by POSTing

{
  "username": "test",
  "email": "test@local",
  "password": "test1234"
}

results in a response containig {} with status 500 and the following logs:

debug: Error (E_VALIDATION) :: 1 attribute is invalid
    at WLValidationError.WLError (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/error/WLError.js:26:15)
    at new WLValidationError (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js:20:28)
    at /usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/validate.js:45:43
    at allValidationsChecked (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/core/validations.js:198:5)
    at done (/usr/lib/node_modules/sails/node_modules/async/lib/async.js:132:19)
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:32:16
    at validate (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/core/validations.js:135:49)
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:122:13
    at _each (/usr/lib/node_modules/sails/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/usr/lib/node_modules/sails/node_modules/async/lib/async.js:121:9)
    at Validator.validate (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/core/validations.js:195:9)
    at async.series.runner (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/validate.js:41:25)
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:607:21
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:246:17
    at iterate (/usr/lib/node_modules/sails/node_modules/async/lib/async.js:146:13)
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:157:25

Invalid attributes sent to User:
 • email
   • `undefined` should be a email (instead of "test@local", which is a string)

error: Sending 500 ("Server Error") response: 
 Error: Error.Passport.Email.Exists
    at /home/milka/Projects/minimoo/node_modules/sails-auth/api/services/protocols/local.js:45:23
    at /usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:73:22
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:251:17
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:148:21
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:248:21
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:612:34
    at /usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/validate.js:70:22
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:251:17
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:148:21
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:248:21
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:612:34
    at /usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/validate.js:45:40
    at allValidationsChecked (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/core/validations.js:198:5)
    at done (/usr/lib/node_modules/sails/node_modules/async/lib/async.js:132:19)
    at /usr/lib/node_modules/sails/node_modules/async/lib/async.js:32:16
    at validate (/usr/lib/node_modules/sails/node_modules/waterline/lib/waterline/core/validations.js:135:49) [Error: Error.Passport.Email.Exists]

I would expect the validation error to be returned, as it is when simply using the blueprints API.

Documentation for local authentication updates and maintaining user in session

I'm fairly new at Sailjs and have a question about sails-auth. Could you provide more information about how to use the authenticated user, and what the external links/routes may be for local authentication?
I'm assuming POST requests for all of these:

/auth/local/register
/auth/local/connect
/auth/local/disconnect

it would return to?

/auth/local/callback

When I do a post to /auth/local/register with username and password or email parameters it has a 500 Server Error response. Am I doing this correctly?
Sending 500 ("Server Error") response: RangeError: Maximum call stack size exceeded

Authenticating through Google, Facebook works fine (I get a returned JSON user). It returns to /auth/callback. What I'd like to do is return to /user/profile and show more information or something. When I tried to create this in the controller, I'm not getting a req.user or req.session.user or req.locals.user defined. Is there a way to get the authenticated user from a session?

I see there are connect/disconnect options available, are there parameters that need to be defined to hook these up? Or do you just need to have a registered session?

I'm using:
sails: ~0.11.0
sails-auth: 1.0.2

Attempted to `POST /register` with `[email protected]&password=admin1234` shuts down server

Attempted to POST /register with [email protected]&password=admin1234 instead of [email protected]&password=admin1234...

$ sails lift

info: Starting app...

-----------------------------------------------------------------

 Excuse my interruption, but it looks like this app
 does not have a project-wide "migrate" setting configured yet.
 (perhaps this is the first time you're lifting it with models?)

 In short, this setting controls whether/how Sails will attempt to automatically
 rebuild the tables/collections/sets/etc. in your database schema.
 You can read more about the "migrate" setting here:
 http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html?q=migrate

 In a production environment (NODE_ENV==="production") Sails always uses
 migrate:"safe" to protect inadvertent deletion of your data.
 However during development, you have a few other options for convenience:

 1. safe  - never auto-migrate my database(s). I will do it myself (by hand)
 2. alter - auto-migrate, but attempt to keep my existing data (experimental)
 3. drop  - wipe/drop ALL my data and rebuild models every time I lift Sails

What would you like Sails to do?

info: To skip this prompt in the future, set `sails.config.models.migrate`.
info: (conventionally, this is done in `config/models.js`)

warn: ** DO NOT CHOOSE "2" or "3" IF YOU ARE WORKING WITH PRODUCTION DATA **

prompt: ?:

 Temporarily using `sails.config.models.migrate="safe"...
 (press CTRL+C to cancel-- continuing lift automatically in 0.5 seconds...)

info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v0.11.0             |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `/Users/dan/sails-auth-test`
info: To see your app, visit http://localhost:1337
info: To shut down Sails, press <CTRL> + C at any time.

debug: --------------------------------------------------------
debug: :: Fri May 15 2015 20:29:45 GMT-0400 (EDT)

debug: Environment : development
debug: Port        : 1337
debug: --------------------------------------------------------
crypto.js:119
  this._handle.update(data, encoding);
               ^
TypeError: Not a string or buffer
    at TypeError (native)
    at Hash.update (crypto.js:119:16)
    at module.exports.attributes.getGravatarUrl (/Users/dan/sails-auth-test/node_modules/sails-auth/api/models/User.js:26:11)
    at module.exports.attributes.toJSON (/Users/dan/sails-auth-test/node_modules/sails-auth/api/models/User.js:33:31)
    at Object.stringify (native)
    at ServerResponse.res.json (/usr/local/lib/node_modules/sails/node_modules/express/lib/response.js:217:19)
    at ServerResponse.jsonx (/usr/local/lib/node_modules/sails/lib/hooks/responses/index.js:218:21)
    at Object.sendOK (/Users/dan/sails-auth-test/api/responses/ok.js:28:16)
    at ServerResponse.bound [as ok] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /Users/dan/sails-auth-test/node_modules/sails-auth/api/controllers/UserController.js:13:11
    at /Users/dan/sails-auth-test/node_modules/sails-auth/api/services/protocols/local.js:71:7
    at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:241:9
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:157:25
    at bound.<anonymous> (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/schema.js:151:44)
    at fn (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/callbacksRunner.js:60:10)
    at iterate (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:149:13)

 20:29:48  ✘ 1  dan@elise:~/sails-auth-test   master ✘ ✹ 
$

Trying to POST to /user gives me 403

Hey there.

I've configured sails-auth as you explain in your readme.

You say that one would normally POST to /user without a problem. But it's giving me 403:

{
    "error": "You are not permitted to perform this action."
}

Should I modify the config/policies.js you specify in your readme?.

Decoupling from sails.session, aiming to use JWT

Hi, and thanks for creating such a cool package!

I'm wondering how I can decouple my use of sails-auth from sails' session component, and maybe later have it work with no sessions at all. My goal in the end is to use tokens for both my frontend which is a single page app and later maybe external apps that rely on the API only.

I summed up my needs on this stackoverflow question but thought it'd be relevant to have it tagged as a question here.

Ideally I want to, no matter how the user authentifies (OAuth or local), generate a token. I guess for OAuth I would have to serve the index again, and embed the token directly in the page's JS, and for local to return the token via AJAX. But how/at what point do I create this token? And should I manually create a passport-http-bearer token or should I have my own layer of token?

I've been thinking and trying a lot of solutions in the past 2 days, with sessions and cookies it works fine but tokens have a lot of advantages and I'd like to go this way. Could you recommend the high-level auth flow that I should go for?

posting to auth/local on fresh install returns error

I'm getting the error below on a clean install of sails-auth and sails-permissions. It happens when I attempt to post to /auth/local with the default admin credentials { email: '[email protected]' password:'admin1234'}.

Error: Failed to serialize user into session
at pass (/Users/bgulotta/git/reach-api/node_modules/sails-auth/node_modules/passport/lib/authenticator.js:277:19)

TypeError: undefined is not a function

In file sails-auth/api/services/protocols/local.js

isEmail(identifier)

is causing the error TypeError: undefined is not a function

if I change it back to what sails-generate-auth uses i.e

validator.isEmail(identifier)

is works fine

Maintaining a Session and req.session.authenticated undefined

I can can login using passport-local and the session is created in my mongodb, but for any subsequent requests req.session.passport is always empty.

Also req.session.authenticated in the sessionAuth policy is always undefined.

Not sure if I'm missing something or if it's a bug, I've setup others sails projects with passport and not had this issue.

Major issue, sails shuts down completely after GET instead of POST request to /auth/local

io.socket.get('/auth/local', {identifier: '[email protected]', password: 'asdfasdf'}, function () { console.log('user', arguments); });
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v0.11.0             |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `/Users/dan/stuff/nodegolf`
info: To see your app, visit http://localhost:1337
info: To shut down Sails, press <CTRL> + C at any time.

debug: --------------------------------------------------------
debug: :: Thu May 14 2015 19:16:23 GMT-0400 (EDT)

debug: Environment : development
debug: Port        : 1337
debug: --------------------------------------------------------
/Users/dan/stuff/sails-auth/node_modules/passport/lib/middleware/authenticate.js:229
          if (err) { return next(err); }
                            ^
TypeError: undefined is not a function
    at /Users/dan/stuff/sails-auth/node_modules/passport/lib/middleware/authenticate.js:229:29
    at /Users/dan/stuff/sails-auth/node_modules/passport/lib/http/request.js:49:48
    at pass (/Users/dan/stuff/sails-auth/node_modules/passport/lib/authenticator.js:293:14)
    at Authenticator.serializeUser (/Users/dan/stuff/sails-auth/node_modules/passport/lib/authenticator.js:295:5)
    at Authenticator.bound [as serializeUser] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at MockIncomingMessage.req.login.req.logIn (/Users/dan/stuff/sails-auth/node_modules/passport/lib/http/request.js:48:29)
    at Strategy.strategy.success (/Users/dan/stuff/sails-auth/node_modules/passport/lib/middleware/authenticate.js:228:13)
    at verified (/Users/dan/stuff/sails-auth/node_modules/passport-local/lib/strategy.js:83:10)
    at /Users/dan/stuff/sails-auth/api/services/protocols/local.js:167:20
    at /Users/dan/stuff/sails-auth/node_modules/bcryptjs/dist/bcrypt.js:230:13
    at /Users/dan/stuff/sails-auth/node_modules/bcryptjs/dist/bcrypt.js:1167:21
    at Immediate.next [as _onImmediate] (/Users/dan/stuff/sails-auth/node_modules/bcryptjs/dist/bcrypt.js:1047:21)
    at processImmediate [as _immediateCallback] (timers.js:358:17)

Middleware not initialized

Hey TJ,

Following the steps to install sails-permissions, I receive this error

/SailsJSApp/node_modules/sails-auth/node_modules/passport/lib/http/request.js:44
    if (!this._passport) { throw new Error('passport.initialize() middleware n
                                 ^
Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn (/SailsJSApp/node_modules/sails-auth/node_modules/passport/lib/http/request.js:44:34)
    at /SailsJSApp/node_modules/sails-auth/api/controllers/AuthController.js:93:11
    at Strategy.strategy.success (/SailsJSApp/node_modules/sails-auth/node_modules/passport/lib/middleware/authenticate.js:194:18)
    at verified (/SailsJSApp/node_modules/sails-auth/node_modules/passport-google/node_modules/passport-openid/lib/passport-openid/strategy.js:194:14)

Seems like a relatively simple fix, but since Sails handles middleware configuration, I thought I would post here to get your thoughts on the issue.

disable globals

Hi, thank you for great module.

I'm not using globals in my project, so when I include your module it falls down with error:

ReferenceError: sails is not defined
    at Authenticator.passport.loadStrategies (/home/jifeon/projects/adwiki/node_modules/sails-auth/api/services/passport.js:278:20)
    at Authenticator.bound [as loadStrategies] (/home/jifeon/projects/adwiki/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at Hook.initialize (/home/jifeon/projects/adwiki/node_modules/sails-auth/api/hooks/sails-auth.js:4:31)
    at Hook.bound [as initialize] (/home/jifeon/projects/adwiki/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /home/jifeon/projects/adwiki/node_modules/sails/lib/hooks/index.js:75:14
    at /home/jifeon/projects/adwiki/node_modules/sails/node_modules/async/lib/async.js:454:17
    at /home/jifeon/projects/adwiki/node_modules/sails/node_modules/async/lib/async.js:444:17
    at Array.forEach (native)
    at _each (/home/jifeon/projects/adwiki/node_modules/sails/node_modules/async/lib/async.js:46:24)
    at Object.taskComplete (/home/jifeon/projects/adwiki/node_modules/sails/node_modules/async/lib/async.js:443:13)
    at processImmediate [as _immediateCallback] (timers.js:345:15)

Could you please use module system to include sails? In this case both users are using globals and not will be able to enjoy your module :)

Include "user profile" info in Passport object

1. Update Passport model

spec: http://passportjs.org/docs/profile
notes:

  • displayName should equal User.username
  • emails must contain User.email
  • photos should contain the gravatar url currently generated in user
  • all other fields should behave as they currently do
  • toJSON should strip password and tokens

2. Update UserController

  • findOne queries should always populate the Passport object

problem with just generated sails-auth policy

Now I have generated file config/policies/sails-auth.js with following content:

// config/policies/sails-auth.js

var _ = require('lodash');
var _super = require('sails-auth/config/policies/sails-auth');

_.merge(exports, _super);
_.merge(exports, {

  // Extend with custom logic here by adding additional fields, methods, etc.

  /**
   * For example:
   *
   * foo: function (bar) {
   *   bar.x = 1;
   *   bar.y = 2;
   *   return _super.foo(bar);
   * }
   */
});

but sails-auth/config/policies/sails-auth does not exist. Looks like a mistake

passport model should provide option to not rehash a password

#66 I was basing the detection off of $2a$%%$ and then any length after that, which would not care about salt or salt length. Yes it is possible that a user could have a password of $2a$08$.... but how likely is that?

I have other users other than admin that I need to add when the system is initialized and I don't have their unhashed password. As it is there is no option for adding them to the database without having their unhashed password.

What if there was an attribute on the passport that indicated whether or not it was already hashed and then "delete passport.passwordAlreadyHashed"?

Sails auth now throwing sails.services.passport.loadStrategies() undefined error.

I was building an app using sailsjs and after week ago it was working fine but right now I'm getting this error. I did'nt change anything. The stacktrace is given below:-

/home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails-auth/api/hooks/sails-auth.js:4
sails.services.passport.loadStrategies();
^
TypeError: Cannot read property 'loadStrategies' of undefined
at Hook.initialize (/home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails-auth/api/hooks/sails-auth.js:4:30)
at Hook.bound as initialize
at /home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails/lib/hooks/index.js:78:14
at /home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails/node_modules/async/lib/async.js:451:17
at /home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails/node_modules/async/lib/async.js:441:17
at _each (/home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails/node_modules/async/lib/async.js:46:13)
at Immediate.taskComplete (/home/redbuffer/my_stuff/apps/AfterEidApp1/node_modules/sails/node_modules/async/lib/async.js:440:13)
at processImmediate as _immediateCallback

res.json is deprecated

express deprecated res.json(num, status): Use res.status(status).json(num) instead ../sails-auth/api/policies/basicAuth.js:28:18

Missing Login method in the Local Callback

I'm having an issue trying to use login. I would just add this in and do a PR, but I am really bad at doing the testing stuff. I think this is what it should look like... perhaps I'm wrong?

callback: function (req, res, next) {
    var provider = req.param('provider', 'local');
    var action = req.param('action');

    // Passport.js wasn't really built for local user registration, but it's nice
    // having it tied into everything else.
    if (provider === 'local' && action !== undefined) {
      if (action === 'register' && !req.user) {
        this.protocols.local.register(req, res, next);
      }
      else if (action === 'login' && !req.user) {
        this.protocols.local.login(req, res, next);
      }
      else if (action === 'connect' && req.user) {
        this.protocols.local.connect(req, res, next);
      }
      else if (action === 'disconnect' && req.user) {
        this.protocols.local.disconnect(req, res, next);
      }    
      else {
        next(new Error('Invalid action'));
      }
    } else {
      if (action === 'disconnect' && req.user) {
        this.disconnect(req, res, next) ;
      } else {
        // The provider will redirect the user to this URL after approval. Finish
        // the authentication process by attempting to obtain an access token. If
        // access was granted, the user will be logged in. Otherwise, authentication
        // has failed.
        this.authenticate(provider, next)(req, res, req.next);
      }
    }
  }

Validation is broken

Posting {} to /user results in a successful registration. Same with posting password-less, username-less or email-less registration in any combination. They produce broken users entries.

What is the expected behaviour here?

Using dropbox-oauth2

So this had me confused for a little while. I'm was trying to use passport-dropbox-oauth2 to login, but ran into multiple issues. I had created the following object in config/passport.js

_.merge(exports, {
    passport:{
        dropbox:{
            name: 'Dropbox',
            protocol: 'oauth2',
            strategy: require('passport-dropbox-oauth2').Strategy,
            options: {
                clientID: 'xxx',
                clientSecret: 'xxx',
                callbackURL: '/auth/dropbox/callback' 
            }
        }
    }
});

this gave the following error:

Error: Unknown authentication strategy "dropbox"

Apparently sails-auth is using the key value of the object (in this case "dropbox") to find the right passport. However the passport is called dropbox-oauth2, so it will not find it an thus throw the error.

As you can't use a "-" as key value this way, you have to rebuild the object slightly to this:

 var passportObj = {passport:{}};

 passportObj.passport['dropbox-oauth2'] =  {
            name: 'dropbox-oauth2',
            protocol: 'oauth2',
            strategy: require('passport-dropbox-oauth2').Strategy,
            options: {
                clientID: 'xxx',
                clientSecret: 'xxx',
                callbackURL: '/auth/dropbox-oauth2/callback'
            }
 };


_.merge(exports, passport);

This solves the first issue. Maybe introducing a new value like passport-name in the object would be a cleaner way to do this?

After this I ran into the second issue: authenticating multiple times. Authenticating once goes smoothly, however authenticating twice throws the following error:

warn: Error (E_VALIDATION) :: 2 attributes are invalid
...
Invalid attributes sent to undefined:
 • username
   • A record with that `username` already exists (`[email protected]`).
 • email
   • A record with that `email` already exists (`[email protected]`).

It seems like sails-auth tries to create another user, while my user was already in the database. After some console.logging in sails-auth/api/services/passport.js I found out that provider was set to "dropbox", while in the database the provider is set to "dropbox-oauth2", so the passport is not found and a new passport is created, but the user already exists.

I currently fixed this quick and dirty by setting the provider to dropbox-oauth2 (hard in passport.js). I can imagine that some parts of sails-auth have to be rewritten in order to deal with passports that don't match the provider / have dashes in there name.

I hope this illustrates the problem with less common passports.

Lifting the app after the first time throws errors trying to create an admin user that already exists

$ sails lift

info: Starting app...

debug: sails-permissions: syncing waterline models
debug: sails-permissions: admin user does not exist; creating...
debug: Error (E_VALIDATION) :: 2 attributes are invalid
    at WLValidationError.WLError (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/error/WLError.js:26:15)
    at new WLValidationError (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js:20:28)
    at duckType (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/error/index.js:60:12)
    at errorify (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/error/index.js:39:10)
    at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:325:15)
    at callback.error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
    at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:46:28)
    at null._onTimeout (/usr/local/lib/node_modules/sails/node_modules/sails-disk/lib/adapter.js:179:10)
    at Timer.listOnTimeout (timers.js:110:15)

Invalid attributes sent to undefined:
 • username
   • A record with that `username` already exists (`[email protected]`).
 • email
   • A record with that `email` already exists (`[email protected]`).

error: Error: Error.Passport.Email.Exists
    at /Users/dan/stuff/sails-auth/api/services/protocols/local.js:45:23
    at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:216:14
    at bound (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:957:21)
    at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
    at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:331:16)
    at callback.error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
    at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:46:28)
    at afterwards (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/adapter/dql.js:88:16)
    at bound (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:957:21)
    at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
    at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:331:16)
    at callback.error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
    at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:46:28)
    at null._onTimeout (/usr/local/lib/node_modules/sails/node_modules/sails-disk/lib/adapter.js:179:10)
    at Timer.listOnTimeout (timers.js:110:15)
From previous event:
    at bound.module.exports.register (/Users/dan/stuff/sails-auth/api/models/User.js:42:12)
    at bound [as register] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /Users/dan/stuff/sails-permissions/config/fixtures/user.js:20:19
    at processImmediate [as _immediateCallback] (timers.js:358:17) [Error: Error.Passport.Email.Exists]

Investigate another way to instantiate strategies

Not all passport strategies have the signature of new Strategy(options, verifyFn). For example: passport-jwt has a signature of new Strategy(secret, options, verifyFn) (dumb, I know).

Either we pressure strategy authors to implement a standard signature or we investigate a pattern for defining strategies that allows for more flexible loading.

Having to edit the passport service all the time will get old quickly.

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.