X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fmodels%2Fuser.js;h=a19de7072cd77ae5e881297e775f25c829ab45aa;hb=55723d16fd0e323ce7175db8c4806c73d18b895d;hp=c9c35b3e2dffc0c06cbe6d35f379135998aae583;hpb=5c39adb7313e0696aabb4b71196ab7b0b378c359;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/models/user.js b/server/models/user.js index c9c35b3e2..a19de7072 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -2,6 +2,9 @@ const mongoose = require('mongoose') const customUsersValidators = require('../helpers/custom-validators').users const modelUtils = require('./utils') +const peertubeCrypto = require('../helpers/peertube-crypto') + +const OAuthToken = mongoose.model('OAuthToken') // --------------------------------------------------------------------------- @@ -20,27 +23,65 @@ UserSchema.path('username').required(customUsersValidators.isUserUsernameValid) UserSchema.path('role').validate(customUsersValidators.isUserRoleValid) UserSchema.methods = { - toFormatedJSON: toFormatedJSON + isPasswordMatch, + toFormatedJSON } UserSchema.statics = { - countTotal: countTotal, - getByUsernameAndPassword: getByUsernameAndPassword, - listForApi: listForApi, - loadById: loadById, - loadByUsername: loadByUsername + countTotal, + getByUsername, + list, + listForApi, + loadById, + 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() + }) +}) + +UserSchema.pre('remove', function (next) { + const user = this + + OAuthToken.removeByUserId(user._id, 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 getByUsernameAndPassword (username, password) { - return this.findOne({ username: username, password: password }) +function getByUsername (username) { + return this.findOne({ username: username }) +} + +function list (callback) { + return this.find(callback) } function listForApi (start, count, sort, callback) { @@ -55,11 +96,3 @@ function loadById (id, callback) { function loadByUsername (username, callback) { return this.findOne({ username: username }, callback) } - -function toFormatedJSON () { - return { - id: this._id, - username: this.username, - role: this.role - } -}