1 import { values } from 'lodash'
3 import { getSort } from './utils'
4 import { USER_ROLES } from '../initializers'
10 isUserDisplayNSFWValid
13 // ---------------------------------------------------------------------------
15 module.exports = function (sequelize, DataTypes) {
16 const User = sequelize.define('User',
19 type: DataTypes.STRING,
22 passwordValid: function (value) {
23 const res = isUserPasswordValid(value)
24 if (res === false) throw new Error('Password not valid.')
29 type: DataTypes.STRING,
32 usernameValid: function (value) {
33 const res = isUserUsernameValid(value)
34 if (res === false) throw new Error('Username not valid.')
39 type: DataTypes.STRING(400),
46 type: DataTypes.BOOLEAN,
50 nsfwValid: function (value) {
51 const res = isUserDisplayNSFWValid(value)
52 if (res === false) throw new Error('Display NSFW is not valid.')
57 type: DataTypes.ENUM(values(USER_ROLES)),
64 fields: [ 'username' ],
89 beforeCreate: beforeCreateOrUpdate,
90 beforeUpdate: beforeCreateOrUpdate
98 function beforeCreateOrUpdate (user, options, next) {
99 cryptPassword(user.password, function (err, hash) {
100 if (err) return next(err)
108 // ------------------------------ METHODS ------------------------------
110 function isPasswordMatch (password, callback) {
111 return comparePassword(password, this.password, callback)
114 function toFormatedJSON () {
117 username: this.username,
119 displayNSFW: this.displayNSFW,
121 createdAt: this.createdAt
125 function isAdmin () {
126 return this.role === USER_ROLES.ADMIN
129 // ------------------------------ STATICS ------------------------------
131 function associate (models) {
132 this.hasOne(models.Author, {
133 foreignKey: 'userId',
137 this.hasMany(models.OAuthToken, {
138 foreignKey: 'userId',
143 function countTotal (callback) {
144 return this.count().asCallback(callback)
147 function getByUsername (username) {
154 return this.findOne(query)
157 function list (callback) {
158 return this.find().asCallback(callback)
161 function listForApi (start, count, sort, callback) {
165 order: [ getSort(sort) ]
168 return this.findAndCountAll(query).asCallback(function (err, result) {
169 if (err) return callback(err)
171 return callback(null, result.rows, result.count)
175 function loadById (id, callback) {
176 return this.findById(id).asCallback(callback)
179 function loadByUsername (username, callback) {
186 return this.findOne(query).asCallback(callback)
189 function loadByUsernameOrEmail (username, email, callback) {
192 $or: [ { username }, { email } ]
196 return this.findOne(query).asCallback(callback)