User authentication plugin for mongoose nodejs orm
User authentication plugin for mongoose nodejs orm
User authentication plugin for mongoose node.js orm.
mongoose-auth enables you to support authorization in any number of ways via authorization strategies.
An authorization strategy is how you authorize your user. Currently mongoose-auth supports the following authorization strategies:
passwordfacebooktwittergithubinstagramgooglemongoose-auth does 3 things:
It integrates the everyauth module to help it take care of the routing and helpers. everyauth is a general purpose npm module for authentication & authorization that can be used independently of mongoose.
As you add successive authorization strategies, mongoose-auth at a bare minimum augments your schema with typed attributes corresponding to parameters related to your chosen authorization strategies. For example, if facebook is one of your authorization strategies, then it will add attributes to your User Schema such as 'fb.id' and 'fb.email'.
To decorate your schema:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, mongooseAuth = require('mongoose-auth');
var UserSchema = new Schema({});
UserSchema.plugin(mongooseAuth, {
facebook: true
});Applications require more than just User Schema augmentation in order to implement a complete authorization strategy. Applications also need routes exposing the one or more steps involved for a given authorization strategy. Moreover, applications each handle in their own unique way how they want to respond to successful or failed logins (in addition to logout handling). If you are not using a connect, then you will have to set all of this up yourself. In this case, mongoose-auth only provides you with Schema decoration.
But, if you are building your app on top of connect, then mongoose-auth provides drop in solutions for you. Here is how you can get access to the routing that mongoose-auth provides. Not the "STEP X: ..." comments:
…In "Step 3" of the last code sample, we are adding dynamic view helpers, for if
you are using the Express web framework.
This automically gives you access to a convenient everyauth local variable from
your view, so you do not have to pass req as a local to your view:
everyauth.loggedIn - a Boolean getter that tells you if the request is by a logged in usereveryauth.user - the mongoose User document associated with the sessioneveryauth.facebook - The is equivalent to what is stored at req.session.auth.facebook,
so you can do things like ...everyauth.facebook.user - returns the user json provided from the OAuth provider.everyauth.facebook.accessToken - returns the access_token provided from the OAuth provider
for authorized API calls on behalf of the user.everyauth.twitter.user,
everyauth.github.user, etc.You also get access to the view helper
user - the same as everyauth.user aboveAs an example of how you would use these, consider the following ./views/user.jade jade template:
.user-id
.label User Id
.value #{user.id}
.facebook-id
.label User Facebook Id
.value #{everyauth.facebook.user.id}The "STEP 2: Add in the Routing" step in the last code sample also provides convenience methods on the
ServerRequest instance req. From any scope that has access to req, you get the following
convenience getter and method:
req.loggedIn - a Boolean getter that tells you if the request is by a logged in userreq.user - the mongoose User document associated with the sessionreq.logout() - clears the sesion of your auth dataYou can also use multiple authorization strategies in the same application. Here is an example, using 5 authorization strategies:
…There is an example app located in ./example. To run it:
$ cd example
$ node server.jsThen navigate to http://localhost:3000/
A common recipe is allowing a user to login via multiple accounts and to link those accounts under one user document.
This can be done in the following way:
The real magic lies with https://github.com/bnoguchi/everyauth/, and it should be more obvious once I document everyauth more and document mongoose-auth's relationship to everyauth.
In everyauth's design, every auth module is defined as a set of steps, which are exposed in such a way for
you to over-ride. The step that is of particular interest for this scenario is the findOrCreateUser step
required by every everyauth module. mongoose-auth defines a default version of this findOrCreateUser
step for each everyauth auth module it supports (You can find these default definitions in
"lib/modules/#{moduleName}/everyauth.js" -- e.g., see
.lib/modules/facebook/everyauth.js).
So for example, this is how you would over-ride the default findOrCreateUser step for the
facebook module if you are using both the facebook and password module:
…As this is a common recipe, I plan on adding support for this into everyauth and mongoose-auth, so it's more drop-in, and developers do not have to add this custom code themselves. The intent is for common things like this to be invisible to the developer, so it just works like magic. So, in the near future, you won't have to over-ride the findOrCreateUser step every time you want this feature. This will be coming soon.
By default, everyauth and therefore mongoose-auth use the attribute login as the default attribute used for logging in
with the password module.
However, the need can arise to use a different attribute (such as email) that implies a different schema (use email: String instead of login: String)
in addition to different validation assumptions (email validations are more strict that login handle validations).
Luckily, mongoose-auth provide support for this out of the box. All you need to do is (look for the line labeled "THIS NEXT LINE IS THE ONLY ADDITION"):
…Automatically, mongoose-auth will use an email String attribute in your User schema
instead of the default login String attribute. Moreover, it will automatically add in
validation checks to make sure that the email is valid before registering a user through
the registration process of the password module.
Sometimes your registration will ask for more information from the user besides the login and password.
For this particular scenario, you can configure extraParams.
…What this effectively does is:
phone, name.first, and name.last as attributes to your UserSchema.User document.
The registration form `` names should be, e.g., in the example above: 'phone',
'name[first]', and 'name[last]'.Please see ./example/server.js for a live example.
This one ha come up enough that it is here as a recipe, even though it is not specific to mongoose-auth. Suppose
you want to add a special attribute such as roles: [String] to your UserSchema. This is something that you can do
using just mongoose
var UserSchema = new mongoose.Schema({
roles: [String]
, // other custom attributes
});
UserSchema.plugin(mongooseAuth, {
// mongooseAuth *adds* other attributes to your UserSchema
// depending on the auth modules you choose.
});Currently, mongoose-auth does password authentication by login and password. Suppose you also want to authenticate
by checking against an additional parameter, like active, which is a Boolean attribute on your UserSchema that
indicates whether this user has been activated or not. Then you can modify the authenticate everyauth step in the
following way:
…This is a copy of instructions from everyauth and applied to mongoose-auth:
// ...
UserSchema.plugin(mongooseAuth, {
everymodule: {
everyauth: {
User: function () {
return User;
},
handleLogout: function(req, res) {
// Put your extra logic here
req.logout(); // The logout method is added for you by everyauth, too
// And/or put your extra logic here
res.writeHead(303, { 'Location': this.logoutRedirectPath() });
res.end();
}
}
}
// ...
});
// ...MIT License
Brian Noguchi
No open issues yet, or sync has not completed.