3 const values = require('lodash/values')
5 const modelUtils = require('./utils')
6 const constants = require('../initializers/constants')
7 const peertubeCrypto = require('../helpers/peertube-crypto')
8 const customUsersValidators = require('../helpers/custom-validators').users
10 // ---------------------------------------------------------------------------
12 module.exports = function (sequelize, DataTypes) {
13 const User = sequelize.define('User',
16 type: DataTypes.STRING,
19 passwordValid: function (value) {
20 const res = customUsersValidators.isUserPasswordValid(value)
21 if (res === false) throw new Error('Password not valid.')
26 type: DataTypes.STRING,
29 usernameValid: function (value) {
30 const res = customUsersValidators.isUserUsernameValid(value)
31 if (res === false) throw new Error('Username not valid.')
36 type: DataTypes.STRING(400),
43 type: DataTypes.BOOLEAN,
47 nsfwValid: function (value) {
48 const res = customUsersValidators.isUserDisplayNSFWValid(value)
49 if (res === false) throw new Error('Display NSFW is not valid.')
54 type: DataTypes.ENUM(values(constants.USER_ROLES)),
61 fields: [ 'username' ],
85 beforeCreate: beforeCreateOrUpdate,
86 beforeUpdate: beforeCreateOrUpdate
94 function beforeCreateOrUpdate (user, options, next) {
95 peertubeCrypto.cryptPassword(user.password, function (err, hash) {
96 if (err) return next(err)
104 // ------------------------------ METHODS ------------------------------
106 function isPasswordMatch (password, callback) {
107 return peertubeCrypto.comparePassword(password, this.password, callback)
110 function toFormatedJSON () {
113 username: this.username,
115 displayNSFW: this.displayNSFW,
117 createdAt: this.createdAt
120 // ------------------------------ STATICS ------------------------------
122 function associate (models) {
123 this.hasOne(models.Author, {
124 foreignKey: 'userId',
128 this.hasMany(models.OAuthToken, {
129 foreignKey: 'userId',
134 function countTotal (callback) {
135 return this.count().asCallback(callback)
138 function getByUsername (username) {
145 return this.findOne(query)
148 function list (callback) {
149 return this.find().asCallback(callback)
152 function listForApi (start, count, sort, callback) {
156 order: [ modelUtils.getSort(sort) ]
159 return this.findAndCountAll(query).asCallback(function (err, result) {
160 if (err) return callback(err)
162 return callback(null, result.rows, result.count)
166 function loadById (id, callback) {
167 return this.findById(id).asCallback(callback)
170 function loadByUsername (username, callback) {
177 return this.findOne(query).asCallback(callback)
180 function loadByUsernameOrEmail (username, email, callback) {
183 $or: [ { username }, { email } ]
187 return this.findOne(query).asCallback(callback)