]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/user.js
Server: do not forget to check the signature when another pod wants to
[github/Chocobozzz/PeerTube.git] / server / models / user.js
CommitLineData
69b0a27c
C
1const mongoose = require('mongoose')
2
9bd26629 3const customUsersValidators = require('../helpers/custom-validators').users
5c39adb7 4const modelUtils = require('./utils')
26d7d31b 5const peertubeCrypto = require('../helpers/peertube-crypto')
9bd26629 6
69b0a27c
C
7// ---------------------------------------------------------------------------
8
9const UserSchema = mongoose.Schema({
5c39adb7
C
10 createdDate: {
11 type: Date,
12 default: Date.now
13 },
69b0a27c 14 password: String,
9bd26629
C
15 username: String,
16 role: String
69b0a27c
C
17})
18
9bd26629
C
19UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
20UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
21UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
22
23UserSchema.methods = {
26d7d31b 24 isPasswordMatch: isPasswordMatch,
9bd26629
C
25 toFormatedJSON: toFormatedJSON
26}
69b0a27c
C
27
28UserSchema.statics = {
5c39adb7 29 countTotal: countTotal,
26d7d31b 30 getByUsername: getByUsername,
00d6b0dd 31 list: list,
5c39adb7 32 listForApi: listForApi,
68a3b9f2 33 loadById: loadById,
9bd26629 34 loadByUsername: loadByUsername
69b0a27c
C
35}
36
26d7d31b
C
37UserSchema.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
69b0a27c
C
49mongoose.model('User', UserSchema)
50
26d7d31b
C
51// ------------------------------ METHODS ------------------------------
52
53function isPasswordMatch (password, callback) {
54 return peertubeCrypto.comparePassword(password, this.password, callback)
55}
56
57function toFormatedJSON () {
58 return {
59 id: this._id,
60 username: this.username,
d74a0680
C
61 role: this.role,
62 createdDate: this.createdDate
26d7d31b
C
63 }
64}
65// ------------------------------ STATICS ------------------------------
69b0a27c 66
5c39adb7 67function countTotal (callback) {
089ff2f2
C
68 return this.count(callback)
69}
70
26d7d31b
C
71function getByUsername (username) {
72 return this.findOne({ username: username })
9bd26629
C
73}
74
00d6b0dd
C
75function list (callback) {
76 return this.find(callback)
77}
78
5c39adb7
C
79function listForApi (start, count, sort, callback) {
80 const query = {}
81 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
69b0a27c
C
82}
83
68a3b9f2
C
84function loadById (id, callback) {
85 return this.findById(id, callback)
86}
87
9bd26629
C
88function loadByUsername (username, callback) {
89 return this.findOne({ username: username }, callback)
90}