1 const mongoose = require('mongoose')
3 const customUsersValidators = require('../helpers/custom-validators').users
4 const modelUtils = require('./utils')
5 const peertubeCrypto = require('../helpers/peertube-crypto')
7 // ---------------------------------------------------------------------------
9 const UserSchema = mongoose.Schema({
19 UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
20 UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
21 UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
23 UserSchema.methods = {
24 isPasswordMatch: isPasswordMatch,
25 toFormatedJSON: toFormatedJSON
28 UserSchema.statics = {
29 countTotal: countTotal,
30 getByUsername: getByUsername,
32 listForApi: listForApi,
34 loadByUsername: loadByUsername
37 UserSchema.pre('save', function (next) {
40 peertubeCrypto.cryptPassword(this.password, function (err, hash) {
41 if (err) return next(err)
49 mongoose.model('User', UserSchema)
51 // ------------------------------ METHODS ------------------------------
53 function isPasswordMatch (password, callback) {
54 return peertubeCrypto.comparePassword(password, this.password, callback)
57 function toFormatedJSON () {
60 username: this.username,
62 createdDate: this.createdDate
65 // ------------------------------ STATICS ------------------------------
67 function countTotal (callback) {
68 return this.count(callback)
71 function getByUsername (username) {
72 return this.findOne({ username: username })
75 function list (callback) {
76 return this.find(callback)
79 function listForApi (start, count, sort, callback) {
81 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
84 function loadById (id, callback) {
85 return this.findById(id, callback)
88 function loadByUsername (username, callback) {
89 return this.findOne({ username: username }, callback)