]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - 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
1const mongoose = require('mongoose')
2
3const customUsersValidators = require('../helpers/custom-validators').users
4const modelUtils = require('./utils')
5const peertubeCrypto = require('../helpers/peertube-crypto')
6
7// ---------------------------------------------------------------------------
8
9const UserSchema = mongoose.Schema({
10 createdDate: {
11 type: Date,
12 default: Date.now
13 },
14 password: String,
15 username: String,
16 role: String
17})
18
19UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
20UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
21UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
22
23UserSchema.methods = {
24 isPasswordMatch: isPasswordMatch,
25 toFormatedJSON: toFormatedJSON
26}
27
28UserSchema.statics = {
29 countTotal: countTotal,
30 getByUsername: getByUsername,
31 list: list,
32 listForApi: listForApi,
33 loadById: loadById,
34 loadByUsername: loadByUsername
35}
36
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
49mongoose.model('User', UserSchema)
50
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,
61 role: this.role,
62 createdDate: this.createdDate
63 }
64}
65// ------------------------------ STATICS ------------------------------
66
67function countTotal (callback) {
68 return this.count(callback)
69}
70
71function getByUsername (username) {
72 return this.findOne({ username: username })
73}
74
75function list (callback) {
76 return this.find(callback)
77}
78
79function listForApi (start, count, sort, callback) {
80 const query = {}
81 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
82}
83
84function loadById (id, callback) {
85 return this.findById(id, callback)
86}
87
88function loadByUsername (username, callback) {
89 return this.findOne({ username: username }, callback)
90}