From dda76f1da46143d6bc017651caa64ba63c6b64a0 Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Fri, 29 Nov 2019 16:27:11 +0100
Subject: [PATCH] FEAT #11645 TIME 0:45 Send notification when user un delete
 account

---
 src/app/user/controllers/UserController.php   | 38 ++++++-------------
 src/app/user/models/UserModelAbstract.php     | 36 ++++++++----------
 .../controllers/AuthenticationController.php  | 22 +++++++++++
 src/core/models/AuthenticationModel.php       | 13 +++++++
 .../user/user-administration.component.ts     |  5 ++-
 5 files changed, 66 insertions(+), 48 deletions(-)

diff --git a/src/app/user/controllers/UserController.php b/src/app/user/controllers/UserController.php
index 2d61a3c789d..1c7be8b7d0a 100755
--- a/src/app/user/controllers/UserController.php
+++ b/src/app/user/controllers/UserController.php
@@ -156,18 +156,24 @@ class UserController
             return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
         }
 
-        $existingUser = UserModel::getByLowerLogin(['login' => $data['userId'], 'select' => ['id', 'status']]);
+        $loggingMethod = CoreConfigModel::getLoggingMethod();
+        $existingUser = UserModel::getByLowerLogin(['login' => $data['userId'], 'select' => ['id', 'status', 'mail']]);
 
         if (!empty($existingUser) && $existingUser['status'] == 'DEL') {
             UserModel::update([
                 'set'   => [
-                    'status'   => 'OK'
+                    'status'    => 'OK',
+                    'password'  => AuthenticationModel::getPasswordHash(AuthenticationModel::generatePassword()),
                 ],
                 'where' => ['id = ?'],
                 'data'  => [$existingUser['id']]
             ]);
 
-            return $response->withJson(['user' => $existingUser]);
+            if ($loggingMethod['id'] == 'standard') {
+                AuthenticationController::sendUserCreationNotification(['userId' => $existingUser['id'], 'userEmail' => $existingUser['mail']]);
+            }
+
+            return $response->withJson(['id' => $existingUser['id']]);
         } elseif (!empty($existingUser)) {
             return $response->withStatus(400)->withJson(['errors' => _USER_ID_ALREADY_EXISTS]);
         }
@@ -181,12 +187,7 @@ class UserController
             $data['loginmode'] = 'standard';
         }
 
-        UserModel::create(['user' => $data]);
-
-        $newUser = UserModel::getByLogin(['login' => $data['userId']]);
-        if (!Validator::intType()->notEmpty()->validate($newUser['id'])) {
-            return $response->withStatus(500)->withJson(['errors' => 'User Creation Error']);
-        }
+        $id = UserModel::create(['user' => $data]);
 
         $userQuota = ParameterModel::getById(['id' => 'user_quota', 'select' => ['param_value_int']]);
         if (!empty($userQuota['param_value_int'])) {
@@ -196,23 +197,8 @@ class UserController
             }
         }
 
-        $loggingMethod = CoreConfigModel::getLoggingMethod();
         if ($loggingMethod['id'] == 'standard') {
-            $resetToken = AuthenticationController::getResetJWT(['id' => $newUser['id'], 'expirationTime' => 1209600]); // 14 days
-            UserModel::update(['set' => ['reset_token' => $resetToken], 'where' => ['id = ?'], 'data' => [$newUser['id']]]);
-
-            $url = UrlController::getCoreUrl() . 'apps/maarch_entreprise/index.php?display=true&page=login&update-password-token=' . $resetToken;
-            EmailController::createEmail([
-                'userId'    => $newUser['id'],
-                'data'      => [
-                    'sender'        => ['email' => 'Notification'],
-                    'recipients'    => [$newUser['mail']],
-                    'object'        => _NOTIFICATIONS_USER_CREATION_SUBJECT,
-                    'body'          => _NOTIFICATIONS_USER_CREATION_BODY . '<a href="' . $url . '">'._CLICK_HERE.'</a>' . _NOTIFICATIONS_USER_CREATION_FOOTER,
-                    'isHtml'        => true,
-                    'status'        => 'WAITING'
-                ]
-            ]);
+            AuthenticationController::sendUserCreationNotification(['userId' => $id, 'userEmail' => $data['mail']]);
         }
 
         HistoryController::add([
@@ -223,7 +209,7 @@ class UserController
             'info'         => _USER_CREATED . " {$data['userId']}"
         ]);
 
-        return $response->withJson(['user' => $newUser]);
+        return $response->withJson(['id' => $id]);
     }
 
     public function update(Request $request, Response $response, array $aArgs)
diff --git a/src/app/user/models/UserModelAbstract.php b/src/app/user/models/UserModelAbstract.php
index 28faec35d37..d8954670a7a 100755
--- a/src/app/user/models/UserModelAbstract.php
+++ b/src/app/user/models/UserModelAbstract.php
@@ -77,37 +77,33 @@ abstract class UserModelAbstract
         return $aUser[0];
     }
 
