PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/controller/UserController.php

https://gitlab.com/janderson/dictionary
PHP | 247 lines | 209 code | 20 blank | 18 comment | 42 complexity | 97e599b4f27670abcf38953bb8bd7d64 MD5 | raw file
  1. <?php
  2. require_once './Controller.php';
  3. require_once '../model/Contact.php';
  4. require_once './ExceptionController.php';
  5. require_once '../model/Config.php';
  6. class UserController extends Controller {
  7. const ERROR_CODE_PREFIX = '11';
  8. const URL_CONTROL_PANEL = '../view/control_panel.php';
  9. const URL_REQUEST_ACTIVE = '../view/activate_account.php';
  10. const URL_RESEARCH = '/dictionary/view/result_of_research.php';
  11. const URL_PROFILE = '../view/profile.php';
  12. protected $user;
  13. protected $contact;
  14. public function __construct() {
  15. parent::__construct();
  16. try {
  17. $this->user = new User();
  18. $this->contact = new Contact();
  19. switch ($_SERVER['REQUEST_METHOD']) {
  20. case "POST":
  21. var_dump($_POST);
  22. switch ($_POST['option']) {
  23. case 'new_user':
  24. $this->newUser();
  25. break;
  26. case 'edit':
  27. $this->editUser();
  28. break;
  29. case 'login':
  30. $login = $_POST['login'];
  31. $password = md5($_POST['password']);
  32. $this->login($login, $password);
  33. break;
  34. case 'request_password':
  35. $email = $_POST['email'];
  36. $this->requestPassword($email);
  37. break;
  38. default:
  39. break;
  40. }
  41. exit();
  42. case "GET":
  43. if (!empty($_GET['option']) && $_GET['option'] == 'logout') {
  44. self::logout();
  45. }
  46. exit();
  47. default :
  48. throw new ExceptionController('Método não suportado!', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_OPTION, NULL);
  49. }
  50. } catch (Exception $e) {
  51. if ($e instanceof ExceptionController || $e instanceof CrudException) {
  52. $_SESSION['error_code'] = $e->getCode();
  53. $_SESSION['error_message'] = $e->getMessage();
  54. if (empty($_SERVER['HTTP_REFERER'])) {
  55. header("Location: " . ExceptionController::PATH_ERROR_PAGE);
  56. } else {
  57. header("Location: {$_SERVER['HTTP_REFERER']}");
  58. }
  59. } else {
  60. ExceptionController::handleException($e);
  61. }
  62. }
  63. }
  64. private function newUser() {
  65. $this->user->name = $this->validateName($_POST['name']);
  66. $this->user->email = $this->validateEmail($_POST['email']);
  67. $this->user->password = $this->validatePassword($_POST['password'], $_POST['re_password']);
  68. $this->user->id_city = $_POST['id_city'];
  69. $this->user->id_user = $this->user->create();
  70. if ($this->user->id_user > 0) {
  71. self::setSession($this->user->cpf, $this->user->password, $this->user->email);
  72. header('location: ' . self::URL_CONTROL_PANEL);
  73. } else {
  74. throw new ExceptionController('Não foi possível registrar sua conta, verifique se as informações foram digitadas corretamente!', self::ERROR_CODE_PREFIX . '80');
  75. }
  76. }
  77. private function editUser() {
  78. $this->requireUserSession();
  79. $this->_currentUser->name = $this->validateName($_POST['name']);
  80. // $this->_currentUser->email = $this->validateEmail($_POST['email']);
  81. $this->_currentUser->mother_name = $this->validateName($_POST['mothername']);
  82. if (!empty($_POST['new_password'])) {
  83. $this->_currentUser->password = $this->validatePassword($_POST['new_password'], $_POST['re_password']);
  84. }
  85. $this->_currentUser->cpf = Validate::cpf($_POST['cpf']);
  86. $this->_currentUser->institution = $_POST['institution'];
  87. $this->_currentUser->active = 1;
  88. $this->_currentUser->dt_born = Validate::formatDateFromPtBr($_POST['dt_born']);
  89. $this->_currentUser->rg = $_POST['rg'];
  90. $this->_currentUser->phone = $_POST['phone'];
  91. $this->_currentUser->cellfone = $_POST['cellfone'];
  92. $this->_currentUser->adress = $_POST['adress'];
  93. $this->_currentUser->number = $_POST['number'];
  94. $this->_currentUser->postal_code = Validate::cep($_POST['postal_code']);
  95. $this->_currentUser->district = $_POST['district'];
  96. if (!$this->_currentUser->update(array('id_user' => $this->_currentUser->id_user)) > 0) {
  97. throw new ExceptionController('Não foi possível atualizar seu perfil', self::ERROR_CODE_PREFIX . ExceptionController::FAIL_UPDATE);
  98. } else {
  99. $_SESSION['sucess'] = 'Perfil atualizado com sucesso.';
  100. header("Location: " . self::URL_PROFILE);
  101. }
  102. }
  103. protected static function setSession($password, $email = NULL) {
  104. /**
  105. * Método que cria sessão de email e senha do usuário corrente, caso ele seja validado
  106. * @param String $email Email do usuário corrente
  107. * @param String $password Senha do usuário corrente criptografada
  108. *
  109. * */
  110. $_SESSION['email'] = $email; //setando email
  111. $_SESSION['password'] = $password; //setando senha
  112. $_SESSION['type_user'] = 0;
  113. }
  114. private function login($login, $password) {
  115. /**
  116. * Método que valida o login do usuário recebendo por parâmetro email e senha
  117. *
  118. * @param String $email Email do usuário corrente
  119. * @param String $password Senha do usuário corrente criptografada
  120. *
  121. * */
  122. $validate = new Validate();
  123. if ($validate->validateEmail($login)) {
  124. if ($this->user->validateUser($login, $password)) { //realiza validação do usuário buscando dados no banco
  125. $object_user = $this->user->retriveUser($login);
  126. self::setSession($password, $object_user->email); //chama método estático setSession
  127. } else {
  128. throw new ExceptionController('Usuário Inválido.', self::ERROR_CODE_PREFIX . '03');
  129. }
  130. } else {
  131. throw new ExceptionController('Usuário inválido.', self::ERROR_CODE_PREFIX . '04');
  132. }
  133. if (isset($_POST['redirect'])) {
  134. header("Location: " . $_POST['redirect'] . ($_POST['redirect'] == self::URL_RESEARCH ? '?register' : ''));
  135. } else {
  136. header("Location: " . self::URL_CONTROL_PANEL);
  137. }
  138. }
  139. public function requestPassword($email) {
  140. $user = $this->user->retriveUser($_POST['email']);
  141. if (count($user) > 0) {
  142. $new_password = substr(md5(uniqid()), 0, 5);
  143. $this->contact->email = $email;
  144. $this->resetPassword($user->id_user, $new_password);
  145. $this->contact->subject = "Nova Senha - Inventum";
  146. $this->sendEmail($this->contact->email, $user->name, $this->contact->subject, $new_password);
  147. header("Location: ../view/index.php");
  148. } else {
  149. throw new ExceptionController('Email Inválido.', self::ERROR_CODE_PREFIX . '03');
  150. }
  151. }
  152. public function resetPassword($id_user, $password) {
  153. if ($this->user->updatePassword(md5($password), $id_user)) {
  154. $_SESSION['sucess'] = "Senha modificada com sucesso.";
  155. } else {
  156. throw new ExceptionController($this->getErrorMessage('09'), self::ERROR_CODE_PREFIX . '01');
  157. ob_end_flush();
  158. }
  159. }
  160. private function sendEmail($to, $name, $subject, $password) {
  161. $email = new Email();
  162. $this->contact->content = $email->generateEmail(Email::TYPE_REQUEST_PASSWORD, $name, $password);
  163. $res = $this->contact->create(array('id_contact' => $this->contact->id_contact));
  164. $email->sendRequestEmail($to, $subject, $this->contact->content);
  165. return TRUE;
  166. }
  167. public static function logout() {
  168. /**
  169. * Método logout para deslogar o usuário
  170. * */
  171. session_start(); //inicia session
  172. $_SESSION = array(); //atribue um array vazio para a sessão
  173. session_destroy(); // destrói a sessão
  174. header("Location: ../view/index.php"); //redireciona para o login
  175. ob_end_flush();
  176. }
  177. // =========================================================================
  178. private function validateEmail($email) {
  179. $validate = new Validate();
  180. if ($validate->validateEmail($email)) {
  181. if (!$this->user->searchValue('email', $email, $this->user->id_user)) {
  182. return strtolower($email);
  183. } else {
  184. throw new ExceptionController('Email já cadastrado', 1101);
  185. }
  186. } else {
  187. throw new ExceptionController('Email inválido', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_EMAIL);
  188. }
  189. }
  190. private function validateName($name) {
  191. $validate = new Validate();
  192. if (stripos($name, " ")) {
  193. if ($validate->validateField($name, 100, 2) && $validate->getWordsNumber($name > 1)) {
  194. return ucwords(strtolower($name));
  195. } else {
  196. throw new ExceptionController('Nome Inválido', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_USER_NAME);
  197. }
  198. } else {
  199. throw new ExceptionController('Informe o nome completo, seu e de sua mãe', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_USER_NAME);
  200. }
  201. }
  202. private function validateCpf($cpf) {
  203. $validate = new Validate();
  204. $cpf = str_replace(array('.', '-'), '', $cpf);
  205. if ($validate->validateCpf($cpf)) {
  206. if (!$this->user->searchValue('cpf', $cpf, $this->user->id_user)) {
  207. return $cpf;
  208. } else {
  209. throw new ExceptionController('CPF já cadastrado', 1101);
  210. }
  211. } else {
  212. throw new ExceptionController('CPF inválido', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_EMAIL);
  213. }
  214. }
  215. private function formatDate($date) {
  216. $date = str_replace('/', '-', $date);
  217. return date('Y-m-d', strtotime($date));
  218. }
  219. private function validatePassword($pass, $rePass) {
  220. if (md5($pass) == md5($rePass)) {
  221. return md5($pass);
  222. } else {
  223. throw new ExceptionController('As senhas digitadas não correspondem', self::ERROR_CODE_PREFIX . '06');
  224. }
  225. }
  226. }
  227. new UserController();