PeerTube/server/models/user.js

85 lines
2.0 KiB
JavaScript
Raw Normal View History

const mongoose = require('mongoose')
const customUsersValidators = require('../helpers/custom-validators').users
2016-08-16 22:31:45 +02:00
const modelUtils = require('./utils')
2016-08-25 17:57:37 +02:00
const peertubeCrypto = require('../helpers/peertube-crypto')
// ---------------------------------------------------------------------------
const UserSchema = mongoose.Schema({
2016-08-16 22:31:45 +02:00
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 = {
2016-08-25 17:57:37 +02:00
isPasswordMatch: isPasswordMatch,
toFormatedJSON: toFormatedJSON
}
UserSchema.statics = {
2016-08-16 22:31:45 +02:00
countTotal: countTotal,
2016-08-25 17:57:37 +02:00
getByUsername: getByUsername,
2016-08-16 22:31:45 +02:00
listForApi: listForApi,
loadById: loadById,
loadByUsername: loadByUsername
}
2016-08-25 17:57:37 +02:00
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)
2016-08-25 17:57:37 +02:00
// ------------------------------ METHODS ------------------------------
function isPasswordMatch (password, callback) {
return peertubeCrypto.comparePassword(password, this.password, callback)
}
function toFormatedJSON () {
return {
id: this._id,
username: this.username,
role: this.role
}
}
// ------------------------------ STATICS ------------------------------
2016-08-16 22:31:45 +02:00
function countTotal (callback) {
return this.count(callback)
}
2016-08-25 17:57:37 +02:00
function getByUsername (username) {
return this.findOne({ username: username })
}
2016-08-16 22:31:45 +02:00
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)
}