]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/models/user.js
Server: Remove unused console log
[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
7const OAuthToken = mongoose.model('OAuthToken')
8
9// ---------------------------------------------------------------------------
10
11const UserSchema = mongoose.Schema({
12 createdDate: {
13 type: Date,
14 default: Date.now
15 },
16 password: String,
17 username: String,
18 role: String
19})
20
21UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
22UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
23UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
24
25UserSchema.methods = {
26 isPasswordMatch,
27 toFormatedJSON
28}
29
30UserSchema.statics = {
31 countTotal,
32 getByUsername,
33 list,
34 listForApi,
35 loadById,
36 loadByUsername
37}
38
39UserSchema.pre('save', function (next) {
40 const user = this
41
42 peertubeCrypto.cryptPassword(this.password, function (err, hash) {
43 if (err) return next(err)
44
45 user.password = hash
46
47 return next()
48 })
49})
50
51UserSchema.pre('remove', function (next) {
52 const user = this
53
54 OAuthToken.removeByUserId(user._id, next)
55})
56
57mongoose.model('User', UserSchema)
58
59// ------------------------------ METHODS ------------------------------
60
61function isPasswordMatch (password, callback) {
62 return peertubeCrypto.comparePassword(password, this.password, callback)
63}
64
65function toFormatedJSON () {
66 return {
67 id: this._id,
68 username: this.username,
69 role: this.role,
70 createdDate: this.createdDate
71 }
72}
73// ------------------------------ STATICS ------------------------------
74
75function countTotal (callback) {
76 return this.count(callback)
77}
78
79function getByUsername (username) {
80 return this.findOne({ username: username })
81}
82
83function list (callback) {
84 return this.find(callback)
85}
86
87function listForApi (start, count, sort, callback) {
88 const query = {}
89 return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
90}
91
92function loadById (id, callback) {
93 return this.findById(id, callback)
94}
95
96function loadByUsername (username, callback) {
97 return this.findOne({ username: username }, callback)
98}