Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.