aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/user.js
blob: c2c8807f0830da9452ea66c97231199115c7af41 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const mongoose = require('mongoose')

const customUsersValidators = require('../helpers/custom-validators').users
const modelUtils = require('./utils')
const peertubeCrypto = require('../helpers/peertube-crypto')

// ---------------------------------------------------------------------------

const UserSchema = mongoose.Schema({
  createdDate: {
    type: Date,
    default: Date.now
  },
  password: String,
  username: String,
  role: String
})

UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)

UserSchema.methods = {
  isPasswordMatch: isPasswordMatch,
  toFormatedJSON: toFormatedJSON
}

UserSchema.statics = {
  countTotal: countTotal,
  getByUsername: getByUsername,
  list: list,
  listForApi: listForApi,
  loadById: loadById,
  loadByUsername: loadByUsername
}

UserSchema.pre('save', function (next) {
  const user = this

  peertubeCrypto.cryptPassword(this.password, function (err, hash) {
    if (err) return next(err)

    user.password = hash

    return next()
  })
})

mongoose.model('User', UserSchema)

// ------------------------------ METHODS ------------------------------

function isPasswordMatch (password, callback) {
  return peertubeCrypto.comparePassword(password, this.password, callback)
}

function toFormatedJSON () {
  return {
    id: this._id,
    username: this.username,
    role: this.role,
    createdDate: this.createdDate
  }
}
// ------------------------------ STATICS ------------------------------

function countTotal (callback) {
  return this.count(callback)
}

function getByUsername (username) {
  return this.findOne({ username: username })
}

function list (callback) {
  return this.find(callback)
}

function listForApi (start, count, sort, callback) {
  const query = {}
  return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
}

function loadById (id, callback) {
  return this.findById(id, callback)
}

function loadByUsername (username, callback) {
  return this.findOne({ username: username }, callback)
}