river-of-ebooks/api/models/Passport.js

72 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-10-31 17:40:19 +00:00
const bcrypt = require('bcrypt')
async function hashPassword (passport) {
try {
var config = sails.config.auth.bcrypt
var salt = config.rounds
if (passport.password) {
const hash = await bcrypt.hash(passport.password, salt)
passport.password = hash
}
return passport
} catch (e) {
delete passport.password
sails.log.error(e)
throw e
}
}
/**
* Passport.js
*
* @description :: A model definition. Represents a database table/collection/etc.
* @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models
*/
module.exports = {
attributes: {
2018-10-31 18:54:58 +00:00
id: {
2018-10-31 21:05:27 +00:00
type: 'number',
2018-10-31 18:54:58 +00:00
unique: true,
2018-11-07 19:38:28 +00:00
autoIncrement: true
2018-10-31 18:54:58 +00:00
},
2018-10-31 17:40:19 +00:00
// local, oauth2, etc
protocol: {
type: 'string',
required: true
},
password: 'string',
2018-11-19 20:34:13 +00:00
accesstoken: 'string',
2018-10-31 17:40:19 +00:00
provider: 'string',
identifier: 'string',
tokens: 'json',
// User association
user: {
model: 'User',
required: true
}
},
/**
* callback run before creating a Passport
*/
2018-11-01 01:17:57 +00:00
beforeCreate: async function (passport, next) {
await hashPassword(passport)
return next()
2018-10-31 17:40:19 +00:00
},
/**
* callback run before updating
*/
2018-11-01 01:17:57 +00:00
beforeUpdate: async function (passport, next) {
await hashPassword(passport)
return next()
2018-10-31 18:54:58 +00:00
},
// methods
validatePassword: async function (password, passport) {
return bcrypt.compare(password, passport.password)
2018-10-31 17:40:19 +00:00
}
}