From 787b56ea168da392e6fbb414b5789bcde0000378 Mon Sep 17 00:00:00 2001 From: aksinha Date: Wed, 15 Feb 2017 20:11:19 +0530 Subject: [PATCH 01/10] Username and Password regex added --- src/ApiBundle/Controller/AuthController.php | 14 +++++++++++--- src/ApiBundle/Resources/config/config.yml | 7 +++++++ .../Resources/translations/messages.en.yml | 3 ++- .../Resources/translations/messages.fr.yml | 2 ++ .../Resources/translations/messages.hi.yml | 2 ++ 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/ApiBundle/Controller/AuthController.php b/src/ApiBundle/Controller/AuthController.php index 1784e3b..6437cab 100644 --- a/src/ApiBundle/Controller/AuthController.php +++ b/src/ApiBundle/Controller/AuthController.php @@ -216,8 +216,8 @@ private function validateAdminUser(Request $request) { * parameters={ * {"name"="client_id", "dataType"="string", "required"=true, "description"="oAuth ClientId"}, * {"name"="client_secret", "dataType"="string", "required"=true, "description"="oAuth ClientSecret"}, - * {"name"="username", "dataType"="string", "required"=true, "description"="username"}, - * {"name"="password", "dataType"="string", "required"=true, "description"="password"}, + * {"name"="username", "dataType"="string", "required"=true, "description"="Username should be 3-16 characters long with any lowercase letter (a-z), number (0-9), an underscore, or a hyphen"}, + * {"name"="password", "dataType"="string", "required"=true, "description"="Password should be 8-15 characters long and must contain alphanumeric and @*# characters"}, * {"name"="firstname", "dataType"="string", "required"=true, "description"="firstname"}, * {"name"="lastname", "dataType"="string", "required"=true, "description"="lastname"}, * {"name"="dob", "dataType"="datetime", "required"=true, "description"="date of birth mm/dd/yyyy"}, @@ -314,6 +314,10 @@ private function validateUsername(Request $request) { if (null != $user) { $this->logAndThrowError(400, 'User already exists. Username: '.$user->getUsername(), $this->get('translator')->trans('api.show_error_username_taken', array(), 'messages', $request->getLocale()), $request->getLocale()); } + + if ( preg_match($this->container->getParameter('username_regex'), $username ) == false ) { + $this->logAndThrowError(400, 'Username should be 3-16 characters long with any lowercase letter (a-z), number (0-9), an underscore, or a hyphen.', $this->get('translator')->trans('api.show_error_username_policy', array(), 'messages', $request->getLocale()), $request->getLocale()); + } } /** @@ -326,6 +330,10 @@ private function validatePassword(Request $request) { if (null == $password) { $this->logAndThrowError(400, 'Invalid empty password', $this->get('translator')->trans('api.show_error_password', array(), 'messages', $request->getLocale()), $request->getLocale()); } + + if ( preg_match($this->container->getParameter('password_regex'), $password ) == false ) { + $this->logAndThrowError(400, 'Password should be 8-15 characters long and must contain alphanumeric and @*# characters.', $this->get('translator')->trans('api.show_error_password_policy', array(), 'messages', $request->getLocale()), $request->getLocale()); + } } /** @@ -382,7 +390,7 @@ private function validateDob(Request $request) { * description="Change password of the user. Access token to be provided in header (Authorization = Bearer )", * parameters={ * {"name"="old_password", "dataType"="string", "required"=true, "description"="Old password"}, - * {"name"="password", "dataType"="string", "required"=true, "description"="New password"}, + * {"name"="password", "dataType"="string", "required"=true, "description"="Password should be 8-15 characters long and must contain alphanumeric and @*# characters"}, * {"name"="_locale", "dataType"="string", "required"=false, "description"="User locale. Will default to en"} * }, * ) diff --git a/src/ApiBundle/Resources/config/config.yml b/src/ApiBundle/Resources/config/config.yml index 730e784..03e1af0 100644 --- a/src/ApiBundle/Resources/config/config.yml +++ b/src/ApiBundle/Resources/config/config.yml @@ -3,6 +3,13 @@ parameters: # app_locales: en|fr|de|es|cs|nl|ru|uk|ro|pt_BR|pl|it|ja|id|ca|sl app_locales: en|fr|hi + # Password matching expression. Match all alphanumeric character and predefined wild characters. + # Password must consists of at least 8 characters and not more than 15 characters. + password_regex: '/^([a-zA-Z0-9@*#]{8,15})$/' + + # username at least 3 of those characters, but no more than 16, any lowercase letter (a-z), number (0-9), an underscore, or a hyphen + username_regex: '/^[a-z0-9_-]{3,16}$/' + # Assetic Configuration assetic: debug: '%kernel.debug%' diff --git a/src/ApiBundle/Resources/translations/messages.en.yml b/src/ApiBundle/Resources/translations/messages.en.yml index cbfde4e..9cd2d42 100644 --- a/src/ApiBundle/Resources/translations/messages.en.yml +++ b/src/ApiBundle/Resources/translations/messages.en.yml @@ -143,4 +143,5 @@ api: show_error_perm_edit: Sorry, You are not permitted to edit user profile! show_error_password_reset: Sorry, You are not permitted to request for password reset! show_error_reset_req: Password reset request already received - show_error_server_fault: Server Error! Please try again after some time!! + show_error_username_policy: Username should be 3-16 characters long with any lowercase letter (a-z), number (0-9), an underscore, or a hyphen + show_error_password_policy: Password should be 8-15 characters long and must contain alphanumeric and @*# characters diff --git a/src/ApiBundle/Resources/translations/messages.fr.yml b/src/ApiBundle/Resources/translations/messages.fr.yml index 6f59d65..e10746b 100644 --- a/src/ApiBundle/Resources/translations/messages.fr.yml +++ b/src/ApiBundle/Resources/translations/messages.fr.yml @@ -132,3 +132,5 @@ api: show_error_password_reset: Désolé, vous n'êtes pas autorisé à demander une réinitialisation du mot de passe! show_error_reset_req: Réinitialisation du mot de passe déjà reçue show_error_server_fault: Erreur du serveur! Veuillez réessayer après un certain temps !! + show_error_username_policy: Le nom d'utilisateur doit comporter entre 3 et 16 caractères avec une lettre minuscule (a-z), un chiffre (0-9), un trait de soulignement ou un tiret + show_error_password_policy: Le mot de passe doit comporter entre 8 et 15 caractères et contenir des caractères alphanumériques et @*# diff --git a/src/ApiBundle/Resources/translations/messages.hi.yml b/src/ApiBundle/Resources/translations/messages.hi.yml index 2146420..62626c9 100644 --- a/src/ApiBundle/Resources/translations/messages.hi.yml +++ b/src/ApiBundle/Resources/translations/messages.hi.yml @@ -132,3 +132,5 @@ api: show_error_password_reset: क्षमा करें, आप पासवर्ड रीसेट के लिए अनुरोध करने के लिए अनुमति नहीं है! show_error_reset_req: पासवर्ड रीसेट अनुरोध पहले से ही प्राप्त show_error_server_fault: सर्वर त्रुटि! कुछ समय के बाद फिर से कोशिश करें !! + show_error_username_policy: यूजर का नाम किसी भी छोटा अक्षर (a-z), संख्या (0-9), एक अंडरस्कोर, या एक हाइफन के साथ 3-16 अक्षर का होना चाहिए + show_error_password_policy: पासवर्ड 8-15 अक्षर का होना चाहिए और अल्फान्यूमेरिक और शामिल होना चाहिए @#* अक्षर From 89ba0d05b4c4fdeba28209cb3ffee0d3aed094a1 Mon Sep 17 00:00:00 2001 From: aksinha Date: Thu, 16 Feb 2017 19:14:32 +0530 Subject: [PATCH 02/10] Symfony validation added and custom validations removed from UserController.php. Language files added for validation error messages. --- .../Controller/Admin/UserController.php | 111 ------------------ src/ApiBundle/Entity/User.php | 3 - src/ApiBundle/Resources/config/validation.yml | 37 ++++++ .../Resources/translations/validators.en.yml | 24 ++++ .../Resources/translations/validators.fr.yml | 24 ++++ .../Resources/translations/validators.hi.yml | 24 ++++ 6 files changed, 109 insertions(+), 114 deletions(-) create mode 100644 src/ApiBundle/Resources/config/validation.yml create mode 100644 src/ApiBundle/Resources/translations/validators.en.yml create mode 100644 src/ApiBundle/Resources/translations/validators.fr.yml create mode 100644 src/ApiBundle/Resources/translations/validators.hi.yml diff --git a/src/ApiBundle/Controller/Admin/UserController.php b/src/ApiBundle/Controller/Admin/UserController.php index a20b52f..adbe88e 100644 --- a/src/ApiBundle/Controller/Admin/UserController.php +++ b/src/ApiBundle/Controller/Admin/UserController.php @@ -57,14 +57,6 @@ public function newAction(Request $request) if ($form->isSubmitted() && $form->isValid()) { try { - $this->validateUsername($form, $locale, new User()); - $this->validatePassword($form, $locale); - $this->validateEmail($form, $locale, new User()); - $this->validateFirstname($form, $locale); - $this->validateDob($form, $locale); - $this->validateRoles($form, $locale); - - // Everything ok, now proceed to create the user $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->createUser(); @@ -84,7 +76,6 @@ public function newAction(Request $request) $this->addFlash('success', $flashMsg); } catch(HttpException $e) { - // Error messages for this section will come from above validate methods return $this->redirectToRoute('admin_user_new'); // Always catch exact exception for which flash message or logger is needed, @@ -138,13 +129,6 @@ public function editAction(User $user, Request $request) if ($editForm->isSubmitted() && $editForm->isValid()) { try { - $this->validateUsername($editForm, $locale, $user); - $this->validatePassword($editForm, $locale); - $this->validateEmail($editForm, $locale, $user); - $this->validateFirstname($editForm, $locale); - $this->validateDob($editForm, $locale); - $this->validateRoles($editForm, $locale); - $user->setFirstname($editForm['firstname']->getData()); $user->setLastname($editForm['lastname']->getData()); $user->setDob($editForm['dob']->getData()); @@ -163,7 +147,6 @@ public function editAction(User $user, Request $request) // Always catch exact exception for which flash message or logger is needed, // otherwise catch block will not get executed on higher or lower ranked exceptions. } catch(HttpException $e) { - // Error messages for this section will come from above validate methods return $this->redirectToRoute('admin_user_edit', ['id' => $user->getId()]); } catch(\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) { $flashMsg = $this->get('translator')->trans('flash.user_already_exists'); @@ -182,100 +165,6 @@ public function editAction(User $user, Request $request) ]); } - /** - * Validate username - */ - private function validateUsername(\Symfony\Component\Form\Form $form, $locale, User $user) { - $username = $form['username']->getData(); - - // Check if username is empty - if (null == $username) { - $this->logMessageAndFlash(400, 'danger', 'Empty username', $this->get('translator')->trans('api.show_error_username_missing', array(), 'messages', $locale), $locale); - } - - // If the username belongs to same user, no need to further check - if (!($user->getUsername() == $username)) { - // Do a check for existing user with userManager->findByUsername - /** @var $user UserInterface */ - $user = $this->container->get('fos_user.user_manager')->findUserByUsernameOrEmail($username); - if (null != $user) { - $this->logMessageAndFlash(400, 'danger', 'User already exists. Username: '.$user->getUsername(), $this->get('translator')->trans('api.show_error_username_taken', array(), 'messages', $locale), $locale); - } - } - } - - /** - * Validate password - */ - private function validatePassword(\Symfony\Component\Form\Form $form, $locale) { - $password = $form['password']->getData(); - - // Check if password is empty - if (null == $password) { - $this->logMessageAndFlash(400, 'danger', 'Invalid empty password', $this->get('translator')->trans('api.show_error_password', array(), 'messages', $locale), $locale); - } - } - - /** - * Validate email - */ - private function validateEmail(\Symfony\Component\Form\Form $form, $locale, User $user) { - $email = $form['email']->getData(); - - // Check if email is valid - if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { - $this->logMessageAndFlash(400, 'danger', 'Invalid email: '.$email, $this->get('translator')->trans('api.show_error_email', array(), 'messages', $locale), $locale); - } - - // If the email belongs to same user, no need to further check - if (!($user->getEmail() == $email )) { - $user = $this->container->get('fos_user.user_manager')->findUserByUsernameOrEmail($email); - if (null != $user) { - $this->logMessageAndFlash(400, 'danger', 'Email '.$user->getEmail().' already taken by Username: '.$user->getUsername(), $this->get('translator')->trans('api.show_error_email_taken', array(), 'messages', $locale), $locale); - } - } - } - - /** - * Validate firstname - */ - private function validateFirstname(\Symfony\Component\Form\Form $form, $locale) { - $firstname = $form['firstname']->getData(); - - // Check if firstname is empty. At least firstname is required. - if (null == $firstname) { - $this->logMessageAndFlash(400, 'danger', 'Invalid empty firstname', $this->get('translator')->trans('api.show_error_firstname', array(), 'messages', $locale), $locale); - } - - } - - /** - * Validate dob - */ - private function validateDob(\Symfony\Component\Form\Form $form, $locale) { - $dob = $form['dob']->getData(); - - // Check if dob is valid - list($mm,$dd,$yyyy) = explode('/', $dob->format('m/d/Y') ); - if (!checkdate($mm,$dd,$yyyy)) { - $this->logMessageAndFlash(400, 'danger', 'Invalid mm/dd/yyyy DOB: '.$dob, $this->get('translator')->trans('api.show_error_dob', array(), 'messages', $locale), $locale); - } - } - - /** - * Validate roles - */ - private function validateRoles(\Symfony\Component\Form\Form $form, $locale) { - $roles = $form['roles']->getData(); - $permittedRoles = ['ROLE_API', "ROLE_USER"]; - - foreach ($roles as $role) { - // Check if role is valid - if (!in_array($role, $permittedRoles) ) - $this->logMessageAndFlash(400, 'warning', 'Invalid role: '.$role, $this->get('translator')->trans('api.show_error_role'.' '.$role, array(), 'messages', $locale), $locale); - } - } - /** * Deletes a User entity. * diff --git a/src/ApiBundle/Entity/User.php b/src/ApiBundle/Entity/User.php index 9adfc8c..f9fd4f2 100644 --- a/src/ApiBundle/Entity/User.php +++ b/src/ApiBundle/Entity/User.php @@ -5,15 +5,12 @@ use FOS\UserBundle\Entity\User as BaseUser; use Doctrine\ORM\Mapping as ORM; -use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * User * * @ORM\Table("users") * @ORM\Entity - * @UniqueEntity("username") - * @UniqueEntity("email") */ class User extends BaseUser { diff --git a/src/ApiBundle/Resources/config/validation.yml b/src/ApiBundle/Resources/config/validation.yml new file mode 100644 index 0000000..019d3f2 --- /dev/null +++ b/src/ApiBundle/Resources/config/validation.yml @@ -0,0 +1,37 @@ +# src/ApiBundle/Resources/config/validation.yml +ApiBundle\Entity\User: + constraints: + - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: + fields: username + message: "user.show_error_username_taken" + - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: + fields: email + message: "user.show_error_email_taken" + properties: + firstname: + - NotBlank: + message: "user.show_error_firstname" + username: + - Regex: + pattern: '/^[a-z0-9_-]{3,16}$/' + match: true + message: "user.show_error_username_policy" + password: + - Regex: + pattern: '/^([a-zA-Z0-9@*#]{8,15})$/' + match: true + message: "user.show_error_password_policy" + email: + - Email: + message: "user.show_error_email" + checkMX: false + dob: + - Date: + message: "user.show_error_dob" + roles: + - Type: + type: array + message: The value {{ value }} is not a valid {{ type }}. + - Choice: + choices: ['ROLE_USER', 'ROLE_API'] + message: "user.show_error_role" diff --git a/src/ApiBundle/Resources/translations/validators.en.yml b/src/ApiBundle/Resources/translations/validators.en.yml new file mode 100644 index 0000000..36726a3 --- /dev/null +++ b/src/ApiBundle/Resources/translations/validators.en.yml @@ -0,0 +1,24 @@ +client: + show_error_client_name: Sorry, Client Name cannot be empty! + show_error_url: Sorry, Redirect URL cannot be empty! + show_error_non_admin: Sorry, you are not an Admin! +user: + show_error_password: Sorry, Wrong/Missing Password! + show_error_username_missing: Sorry, Wrong/Missing Username! + show_error_credentials: Sorry, Invalid Client Credentials! + show_error_username_empty: Sorry, Empty Username! + show_error_username_taken: Sorry, Username already taken! + show_error_email: Sorry, Wrong/Missing Email! + show_error_email_taken: Sorry, Email already taken! + show_error_dob: Sorry, Invalid date of birth! + show_error_scope: Sorry, Invalid scope! + show_error_firstname: Sorry, Firstname cannot be empty! + show_error_password_change: Sorry, You are not allowed to change password! + show_error_password_old: Sorry, Invalid old password! + show_error_perm_show: Sorry, You are not permitted to view user profile! + show_error_perm_edit: Sorry, You are not permitted to edit user profile! + show_error_password_reset: Sorry, You are not permitted to request for password reset! + show_error_reset_req: Password reset request already received + show_error_username_policy: Username should be 3-16 characters long with any lowercase letter (a-z), number (0-9), an underscore, or a hyphen + show_error_password_policy: Password should be 8-15 characters long and must contain alphanumeric and @*# characters + show_error_role: Sorry! Not a valid Role! diff --git a/src/ApiBundle/Resources/translations/validators.fr.yml b/src/ApiBundle/Resources/translations/validators.fr.yml new file mode 100644 index 0000000..745ffae --- /dev/null +++ b/src/ApiBundle/Resources/translations/validators.fr.yml @@ -0,0 +1,24 @@ +client: + show_error_client_name: Désolé, le nom du client ne peut pas être vide! + show_error_url: Désolé, l'URL de redirection ne peut pas être vide! + show_error_non_admin: Désolé, vous n'êtes pas Admin! +user: + show_error_password: Désolé, mot de passe erroné / manquant! + show_error_username_missing: Désolé, Nom d'utilisateur erroné / manquant! + show_error_credentials: Désolé, Invalid Client Credentials! + show_error_username_empty: Désolé, Nom d'utilisateur vide! + show_error_username_taken: Désolé, Nom d'utilisateur déjà pris! + show_error_email: Désolé, E-mail erroné / manquant! + show_error_email_taken: Désolé, Courriel déjà pris! + show_error_dob: Désolé, date de naissance non valide! + show_error_scope: Désolé, champ non valide! + show_error_firstname: Désolé, le prénom ne peut pas être vide! + show_error_password_change: Désolé, Vous n'êtes pas autorisé à changer de mot de passe! + show_error_password_old: Désolé, ancien mot de passe invalide! + show_error_perm_show: Désolé, Vous n'êtes pas autorisé à voir le profil! + show_error_perm_edit: Désolé, Vous n'êtes pas autorisé à modifier le profil de l'utilisateur! + show_error_password_reset: Désolé, vous n'êtes pas autorisé à demander une réinitialisation du mot de passe! + show_error_reset_req: Réinitialisation du mot de passe déjà reçue + show_error_server_fault: Erreur du serveur! Veuillez réessayer après un certain temps !! + show_error_username_policy: Le nom d'utilisateur doit comporter entre 3 et 16 caractères avec une lettre minuscule (a-z), un chiffre (0-9), un trait de soulignement ou un tiret + show_error_password_policy: Le mot de passe doit comporter entre 8 et 15 caractères et contenir des caractères alphanumériques et @*# diff --git a/src/ApiBundle/Resources/translations/validators.hi.yml b/src/ApiBundle/Resources/translations/validators.hi.yml new file mode 100644 index 0000000..cf03775 --- /dev/null +++ b/src/ApiBundle/Resources/translations/validators.hi.yml @@ -0,0 +1,24 @@ +client: + show_error_client_name: क्षमा करें, क्लाइंट का नाम रिक्त नहीं हो सकता! + show_error_url: क्षमा करें, पुनर्निर्देशन यूआरएल खाली नहीं हो सकता! + show_error_non_admin: क्षमा करें, आप एक व्यवस्थापक नहीं हैं! +user: + show_error_password: माफ करना, गलत / लापता पासवर्ड! + show_error_username_missing: माफ करना, गलत / लापता यूजर का नाम! + show_error_credentials: क्षमा करें, हमारे ग्राहकों का अवैध साख! + show_error_username_empty: क्षमा करें, खाली यूजर का नाम! + show_error_username_taken: क्षमा करें, प्रयोक्ता नाम पहले ही ले लिया! + show_error_email: माफ करना, गलत / लापता ईमेल + show_error_email_taken: क्षमा करें, ईमेल पहले ही ले लिया! + show_error_dob: क्षमा करें, जन्म की तारीख गलत! + show_error_scope: क्षमा करें, अमान्य दायरा! + show_error_firstname: क्षमा करें, प्रथम खाली नहीं हो सकता! + show_error_password_change: क्षमा करें, आप पासवर्ड बदलने की अनुमति नहीं कर रहे हैं! + show_error_password_old: क्षमा करें, अमान्य पुराने पासवर्ड के लिए! + show_error_perm_show: क्षमा करें, आप उपयोगकर्ता प्रोफ़ाइल देखने के लिए अनुमति नहीं है! + show_error_perm_edit: क्षमा करें, आप उपयोगकर्ता के प्रोफ़ाइल को संपादित करने की अनुमति नहीं है! + show_error_password_reset: क्षमा करें, आप पासवर्ड रीसेट के लिए अनुरोध करने के लिए अनुमति नहीं है! + show_error_reset_req: पासवर्ड रीसेट अनुरोध पहले से ही प्राप्त + show_error_server_fault: सर्वर त्रुटि! कुछ समय के बाद फिर से कोशिश करें !! + show_error_username_policy: यूजर का नाम किसी भी छोटा अक्षर (a-z), संख्या (0-9), एक अंडरस्कोर, या एक हाइफन के साथ 3-16 अक्षर का होना चाहिए + show_error_password_policy: पासवर्ड 8-15 अक्षर का होना चाहिए और अल्फान्यूमेरिक और शामिल होना चाहिए @#* अक्षर From 983309149b1669076094ab716a966908b4b4ae13 Mon Sep 17 00:00:00 2001 From: Amarendra Date: Fri, 17 Feb 2017 11:19:52 +0530 Subject: [PATCH 03/10] Symfony validation added to AuthController --- src/ApiBundle/Controller/AuthController.php | 225 ++++-------------- src/ApiBundle/Resources/config/validation.yml | 22 +- .../Resources/translations/messages.en.yml | 1 + .../Resources/translations/messages.fr.yml | 1 + .../Resources/translations/messages.hi.yml | 1 + 5 files changed, 65 insertions(+), 185 deletions(-) diff --git a/src/ApiBundle/Controller/AuthController.php b/src/ApiBundle/Controller/AuthController.php index 6437cab..fb3d752 100644 --- a/src/ApiBundle/Controller/AuthController.php +++ b/src/ApiBundle/Controller/AuthController.php @@ -232,13 +232,6 @@ public function postRegisterAction() $request = $this->container->get('request'); $userManager = $this->get('fos_user.user_manager'); - $this->validateClient($request); - $this->validateUsername($request); - $this->validatePassword($request); - $this->validateEmail($request); - $this->validateFirstname($request); - $this->validateDob($request); - $user = $userManager->createUser(); $user->setUsername($request->request->get('username')); @@ -250,6 +243,26 @@ public function postRegisterAction() $user->setRoles(array('ROLE_API')); $user->setEnabled(true); + // Validate user data + $validator = $this->get('validator'); + $errors = $validator->validate($user); + + if (count($errors) > 0) { + $errorArray = []; + foreach ($errors as $error) { + $constraint = $error->getConstraint(); + $errorItem = array( + "code" => 400, + "error" => "Bad Request", + "error_description" => $error->getMessage(), + "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) + ); + array_push($errorArray, $errorItem); + } + return new JsonResponse($errorArray); + } + + // Everything ok, now write the user record $userManager->updateUser($user); $oAuthRtn = 'Pending'; @@ -297,88 +310,6 @@ private function validateClient(Request $request) { } } - /** - * Validate username - */ - private function validateUsername(Request $request) { - $username = $request->request->get('username'); - - // Check if username is empty - if (null == $username) { - $this->logAndThrowError(400, 'Empty username', $this->get('translator')->trans('api.show_error_username_missing', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - - // Do a check for existing user with userManager->findByUsername - /** @var $user UserInterface */ - $user = $this->container->get('fos_user.user_manager')->findUserByUsernameOrEmail($username); - if (null != $user) { - $this->logAndThrowError(400, 'User already exists. Username: '.$user->getUsername(), $this->get('translator')->trans('api.show_error_username_taken', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - - if ( preg_match($this->container->getParameter('username_regex'), $username ) == false ) { - $this->logAndThrowError(400, 'Username should be 3-16 characters long with any lowercase letter (a-z), number (0-9), an underscore, or a hyphen.', $this->get('translator')->trans('api.show_error_username_policy', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - } - - /** - * Validate password - */ - private function validatePassword(Request $request) { - $password = $request->request->get('password'); - - // Check if password is empty - if (null == $password) { - $this->logAndThrowError(400, 'Invalid empty password', $this->get('translator')->trans('api.show_error_password', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - - if ( preg_match($this->container->getParameter('password_regex'), $password ) == false ) { - $this->logAndThrowError(400, 'Password should be 8-15 characters long and must contain alphanumeric and @*# characters.', $this->get('translator')->trans('api.show_error_password_policy', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - } - - /** - * Validate email - */ - private function validateEmail(Request $request) { - $email = $request->request->get('email'); - - // Check if email is valid - if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { - $this->logAndThrowError(400, 'Invalid email: '.$email, $this->get('translator')->trans('api.show_error_email', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - - $user = $this->container->get('fos_user.user_manager')->findUserByUsernameOrEmail($email); - if (null != $user) { - $this->logAndThrowError(400, 'Email '.$user->getEmail().' already taken by Username: '.$user->getUsername(), $this->get('translator')->trans('api.show_error_email_taken', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - } - - /** - * Validate firstname - */ - private function validateFirstname(Request $request) { - $firstname = $request->request->get('firstname'); - - // Check if firstname is empty. At least firstname is required. - if (null == $firstname) { - $this->logAndThrowError(400, 'Invalid empty firstname', $this->get('translator')->trans('api.show_error_firstname', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - - } - - /** - * Validate dob - */ - private function validateDob(Request $request) { - $dob = $request->request->get('dob'); - - // Check if dob is valid - list($mm,$dd,$yyyy) = explode('/',$dob); - if (!checkdate($mm,$dd,$yyyy)) { - $this->logAndThrowError(400, 'Invalid mm/dd/yyyy DOB: '.$dob, $this->get('translator')->trans('api.show_error_dob', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - } - /** * Change Password request. Will return a JsonResponse(username, msg) upon success. * @@ -489,11 +420,9 @@ public function getProfileAction() * resource=true, * description="Update User profile detail. Access token to be provided in header (Authorization = Bearer )", * parameters={ - * {"name"="username", "dataType"="string", "required"=true, "description"="username, leave null if unchanged"}, * {"name"="firstname", "dataType"="string", "required"=true, "description"="firstname, leave null if unchanged"}, * {"name"="lastname", "dataType"="string", "required"=true, "description"="lastname, leave null if unchanged"}, * {"name"="dob", "dataType"="datetime", "required"=true, "description"="date of birth mm/dd/yyyy, leave null if unchanged"}, - * {"name"="email", "dataType"="email", "required"=true, "description"="Email, leave null if unchanged"}, * {"name"="_locale", "dataType"="string", "required"=false, "description"="User locale. Will default to en"} * }, * ) @@ -511,12 +440,30 @@ public function editProfileAction() $data = $request->request->all(); - $this->handleKeyUsername($user, $request); - $this->handleKeyEmail($user, $request); - $this->handleKeyFirstname($user, $request); - $this->handleKeyLastname($user, $request); - $this->handleKeyDob($user, $request); + $user->setFirstname(array_key_exists('firstname', $data) ? $data['firstname'] : $user->getFirstname() ); + $user->setLastname(array_key_exists('lastname', $data) ? $data['lastname'] : $user->getLastname() ); + $user->setDob( array_key_exists('dob', $data) ? $data['dob'] : $user->getDob() ); + + // Validate user data + $validator = $this->get('validator'); + $errors = $validator->validate($user, null, array('profile_edit')); + + if (count($errors) > 0) { + $errorArray = []; + foreach ($errors as $error) { + $constraint = $error->getConstraint(); + $errorItem = array( + "code" => 400, + "error" => "Bad Request", + "error_description" => $error->getMessage(), + "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) + ); + array_push($errorArray, $errorItem); + } + return new JsonResponse($errorArray); + } + // Everything ok, now update the user record $userManager->updateUser($user); $msg = 'Profile changed successfully'; @@ -531,92 +478,6 @@ public function editProfileAction() )); } - /** - * Checks $request if it contains a key - username - */ - private function handleKeyUsername(UserInterface $user, Request $request) { - $data = $request->request->all(); - - if (array_key_exists('username', $data)) { - // Change username only if username is changed - if ($data['username'] != $user->getUsername()) { - // Check if username is already taken - $user1 = $this->container->get('fos_user.user_manager')->findUserByUsernameOrEmail($data['username']); - if (null != $user1) { - $this->logAndThrowError(400, 'Already taken by Username: '.$user1->getUsername(), $this->get('translator')->trans('api.show_error_username_taken', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - $user->setUsername($data['username']); - } - } - } - - /** - * Checks $request if it contains a key - email - */ - private function handleKeyEmail(UserInterface $user, Request $request) { - $data = $request->request->all(); - - if (array_key_exists('email', $data)) { - // Check if email is valid - if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { - $this->logAndThrowError(400, 'Invalid email: '.$data['email'], 'Invalid email: '.$data['email']); - } - // Update email only if email is changed - if ($data['email'] != $user->getEmail()) { - // Check if email is already taken - $user1 = $this->container->get('fos_user.user_manager')->findUserByUsernameOrEmail($data['email']); - if (null != $user1) { - $this->logAndThrowError(400, 'Email ' .$user1->getEmail().' already taken by Username: '.$user1->getUsername(), $this->get('translator')->trans('api.show_error_email_taken', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - $user->setEmail($data['email']); - } - } - } - - /** - * Checks $request if it contains a key - firstname - */ - private function handleKeyFirstname(UserInterface $user, Request $request) { - $data = $request->request->all(); - - if (array_key_exists('firstname', $data)) { - // Check if firstname is empty. At least firstname is required. - if (null == $data['firstname']) { - $this->logAndThrowError(400, 'Invalid empty firstname', $this->get('translator')->trans('api.show_error_firstname', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - $user->setFirstname($data['firstname']); - } - - } - - /** - * Checks $request if it contains a key - lastname - */ - private function handleKeyLastname(UserInterface $user, Request $request) { - $data = $request->request->all(); - - if (array_key_exists('lastname', $data)) { - $user->setLastname($data['lastname']); - } - } - - /** - * Checks $request if it contains a key - dob - */ - private function handleKeyDob(UserInterface $user, Request $request) { - $data = $request->request->all(); - - if (array_key_exists('dob', $data)) { - // Check if dob is valid - list($mm,$dd,$yyyy) = array_merge( explode('/',$data['dob']), array(0,0,0) ); - if (!checkdate($mm,$dd,$yyyy)) { - $this->logAndThrowError(400, 'Invalid mm/dd/yyyy DOB: '.$data['dob'], $this->get('translator')->trans('api.show_error_dob', array(), 'messages', $request->getLocale()), $request->getLocale()); - } - $user->setDob($data['dob']); - } - - } - /** * Request reset user password. A mail will be sent, if not sent earlier else will return error msg. * diff --git a/src/ApiBundle/Resources/config/validation.yml b/src/ApiBundle/Resources/config/validation.yml index 019d3f2..957e986 100644 --- a/src/ApiBundle/Resources/config/validation.yml +++ b/src/ApiBundle/Resources/config/validation.yml @@ -4,34 +4,50 @@ ApiBundle\Entity\User: - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: fields: username message: "user.show_error_username_taken" + payload: + api_error: 'api.show_error_username_taken' - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: fields: email message: "user.show_error_email_taken" + payload: + api_error: 'api.show_error_email_taken' properties: firstname: - NotBlank: + groups: [profile_edit] message: "user.show_error_firstname" + payload: + api_error: 'api.show_error_firstname' username: - Regex: pattern: '/^[a-z0-9_-]{3,16}$/' match: true message: "user.show_error_username_policy" + payload: + api_error: 'api.show_error_username_policy' password: - Regex: pattern: '/^([a-zA-Z0-9@*#]{8,15})$/' match: true message: "user.show_error_password_policy" + payload: + api_error: 'api.show_error_password_policy' email: - Email: message: "user.show_error_email" checkMX: false + payload: + api_error: 'api.show_error_email' dob: - Date: + groups: [profile_edit] message: "user.show_error_dob" + payload: + api_error: 'api.show_error_dob' roles: - - Type: - type: array - message: The value {{ value }} is not a valid {{ type }}. - Choice: choices: ['ROLE_USER', 'ROLE_API'] + multiple: true message: "user.show_error_role" + payload: + api_error: 'api.show_error_role' diff --git a/src/ApiBundle/Resources/translations/messages.en.yml b/src/ApiBundle/Resources/translations/messages.en.yml index 9cd2d42..c9be419 100644 --- a/src/ApiBundle/Resources/translations/messages.en.yml +++ b/src/ApiBundle/Resources/translations/messages.en.yml @@ -145,3 +145,4 @@ api: show_error_reset_req: Password reset request already received show_error_username_policy: Username should be 3-16 characters long with any lowercase letter (a-z), number (0-9), an underscore, or a hyphen show_error_password_policy: Password should be 8-15 characters long and must contain alphanumeric and @*# characters + show_error_role: Sorry! Wrong Role! diff --git a/src/ApiBundle/Resources/translations/messages.fr.yml b/src/ApiBundle/Resources/translations/messages.fr.yml index e10746b..cf2c111 100644 --- a/src/ApiBundle/Resources/translations/messages.fr.yml +++ b/src/ApiBundle/Resources/translations/messages.fr.yml @@ -134,3 +134,4 @@ api: show_error_server_fault: Erreur du serveur! Veuillez réessayer après un certain temps !! show_error_username_policy: Le nom d'utilisateur doit comporter entre 3 et 16 caractères avec une lettre minuscule (a-z), un chiffre (0-9), un trait de soulignement ou un tiret show_error_password_policy: Le mot de passe doit comporter entre 8 et 15 caractères et contenir des caractères alphanumériques et @*# + show_error_role: Pardon! Mauvais rôle! diff --git a/src/ApiBundle/Resources/translations/messages.hi.yml b/src/ApiBundle/Resources/translations/messages.hi.yml index 62626c9..24d8fbd 100644 --- a/src/ApiBundle/Resources/translations/messages.hi.yml +++ b/src/ApiBundle/Resources/translations/messages.hi.yml @@ -134,3 +134,4 @@ api: show_error_server_fault: सर्वर त्रुटि! कुछ समय के बाद फिर से कोशिश करें !! show_error_username_policy: यूजर का नाम किसी भी छोटा अक्षर (a-z), संख्या (0-9), एक अंडरस्कोर, या एक हाइफन के साथ 3-16 अक्षर का होना चाहिए show_error_password_policy: पासवर्ड 8-15 अक्षर का होना चाहिए और अल्फान्यूमेरिक और शामिल होना चाहिए @#* अक्षर + show_error_role: माफ़ कीजिये! गलत भूमिका! From eb40e2251e823c8d74db5b391a652a503c889256 Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 13:08:17 +0530 Subject: [PATCH 04/10] Changes per feedback --- src/ApiBundle/Controller/AuthController.php | 28 +++++++++++++-------- src/ApiBundle/Resources/config/config.yml | 7 ------ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/src/ApiBundle/Controller/AuthController.php b/src/ApiBundle/Controller/AuthController.php index fb3d752..1a105f9 100644 --- a/src/ApiBundle/Controller/AuthController.php +++ b/src/ApiBundle/Controller/AuthController.php @@ -252,14 +252,15 @@ public function postRegisterAction() foreach ($errors as $error) { $constraint = $error->getConstraint(); $errorItem = array( - "code" => 400, - "error" => "Bad Request", "error_description" => $error->getMessage(), "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) ); array_push($errorArray, $errorItem); } - return new JsonResponse($errorArray); + return new JsonResponse(array( + "code" => 400, + "error" => "Bad Request", + 'errors' => $errorArray)); } // Everything ok, now write the user record @@ -436,13 +437,16 @@ public function editProfileAction() $this->logAndThrowError(400, 'Invalid User', $this->get('translator')->trans('api.show_error_perm_edit', array(), 'messages', $request->getLocale()), $request->getLocale()); } - $userManager = $this->get('fos_user.user_manager'); - $data = $request->request->all(); - $user->setFirstname(array_key_exists('firstname', $data) ? $data['firstname'] : $user->getFirstname() ); - $user->setLastname(array_key_exists('lastname', $data) ? $data['lastname'] : $user->getLastname() ); - $user->setDob( array_key_exists('dob', $data) ? $data['dob'] : $user->getDob() ); + $firstname = array_key_exists('firstname', $data) ? $data['firstname'] : $user->getFirstname(); + $user->setFirstname($firstname); + + $lastname = array_key_exists('lastname', $data) ? $data['lastname'] : $user->getLastname(); + $user->setLastname($lastname); + + $dob = array_key_exists('dob', $data) ? $data['dob'] : $user->getDob(); + $user->setDob($dob); // Validate user data $validator = $this->get('validator'); @@ -453,17 +457,19 @@ public function editProfileAction() foreach ($errors as $error) { $constraint = $error->getConstraint(); $errorItem = array( - "code" => 400, - "error" => "Bad Request", "error_description" => $error->getMessage(), "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) ); array_push($errorArray, $errorItem); } - return new JsonResponse($errorArray); + return new JsonResponse(array( + "code" => 400, + "error" => "Bad Request", + 'errors' => $errorArray)); } // Everything ok, now update the user record + $userManager = $this->get('fos_user.user_manager'); $userManager->updateUser($user); $msg = 'Profile changed successfully'; diff --git a/src/ApiBundle/Resources/config/config.yml b/src/ApiBundle/Resources/config/config.yml index 03e1af0..730e784 100644 --- a/src/ApiBundle/Resources/config/config.yml +++ b/src/ApiBundle/Resources/config/config.yml @@ -3,13 +3,6 @@ parameters: # app_locales: en|fr|de|es|cs|nl|ru|uk|ro|pt_BR|pl|it|ja|id|ca|sl app_locales: en|fr|hi - # Password matching expression. Match all alphanumeric character and predefined wild characters. - # Password must consists of at least 8 characters and not more than 15 characters. - password_regex: '/^([a-zA-Z0-9@*#]{8,15})$/' - - # username at least 3 of those characters, but no more than 16, any lowercase letter (a-z), number (0-9), an underscore, or a hyphen - username_regex: '/^[a-z0-9_-]{3,16}$/' - # Assetic Configuration assetic: debug: '%kernel.debug%' From d38264d2abd1d2441f963e212ac00d07248bbccc Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 13:29:18 +0530 Subject: [PATCH 05/10] Changes per feedback --- src/ApiBundle/Controller/AuthController.php | 24 ++++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/ApiBundle/Controller/AuthController.php b/src/ApiBundle/Controller/AuthController.php index 1a105f9..bf69a43 100644 --- a/src/ApiBundle/Controller/AuthController.php +++ b/src/ApiBundle/Controller/AuthController.php @@ -252,15 +252,19 @@ public function postRegisterAction() foreach ($errors as $error) { $constraint = $error->getConstraint(); $errorItem = array( - "error_description" => $error->getMessage(), + "error_description" => $error->getPropertyPath().': '.$error->getMessage().' '.$error->getInvalidValue(), "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) ); array_push($errorArray, $errorItem); + $this->logMessage(400, $errorItem['error_description'] ); } return new JsonResponse(array( - "code" => 400, - "error" => "Bad Request", - 'errors' => $errorArray)); + "code" => 400, + "error" => "Bad Request", + "error_description" => $errorArray[0]['error_description'], + "show_message" => $errorArray[0]['show_message'], + 'errors' => $errorArray + )); } // Everything ok, now write the user record @@ -457,15 +461,19 @@ public function editProfileAction() foreach ($errors as $error) { $constraint = $error->getConstraint(); $errorItem = array( - "error_description" => $error->getMessage(), + "error_description" => $error->getPropertyPath().': '.$error->getMessage().' '.$error->getInvalidValue(), "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) ); array_push($errorArray, $errorItem); + $this->logMessage(400, $errorItem['error_description'] ); } return new JsonResponse(array( - "code" => 400, - "error" => "Bad Request", - 'errors' => $errorArray)); + "code" => 400, + "error" => "Bad Request", + "error_description" => $errorArray[0]['error_description'], + "show_message" => $errorArray[0]['show_message'], + 'errors' => $errorArray + )); } // Everything ok, now update the user record From c1ff549d8f3f28d3faed7a250be420e3bef5de6f Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 13:49:55 +0530 Subject: [PATCH 06/10] Changes per feedback --- src/ApiBundle/Controller/AuthController.php | 59 +++++++++------------ 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/src/ApiBundle/Controller/AuthController.php b/src/ApiBundle/Controller/AuthController.php index bf69a43..075a197 100644 --- a/src/ApiBundle/Controller/AuthController.php +++ b/src/ApiBundle/Controller/AuthController.php @@ -248,23 +248,7 @@ public function postRegisterAction() $errors = $validator->validate($user); if (count($errors) > 0) { - $errorArray = []; - foreach ($errors as $error) { - $constraint = $error->getConstraint(); - $errorItem = array( - "error_description" => $error->getPropertyPath().': '.$error->getMessage().' '.$error->getInvalidValue(), - "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) - ); - array_push($errorArray, $errorItem); - $this->logMessage(400, $errorItem['error_description'] ); - } - return new JsonResponse(array( - "code" => 400, - "error" => "Bad Request", - "error_description" => $errorArray[0]['error_description'], - "show_message" => $errorArray[0]['show_message'], - 'errors' => $errorArray - )); + return $this->reportValidationErrors($request, $errors); } // Everything ok, now write the user record @@ -457,24 +441,8 @@ public function editProfileAction() $errors = $validator->validate($user, null, array('profile_edit')); if (count($errors) > 0) { - $errorArray = []; - foreach ($errors as $error) { - $constraint = $error->getConstraint(); - $errorItem = array( - "error_description" => $error->getPropertyPath().': '.$error->getMessage().' '.$error->getInvalidValue(), - "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) - ); - array_push($errorArray, $errorItem); - $this->logMessage(400, $errorItem['error_description'] ); - } - return new JsonResponse(array( - "code" => 400, - "error" => "Bad Request", - "error_description" => $errorArray[0]['error_description'], - "show_message" => $errorArray[0]['show_message'], - 'errors' => $errorArray - )); - } + return $this->reportValidationErrors($request, $errors); + } // Everything ok, now update the user record $userManager = $this->get('fos_user.user_manager'); @@ -697,6 +665,27 @@ private function fetchAccessToken(Request $request, $grantType) return $response['result']; } + private function reportValidationErrors(Request $request, \Symfony\Component\Validator\ConstraintViolationList $errors) + { + $errorArray = []; + foreach ($errors as $error) { + $constraint = $error->getConstraint(); + $errorItem = array( + "error_description" => $error->getPropertyPath().': '.$error->getMessage().' '.$error->getInvalidValue(), + "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) + ); + array_push($errorArray, $errorItem); + $this->logMessage(400, $errorItem['error_description'] ); + } + return new JsonResponse(array( + "code" => 400, + "error" => "Bad Request", + "error_description" => $errorArray[0]['error_description'], + "show_message" => $errorArray[0]['show_message'], + 'errors' => $errorArray + )); + } + private function logAndThrowError($errCode = 400, $errMsg = 'Bad Request', $showMsg = '', $locale = 'en') { $this->logMessage($errCode, $errMsg); throw new HttpException($errCode, $errMsg.($showMsg ? '#showme#'.$showMsg : '') ); From 7474f3692f305c202bbb76b7002ef8d755d4cf18 Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 13:58:46 +0530 Subject: [PATCH 07/10] Changes per feedback --- src/ApiBundle/Controller/AuthController.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ApiBundle/Controller/AuthController.php b/src/ApiBundle/Controller/AuthController.php index 075a197..f81b3ce 100644 --- a/src/ApiBundle/Controller/AuthController.php +++ b/src/ApiBundle/Controller/AuthController.php @@ -248,7 +248,7 @@ public function postRegisterAction() $errors = $validator->validate($user); if (count($errors) > 0) { - return $this->reportValidationErrors($request, $errors); + return $this->reportValidationErrors($errors, $request->getLocale()); } // Everything ok, now write the user record @@ -441,7 +441,7 @@ public function editProfileAction() $errors = $validator->validate($user, null, array('profile_edit')); if (count($errors) > 0) { - return $this->reportValidationErrors($request, $errors); + return $this->reportValidationErrors($errors, $request->getLocale()); } // Everything ok, now update the user record @@ -665,14 +665,14 @@ private function fetchAccessToken(Request $request, $grantType) return $response['result']; } - private function reportValidationErrors(Request $request, \Symfony\Component\Validator\ConstraintViolationList $errors) + private function reportValidationErrors(\Symfony\Component\Validator\ConstraintViolationList $errors, $locale) { $errorArray = []; foreach ($errors as $error) { $constraint = $error->getConstraint(); $errorItem = array( "error_description" => $error->getPropertyPath().': '.$error->getMessage().' '.$error->getInvalidValue(), - "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $request->getLocale()) + "show_message" => $this->get('translator')->trans($constraint->payload['api_error'], array(), 'messages', $locale) ); array_push($errorArray, $errorItem); $this->logMessage(400, $errorItem['error_description'] ); From 38d89869206dc24a230848b73ada3bdca2b75fe4 Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 15:41:54 +0530 Subject: [PATCH 08/10] Changes per feedback --- .../Controller/Admin/UserController.php | 93 ++++++------------- src/ApiBundle/Form/UserType.php | 7 +- 2 files changed, 34 insertions(+), 66 deletions(-) diff --git a/src/ApiBundle/Controller/Admin/UserController.php b/src/ApiBundle/Controller/Admin/UserController.php index adbe88e..f71a99e 100644 --- a/src/ApiBundle/Controller/Admin/UserController.php +++ b/src/ApiBundle/Controller/Admin/UserController.php @@ -56,39 +56,17 @@ public function newAction(Request $request) $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - try { - $userManager = $this->container->get('fos_user.user_manager'); - $user = $userManager->createUser(); - - $user->setFirstname($form['firstname']->getData()); - $user->setLastname($form['lastname']->getData()); - $user->setDob($form['dob']->getData()); - $user->setEmail($form['email']->getData()); - $user->setUsername($form['username']->getData()); - $user->setPlainPassword($form['password']->getData()); - $user->setRoles($form['roles']->getData()); - $user->setConfirmationToken(null); - $user->setEnabled(true); - $user->setLastLogin(new \DateTime()); - - $userManager->updateUser($user); - $flashMsg = $this->get('translator')->trans('flash.user_created_successfully'); - $this->addFlash('success', $flashMsg); - - } catch(HttpException $e) { - return $this->redirectToRoute('admin_user_new'); - - // Always catch exact exception for which flash message or logger is needed, - // otherwise catch block will not get executed on higher or lower ranked exceptions. - } catch(\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) { - $flashMsg = $this->get('translator')->trans('flash.user_already_exists'); - $this->logMessage(400, 'danger', $e->getMessage()); - $this->addFlash('danger', $flashMsg); - return $this->redirectToRoute('admin_user_new'); - } + $userManager = $this->container->get('fos_user.user_manager'); + $user = $userManager->createUser(); + + $this->setUserColumns($user, $form); + + $userManager->updateUser($user); + + $this->logMessageAndFlash(200, 'success', 'User successfully created: ', $this->get('translator')->trans('flash.user_creatd_successfully'), $request->getLocale() ); return $this->redirectToRoute('admin_user_index'); - } // if form is valid + } return $this->render('@ApiBundle/Resources/views/admin/user/new.html.twig', [ 'form' => $form->createView(), @@ -119,8 +97,6 @@ public function showAction(User $user) */ public function editAction(User $user, Request $request) { - $entityManager = $this->getDoctrine()->getManager(); - $editForm = $this->createForm(UserType::class, $user); $deleteForm = $this->createDeleteForm($user); $locale = $request->getLocale(); @@ -128,32 +104,12 @@ public function editAction(User $user, Request $request) $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { - try { - $user->setFirstname($editForm['firstname']->getData()); - $user->setLastname($editForm['lastname']->getData()); - $user->setDob($editForm['dob']->getData()); - $user->setEmail($editForm['email']->getData()); - $user->setUsername($editForm['username']->getData()); - $user->setPlainPassword($editForm['password']->getData()); - $user->setRoles($editForm['roles']->getData()); - $user->setConfirmationToken(null); - $user->setEnabled(true); - $user->setLastLogin(new \DateTime()); - - $entityManager->flush(); - $flashMsg = $this->get('translator')->trans('flash.user_updated_successfully'); - $this->addFlash('success', $flashMsg); - - // Always catch exact exception for which flash message or logger is needed, - // otherwise catch block will not get executed on higher or lower ranked exceptions. - } catch(HttpException $e) { - return $this->redirectToRoute('admin_user_edit', ['id' => $user->getId()]); - } catch(\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) { - $flashMsg = $this->get('translator')->trans('flash.user_already_exists'); - $this->logMessage(400, 'danger', $e->getMessage()); - $this->addFlash('danger', $flashMsg); - return $this->redirectToRoute('admin_user_edit', ['id' => $user->getId()]); - } + $this->setUserColumns($user, $editForm); + + $entityManager = $this->getDoctrine()->getManager(); + $entityManager->flush(); + + $this->logMessageAndFlash(200, 'success', 'User successfully updated: ', $this->get('translator')->trans('flash.user_updated_successfully'), $request->getLocale() ); return $this->redirectToRoute('admin_user_index'); } @@ -179,9 +135,7 @@ public function deleteAction(Request $request, User $user) $entityManager->flush(); - $flashMsg = $this->get('translator')->trans('flash.user_deleted_successfully'); - $this->logMessage(200, 'success', 'User successfully deleted: '); - $this->addFlash('success', $flashMsg); + $this->logMessageAndFlash(200, 'success', 'User successfully deleted: ', $this->get('translator')->trans('flash.user_deleted_successfully'), $request->getLocale() ); return $this->redirectToRoute('admin_user_index'); } @@ -202,11 +156,24 @@ private function createDeleteForm(User $user) ; } + private function setUserColumns(User $user, \Symfony\Component\Form\Form $form) + { + $user->setFirstname($form['firstname']->getData()); + $user->setLastname($form['lastname']->getData()); + $user->setDob($form['dob']->getData()); + $user->setEmail($form['email']->getData()); + $user->setUsername($form['username']->getData()); + $user->setPlainPassword($form['password']->getData()); + $user->setRoles($form['roles']->getData()); + $user->setConfirmationToken(null); + $user->setEnabled(true); + $user->setLastLogin(new \DateTime()); + } + private function logMessageAndFlash($code = 200, $type = 'success', $logMsg = '', $flashMsg = '', $locale = 'en') { $this->logMessage($code, $type, $logMsg); $this->addFlash($type, $flashMsg); - throw new HttpException($code, $logMsg); } private function logMessage($code = 200, $type='success', $logMsg = '') { diff --git a/src/ApiBundle/Form/UserType.php b/src/ApiBundle/Form/UserType.php index e9cfa46..dbf321e 100755 --- a/src/ApiBundle/Form/UserType.php +++ b/src/ApiBundle/Form/UserType.php @@ -24,14 +24,15 @@ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('firstname',TextType::class) - ->add('lastname',TextType::class) + ->add('lastname',TextType::class, array('required' => false)) ->add('email', EmailType::class) - ->add('dob', DateType::class) + ->add('dob', DateType::class, array('widget' => 'single_text', 'format' => 'M/d/y')) ->add('username', TextType::class) - ->add('password', TextType::class, array('data' => '')) + ->add('password', PasswordType::class, array('data' => '')) ->add('roles', CollectionType::class, array( 'entry_type' => ChoiceType::class, 'entry_options' => array( + 'label' => false, 'choices' => array( 'ROLE_USER' => 'ROLE_USER', 'ROLE_API' => 'ROLE_API', From 15f1fce357509194046f650ea19eb1c68ffd0083 Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 15:54:15 +0530 Subject: [PATCH 09/10] Changes per feedback --- src/ApiBundle/Controller/Admin/UserController.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ApiBundle/Controller/Admin/UserController.php b/src/ApiBundle/Controller/Admin/UserController.php index f71a99e..db52131 100644 --- a/src/ApiBundle/Controller/Admin/UserController.php +++ b/src/ApiBundle/Controller/Admin/UserController.php @@ -59,7 +59,7 @@ public function newAction(Request $request) $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->createUser(); - $this->setUserColumns($user, $form); + $this->setUserData($user, $form); $userManager->updateUser($user); @@ -104,7 +104,7 @@ public function editAction(User $user, Request $request) $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { - $this->setUserColumns($user, $editForm); + $this->setUserData($user, $editForm); $entityManager = $this->getDoctrine()->getManager(); $entityManager->flush(); @@ -156,7 +156,7 @@ private function createDeleteForm(User $user) ; } - private function setUserColumns(User $user, \Symfony\Component\Form\Form $form) + private function setUserData(User $user, \Symfony\Component\Form\Form $form) { $user->setFirstname($form['firstname']->getData()); $user->setLastname($form['lastname']->getData()); From 5f95d5e324cb1e7271660aa8deb21d00cbfa63bb Mon Sep 17 00:00:00 2001 From: aksinha Date: Fri, 17 Feb 2017 16:15:19 +0530 Subject: [PATCH 10/10] Readme corrected --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5f5126d..a5f51fd 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ This is an example project, ready to use. This project is using below Symfony Bu cd /path/to/auth php app/console doctrine:database:create - php app/console doctrine:scheme:create + php app/console doctrine:schema:create **Step 3 - Create assets** @@ -62,7 +62,7 @@ This is an example project, ready to use. This project is using below Symfony Bu Make this user admin - php app/console fos:user:create admin ROLE_ADMIN + php app/console fos:user:promote admin ROLE_ADMIN Now you are ready to use the Package!