UserModel.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. <?php
  2. namespace Models;
  3. use Libs\Database;
  4. class UserModel
  5. {
  6. private \PDO $pdo;
  7. public function __construct()
  8. {
  9. $this->pdo = Database::pdo();
  10. }
  11. /**
  12. * Valida credenciais de login e retorna dados do usuário se válido.
  13. *
  14. * @param string $username
  15. * @param string $password Plain-text password para verificar
  16. * @return array|null Dados do usuário (user_id, user_name, etc.) ou null se inválido
  17. */
  18. public function validateLogin(string $email, string $password): ?array
  19. {
  20. $stmt = $this->pdo->prepare("SELECT user_id, company_id, user_name, user_phone, user_email, user_role, user_password FROM \"user\" WHERE user_email = :email AND user_deleted_at = 'infinity'");
  21. $stmt->execute(['email' => mb_strtolower(trim($email))]);
  22. $user = $stmt->fetch(\PDO::FETCH_ASSOC);
  23. if ($user && password_verify($password, $user['user_password'])) {
  24. unset($user['user_password']);
  25. return $user;
  26. }
  27. return null;
  28. }
  29. /**
  30. * Cria um novo usuário com senha hasheada e gera chaves API.
  31. *
  32. * @param string $username
  33. * @param string $password Plain-text password
  34. * @param string $flag Default 'a' para ativo
  35. * @return array|bool Dados do usuário criado (incluindo api_key) ou false em erro
  36. */
  37. public function createUser(int $companyId, string $email, string $password, string $phone, string $role, ?string $name = null)
  38. {
  39. $normalizedEmail = mb_strtolower(trim($email));
  40. $normalizedPhone = trim($phone);
  41. $normalizedRole = trim($role);
  42. $normalizedName = $name !== null ? trim($name) : null;
  43. if ($normalizedName === '') {
  44. $normalizedName = null;
  45. }
  46. $stmt = $this->pdo->prepare('SELECT user_id FROM "user" WHERE user_email = :email');
  47. $stmt->execute(['email' => $normalizedEmail]);
  48. if ($stmt->fetch()) {
  49. return false;
  50. }
  51. $hash = password_hash($password, PASSWORD_DEFAULT);
  52. try {
  53. $stmt = $this->pdo->prepare("INSERT INTO \"user\" (company_id, user_name, user_phone, user_email, user_role, user_password) VALUES (:company_id, :user_name, :user_phone, :user_email, :user_role, :user_password) RETURNING user_id, company_id, user_name, user_phone, user_email, user_role, user_created_at");
  54. $stmt->execute([
  55. 'company_id' => $companyId,
  56. 'user_name' => $normalizedName,
  57. 'user_phone' => $normalizedPhone,
  58. 'user_email' => $normalizedEmail,
  59. 'user_role' => $normalizedRole,
  60. 'user_password' => $hash,
  61. ]);
  62. $createdUser = $stmt->fetch(\PDO::FETCH_ASSOC);
  63. } catch (\PDOException $e) {
  64. return false;
  65. }
  66. if (!$createdUser) {
  67. return false;
  68. }
  69. return [
  70. 'user_id' => (int) $createdUser['user_id'],
  71. 'company_id' => (int) $createdUser['company_id'],
  72. 'user_name' => $createdUser['user_name'],
  73. 'user_phone' => $createdUser['user_phone'],
  74. 'user_email' => $createdUser['user_email'],
  75. 'user_role' => $createdUser['user_role'],
  76. 'user_created_at' => $createdUser['user_created_at'],
  77. ];
  78. }
  79. public function getCompanyIdByUserId(int $userId): ?int
  80. {
  81. $stmt = $this->pdo->prepare(
  82. "SELECT company_id
  83. FROM \"user\"
  84. WHERE user_id = :user_id
  85. AND user_deleted_at = 'infinity'
  86. LIMIT 1"
  87. );
  88. $stmt->execute(['user_id' => $userId]);
  89. $companyId = $stmt->fetchColumn();
  90. return $companyId === false ? null : (int) $companyId;
  91. }
  92. public function getAuthenticatedProfile(int $userId): ?array
  93. {
  94. $stmt = $this->pdo->prepare(
  95. 'SELECT
  96. u.user_id,
  97. u.company_id,
  98. u.user_name,
  99. u.user_phone,
  100. u.user_email,
  101. u.user_role,
  102. u.user_created_at,
  103. c.company_name,
  104. c.company_cnpj,
  105. c.company_logo,
  106. c.company_created_at
  107. FROM "user" u
  108. INNER JOIN company c ON c.company_id = u.company_id
  109. WHERE u.user_id = :user_id
  110. AND u.user_deleted_at = \'infinity\'
  111. AND c.company_deleted_at = \'infinity\'
  112. LIMIT 1'
  113. );
  114. $stmt->execute(['user_id' => $userId]);
  115. $user = $stmt->fetch(\PDO::FETCH_ASSOC);
  116. if (!$user) {
  117. return null;
  118. }
  119. return [
  120. 'user_id' => (int) $user['user_id'],
  121. 'company_id' => (int) $user['company_id'],
  122. 'user_name' => $user['user_name'],
  123. 'user_phone' => $user['user_phone'],
  124. 'user_email' => $user['user_email'],
  125. 'user_role' => $user['user_role'],
  126. 'user_created_at' => $user['user_created_at'],
  127. 'company' => [
  128. 'company_id' => (int) $user['company_id'],
  129. 'company_name' => $user['company_name'],
  130. 'company_cnpj' => $user['company_cnpj'],
  131. 'company_logo' => $user['company_logo'],
  132. 'company_created_at' => $user['company_created_at'],
  133. ],
  134. ];
  135. }
  136. }