Files
gancio/server/api/models/user.js

82 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-06-07 17:02:33 +02:00
'use strict'
2019-07-07 23:00:31 +02:00
const bcrypt = require('bcryptjs')
2019-07-29 14:10:18 +02:00
const crypto = require('crypto')
const util = require('util')
const debug = require('debug')('model:user')
2019-07-29 14:10:18 +02:00
const generateKeyPair = util.promisify(crypto.generateKeyPair)
2019-04-03 00:25:12 +02:00
2019-06-06 23:54:32 +02:00
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
2019-07-28 20:49:39 +02:00
username: {
type: DataTypes.STRING,
2019-09-05 14:41:40 +02:00
unique: { msg: 'error.nick_taken' },
2019-07-28 20:49:39 +02:00
index: true,
allowNull: false
},
display_name: DataTypes.STRING,
2019-10-30 15:01:15 +01:00
settings: {
type: DataTypes.JSON,
defaultValue: '{}'
},
2019-06-06 23:54:32 +02:00
email: {
type: DataTypes.STRING,
2019-09-11 19:12:24 +02:00
unique: { msg: 'error.email_taken' },
2019-06-06 23:54:32 +02:00
index: true,
allowNull: false
},
description: DataTypes.TEXT,
password: DataTypes.STRING,
recover_code: DataTypes.STRING,
is_admin: DataTypes.BOOLEAN,
2019-07-29 14:10:18 +02:00
is_active: DataTypes.BOOLEAN,
2019-10-28 17:33:20 +01:00
rsa: DataTypes.JSON
2019-06-07 17:02:33 +02:00
}, {
2019-06-08 15:16:56 +02:00
scopes: {
withoutPassword: {
attributes: { exclude: ['password', 'recover_code'] }
}
2019-06-07 17:02:33 +02:00
}
})
2019-04-03 00:25:12 +02:00
2019-06-07 17:02:33 +02:00
user.associate = function (models) {
2019-06-06 23:54:32 +02:00
// associations can be defined here
user.hasMany(models.event)
user.belongsToMany(models.fed_users, { through: 'user_followers', as: 'followers' })
2019-06-07 17:02:33 +02:00
}
2019-04-03 00:25:12 +02:00
2019-06-06 23:54:32 +02:00
user.prototype.comparePassword = async function (pwd) {
2019-09-11 19:12:24 +02:00
if (!this.password) { return false }
2019-06-06 23:54:32 +02:00
const ret = await bcrypt.compare(pwd, this.password)
return ret
2019-04-03 00:25:12 +02:00
}
2019-06-07 17:02:33 +02:00
2019-06-06 23:54:32 +02:00
user.beforeSave(async (user, options) => {
if (user.changed('password')) {
debug('Password for %s modified', user.username)
2019-06-06 23:54:32 +02:00
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(user.password, salt)
user.password = hash
}
})
2019-04-03 00:25:12 +02:00
2019-07-29 14:10:18 +02:00
user.beforeCreate(async (user, options) => {
debug('Create a new user => %s', user.username)
2019-07-29 14:10:18 +02:00
// generate rsa keys
const rsa = await generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
})
user.rsa = rsa
})
2019-06-07 17:02:33 +02:00
return user
2019-09-11 19:12:24 +02:00
}