]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/user.js
Add migration (for db, folders...) mechanism
[github/Chocobozzz/PeerTube.git] / server / models / user.js
1 const mongoose = require('mongoose')
2
3 const customUsersValidators = require('../helpers/custom-validators').users
4 const modelUtils = require('./utils')
5 const peertubeCrypto = require('../helpers/peertube-crypto')
6
7 // ---------------------------------------------------------------------------
8
9 const UserSchema = mongoose.Schema({
10 createdDate: {
11 type: Date,
12 default: Date.now
13 },
14 password: String,
15 username: String,
16 role: String
17 })
18
19 UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
20 UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
21 UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
22
23 UserSchema.methods = {
24 isPasswordMatch: isPasswordMatch,
25 toFormatedJSON: toFormatedJSON
26 }
27
28 UserSchema.statics = {
29 countTotal: countTotal,
30 getByUsername: getByUsername,
31 list: list,
32 listForApi: listForApi,
33 loadById: loadById,
34 loadByUsername: loadByUsername
35 }
36
37 UserSchema.pre('save', function (next) {
38 const user = this
39
40 peertubeCrypto.cryptPassword(this.password, function (err, hash) {
41 if (err) return next(err)
42
43 user.password = hash
44
45 return next()
46 })
47 })
48
49 mongoose.model('User', UserSchema)
50
51 // ------------------------------ METHODS ------------------------------
52
53 function isPasswordMatch (password, callback) {
54 return peertubeCrypto.comparePassword(password, this.password, callback)
55 }
56
57 function toFormatedJSON () {
58 return {
59 id: this._id,
60 username: this.username,
61 role: this.role,
62 createdDate: this.createdDate
63 }
64 }
65 // ------------------------------ STATICS ------------------------------
66
67 function countTotal (callback) {
68 return this.count(callback)
69 }
70
71 function getByUsername (username) {
72 return this.findOne({ username: username })
73 }
74
75 function list (callback) {
76 return this.find(callback)
77 }
78
79 function listForApi (start, count, sort, callback) {
80 const query = {}
81 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
82 }
83
84 function loadById (id, callback) {
85 return this.findById(id, callback)
86 }
87
88 function loadByUsername (username, callback) {
89 return this.findOne({ username: username }, callback)
90 }