]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/user.js
e76aab2ce5ad25d1459b90c9a7423cce8acef7d7
[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 listForApi: listForApi,
32 loadById: loadById,
33 loadByUsername: loadByUsername
34 }
35
36 UserSchema.pre('save', function (next) {
37 const user = this
38
39 peertubeCrypto.cryptPassword(this.password, function (err, hash) {
40 if (err) return next(err)
41
42 user.password = hash
43
44 return next()
45 })
46 })
47
48 mongoose.model('User', UserSchema)
49
50 // ------------------------------ METHODS ------------------------------
51
52 function isPasswordMatch (password, callback) {
53 return peertubeCrypto.comparePassword(password, this.password, callback)
54 }
55
56 function toFormatedJSON () {
57 return {
58 id: this._id,
59 username: this.username,
60 role: this.role
61 }
62 }
63 // ------------------------------ STATICS ------------------------------
64
65 function countTotal (callback) {
66 return this.count(callback)
67 }
68
69 function getByUsername (username) {
70 return this.findOne({ username: username })
71 }
72
73 function listForApi (start, count, sort, callback) {
74 const query = {}
75 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
76 }
77
78 function loadById (id, callback) {
79 return this.findById(id, callback)
80 }
81
82 function loadByUsername (username, callback) {
83 return this.findOne({ username: username }, callback)
84 }