Skip to content

Instantly share code, notes, and snippets.

@kriswill
Created February 3, 2015 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kriswill/579649135ed7168835fc to your computer and use it in GitHub Desktop.
Save kriswill/579649135ed7168835fc to your computer and use it in GitHub Desktop.
Passport model
/**
* Passport Model
*
* The Passport model handles associating authenticators with users. An authen-
* ticator can be either local (password) or third-party (provider). A single
* user can have multiple passports, allowing them to connect and use several
* third-party strategies in optional conjunction with a password.
*/
var bcrypt = require('bcrypt')
module.exports = {
schema: true,
beforeCreate: function(passport, next) {
passport.id = require('node-uuid').v1() // RFC4122 v1, timestamp encoded
hashPassword(passport, next)
},
beforeUpdate: hashPassword,
attributes: {
id: {
type: 'string', // uuid v1
primaryKey: true,
unique: true
},
// Required field: Protocol
//
// Defines the protocol to use for the passport. When employing the local
// strategy, the protocol will be set to 'local'. When using a third-party
// strategy, the protocol will be set to the standard used by the third-
// party service (e.g. 'oauth', 'oauth2', 'openid').
protocol: {
type: 'alphanumeric',
required: true
},
password: {
type: 'string',
minLength: 8
},
// Provider fields: Provider, identifer and tokens
//
// "provider" is the name of the third-party auth service in all lowercase
// (e.g. 'github', 'facebook') whereas "identifier" is a provider-specific
// key, typically an ID. These two fields are used as the main means of
// identifying a passport and tying it to a local user.
//
// The "tokens" field is a JSON object used in the case of the OAuth stan-
// dards. When using OAuth 1.0, a `token` as well as a `tokenSecret` will
// be issued by the provider. In the case of OAuth 2.0, an `accessToken`
// and a `refreshToken` will be issued.
provider: {
type: 'alphanumericdashed'
},
identifier: {
type: 'string'
},
tokens: {
type: 'json'
},
//
// Associations
//
user: {
model: 'User'
columnName: 'user_id',
required: true
},
//
// Methods
//
validatePassword: function(password, next) {
bcrypt.compare(password, this.password, next)
}
}
}
function hashPassword(passport, next) {
if (passport.hasOwnProperty('password')) {
var rounds = 10 // https://github.com/ncb000gt/node.bcrypt.js/blob/master/README.md#a-note-on-rounds
bcrypt.genSalt(rounds, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
if (err) {
sails.log.error(err)
next(err, passport)
} else {
passport.password = hash
next(null, passport)
}
})
})
} else {
next(null, passport)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment