]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/user.js
Server: show user created date for the api
[github/Chocobozzz/PeerTube.git] / server / models / user.js
index d289da19af804615ee1f075409a5fa760c2189ea..db6f1765b66ddf56ef54b0676c276c48b2455c2c 100644 (file)
@@ -1,10 +1,16 @@
 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
@@ -15,31 +21,59 @@ UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
 UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
 
 UserSchema.methods = {
+  isPasswordMatch: isPasswordMatch,
   toFormatedJSON: toFormatedJSON
 }
 
 UserSchema.statics = {
-  count: count,
-  getByUsernameAndPassword: getByUsernameAndPassword,
-  list: list,
+  countTotal: countTotal,
+  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,
+    createdDate: this.createdDate
+  }
+}
+// ------------------------------ STATICS ------------------------------
 
-function count (callback) {
+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) {
+  const query = {}
+  return modelUtils.listForApiWithCount.call(this, query, start, count, sort, callback)
 }
 
 function loadById (id, callback) {
@@ -49,11 +83,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
-  }
-}