From 26d7d31ba3b1d26ea9a51e8626e4a4537867db94 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 25 Aug 2016 17:57:37 +0200 Subject: Server: encrypt password in database --- server/models/user.js | 43 +++++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) (limited to 'server/models/user.js') diff --git a/server/models/user.js b/server/models/user.js index c9c35b3e2..e76aab2ce 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -2,6 +2,7 @@ const mongoose = require('mongoose') const customUsersValidators = require('../helpers/custom-validators').users const modelUtils = require('./utils') +const peertubeCrypto = require('../helpers/peertube-crypto') // --------------------------------------------------------------------------- @@ -20,27 +21,53 @@ UserSchema.path('username').required(customUsersValidators.isUserUsernameValid) UserSchema.path('role').validate(customUsersValidators.isUserRoleValid) UserSchema.methods = { + isPasswordMatch: isPasswordMatch, toFormatedJSON: toFormatedJSON } UserSchema.statics = { countTotal: countTotal, - getByUsernameAndPassword: getByUsernameAndPassword, + getByUsername: getByUsername, 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 + } +} +// ------------------------------ 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 listForApi (start, count, sort, callback) { @@ -55,11 +82,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 - } -} -- cgit v1.2.3