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 const OAuthToken = mongoose.model('OAuthToken')
9 // ---------------------------------------------------------------------------
11 const UserSchema = mongoose.Schema({
21 UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
22 UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
23 UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
25 UserSchema.methods = {
30 UserSchema.statics = {
39 UserSchema.pre('save', function (next) {
42 peertubeCrypto.cryptPassword(this.password, function (err, hash) {
43 if (err) return next(err)
51 UserSchema.pre('remove', function (next) {
54 OAuthToken.removeByUserId(user._id, next)
57 mongoose.model('User', UserSchema)
59 // ------------------------------ METHODS ------------------------------
61 function isPasswordMatch (password, callback) {
62 return peertubeCrypto.comparePassword(password, this.password, callback)
65 function toFormatedJSON () {
68 username: this.username,
70 createdDate: this.createdDate
73 // ------------------------------ STATICS ------------------------------
75 function countTotal (callback) {
76 return this.count(callback)
79 function getByUsername (username) {
80 return this.findOne({ username: username })
83 function list (callback) {
84 return this.find(callback)
87 function listForApi (start, count, sort, callback) {
89 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
92 function loadById (id, callback) {
93 return this.findById(id, callback)
96 function loadByUsername (username, callback) {
97 return this.findOne({ username: username }, callback)