-    public static function create(array $aArgs)
+    public static function create(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['user']);
-        ValidatorModel::notEmpty($aArgs['user'], ['userId', 'firstname', 'lastname']);
-        ValidatorModel::stringType($aArgs['user'], ['userId', 'firstname', 'lastname', 'mail', 'initials', 'phone', 'loginmode']);
-
-        $length = rand(50, 70);
-        $chars = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz!@$%^*_=+,.?';
-        $count = mb_strlen($chars);
-        for ($i = 0, $password = ''; $i < $length; $i++) {
-            $index = rand(0, $count - 1);
-            $password .= mb_substr($chars, $index, 1);
-        }
+        ValidatorModel::notEmpty($args, ['user']);
+        ValidatorModel::notEmpty($args['user'], ['userId', 'firstname', 'lastname']);
+        ValidatorModel::stringType($args['user'], ['userId', 'firstname', 'lastname', 'mail', 'initials', 'phone', 'loginmode']);
+
+        $password = AuthenticationModel::generatePassword();
+        $nextSequenceId = DatabaseModel::getNextSequenceValue(['sequenceId' => 'users_id_seq']);
 
         DatabaseModel::insert([
             'table'         => 'users',
             'columnsValues' => [
-                'user_id'                       => strtolower($aArgs['user']['userId']),
-                'firstname'                     => $aArgs['user']['firstname'],
-                'lastname'                      => $aArgs['user']['lastname'],
-                'mail'                          => $aArgs['user']['mail'],
-                'phone'                         => $aArgs['user']['phone'],
-                'initials'                      => $aArgs['user']['initials'],
+                'id'                            => $nextSequenceId,
+                'user_id'                       => strtolower($args['user']['userId']),
+                'firstname'                     => $args['user']['firstname'],
+                'lastname'                      => $args['user']['lastname'],
+                'mail'                          => $args['user']['mail'],
+                'phone'                         => $args['user']['phone'],
+                'initials'                      => $args['user']['initials'],
                 'status'                        => 'OK',
-                'loginmode'                     => empty($aArgs['user']['loginmode']) ? 'standard' : $aArgs['user']['loginmode'],
+                'loginmode'                     => empty($args['user']['loginmode']) ? 'standard' : $args['user']['loginmode'],
                 'password'                      => AuthenticationModel::getPasswordHash($password),
                 'password_modification_date'    => 'CURRENT_TIMESTAMP'
             ]
         ]);
 
-        return true;
+        return $nextSequenceId;
     }
 
     public static function update(array $aArgs)
diff --git a/src/core/controllers/AuthenticationController.php b/src/core/controllers/AuthenticationController.php
index 91f4a2acb2a..cf9dfbbe0f4 100755
--- a/src/core/controllers/AuthenticationController.php
+++ b/src/core/controllers/AuthenticationController.php
@@ -14,6 +14,7 @@
 
 namespace SrcCore\controllers;
 
+use Email\controllers\EmailController;
 use Firebase\JWT\JWT;
 use SrcCore\models\AuthenticationModel;
 use SrcCore\models\CoreConfigModel;
@@ -139,4 +140,25 @@ class AuthenticationController
 
         return $jwt;
     }
+
+    public static function sendUserCreationNotification(array $args)
+    {
+        $resetToken = AuthenticationController::getResetJWT(['id' => $args['userId'], 'expirationTime' => 1209600]); // 14 days
+        UserModel::update(['set' => ['reset_token' => $resetToken], 'where' => ['id = ?'], 'data' => [$args['userId']]]);
+
+        $url = UrlController::getCoreUrl() . 'apps/maarch_entreprise/index.php?display=true&page=login&update-password-token=' . $resetToken;
+        EmailController::createEmail([
+            'userId'    => $args['userId'],
+            'data'      => [
+                'sender'        => ['email' => 'Notification'],
+                'recipients'    => [$args['userEmail']],
+                'object'        => _NOTIFICATIONS_USER_CREATION_SUBJECT,
+                'body'          => _NOTIFICATIONS_USER_CREATION_BODY . '<a href="' . $url . '">'._CLICK_HERE.'</a>' . _NOTIFICATIONS_USER_CREATION_FOOTER,
+                'isHtml'        => true,
+                'status'        => 'WAITING'
+            ]
+        ]);
+
+        return true;
+    }
 }
diff --git a/src/core/models/AuthenticationModel.php b/src/core/models/AuthenticationModel.php
index 5418f61db47..d9a50c6ea58 100755
--- a/src/core/models/AuthenticationModel.php
+++ b/src/core/models/AuthenticationModel.php
@@ -179,4 +179,17 @@ class AuthenticationModel
 
         return true;
     }
+
+    public static function generatePassword()
+    {
+        $length = rand(50, 70);
+        $chars = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz!@$%^*_=+,.?';
+        $count = mb_strlen($chars);
+        for ($i = 0, $password = ''; $i < $length; $i++) {
+            $index = rand(0, $count - 1);
+            $password .= mb_substr($chars, $index, 1);
+        }
+
+        return $password;
+    }
 }
diff --git a/src/frontend/app/administration/user/user-administration.component.ts b/src/frontend/app/administration/user/user-administration.component.ts
index f396aa38d3d..a6e043297b8 100755
--- a/src/frontend/app/administration/user/user-administration.component.ts
+++ b/src/frontend/app/administration/user/user-administration.component.ts
@@ -865,12 +865,13 @@ export class UserAdministrationComponent implements OnInit {
                                 } else {
                                     this.notify.success(this.lang.userAdded);
                                 }
-                                this.router.navigate(["/administration/users/" + data.user.id]);
+                                this.router.navigate(["/administration/users/" + data.id]);
                             }, (err: any) => {
                                 this.notify.error(err.error.errors);
                             });
                     }
-                }, () => {
+                }, (err: any) => {
+                    this.notify.error(err.error.errors);
                 });
         } else {
             this.http.put("../../rest/users/" + this.serialId, this.user)
-- 
GitLab