| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 |
- <?php
- namespace Models;
- use Libs\Database;
- use Libs\Logger;
- class UserModel
- {
- private \PDO $pdo;
- public function __construct()
- {
- $this->pdo = Database::pdo();
- }
- /**
- * Valida credenciais de login e retorna dados do usuário se válido.
- *
- * @param string $username
- * @param string $password Plain-text password para verificar
- * @return array|null Dados do usuário (user_id, user_name, etc.) ou null se inválido
- */
- public function validateLogin(string $email, string $password): ?array
- {
- $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'");
- $stmt->execute(['email' => mb_strtolower(trim($email))]);
- $user = $stmt->fetch(\PDO::FETCH_ASSOC);
- if ($user && password_verify($password, $user['user_password'])) {
- unset($user['user_password']);
- return $user;
- }
- return null;
- }
- /**
- * Cria um novo usuário com senha hasheada e gera chaves API.
- *
- * @param string $username
- * @param string $password Plain-text password
- * @param string $flag Default 'a' para ativo
- * @return array|bool Dados do usuário criado (incluindo api_key) ou false em erro
- */
- public function createUser(int $companyId, string $email, string $password, string $phone, string $role, ?string $name = null)
- {
- $normalizedEmail = mb_strtolower(trim($email));
- $normalizedPhone = trim($phone);
- $normalizedRole = trim($role);
- $normalizedName = $name !== null ? trim($name) : null;
- if ($normalizedName === '') {
- $normalizedName = null;
- }
- $stmt = $this->pdo->prepare('SELECT user_id FROM "user" WHERE user_email = :email');
- $stmt->execute(['email' => $normalizedEmail]);
- if ($stmt->fetch()) {
- return false;
- }
- $hash = password_hash($password, PASSWORD_DEFAULT);
- try {
- $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");
- $stmt->execute([
- 'company_id' => $companyId,
- 'user_name' => $normalizedName,
- 'user_phone' => $normalizedPhone,
- 'user_email' => $normalizedEmail,
- 'user_role' => $normalizedRole,
- 'user_password' => $hash,
- ]);
- $createdUser = $stmt->fetch(\PDO::FETCH_ASSOC);
- } catch (\PDOException $e) {
- Logger::error('Failed to insert user', ['email' => $normalizedEmail, 'error' => $e->getMessage()]);
- return false;
- }
- if (!$createdUser) {
- return false;
- }
- return [
- 'user_id' => (int) $createdUser['user_id'],
- 'company_id' => (int) $createdUser['company_id'],
- 'user_name' => $createdUser['user_name'],
- 'user_phone' => $createdUser['user_phone'],
- 'user_email' => $createdUser['user_email'],
- 'user_role' => $createdUser['user_role'],
- 'user_created_at' => $createdUser['user_created_at'],
- ];
- }
- public function getCompanyIdByUserId(int $userId): ?int
- {
- $stmt = $this->pdo->prepare(
- "SELECT company_id
- FROM \"user\"
- WHERE user_id = :user_id
- AND user_deleted_at = 'infinity'
- LIMIT 1"
- );
- $stmt->execute(['user_id' => $userId]);
- $companyId = $stmt->fetchColumn();
- return $companyId === false ? null : (int) $companyId;
- }
- public function getAuthenticatedProfile(int $userId): ?array
- {
- $stmt = $this->pdo->prepare(
- 'SELECT
- u.user_id,
- u.company_id,
- u.user_name,
- u.user_phone,
- u.user_email,
- u.user_role,
- u.user_created_at,
- c.company_name,
- c.company_cnpj,
- c.company_logo,
- c.company_created_at
- FROM "user" u
- INNER JOIN company c ON c.company_id = u.company_id
- WHERE u.user_id = :user_id
- AND u.user_deleted_at = \'infinity\'
- AND c.company_deleted_at = \'infinity\'
- LIMIT 1'
- );
- $stmt->execute(['user_id' => $userId]);
- $user = $stmt->fetch(\PDO::FETCH_ASSOC);
- if (!$user) {
- return null;
- }
- return [
- 'user_id' => (int) $user['user_id'],
- 'company_id' => (int) $user['company_id'],
- 'user_name' => $user['user_name'],
- 'user_phone' => $user['user_phone'],
- 'user_email' => $user['user_email'],
- 'user_role' => $user['user_role'],
- 'user_created_at' => $user['user_created_at'],
- 'company' => [
- 'company_id' => (int) $user['company_id'],
- 'company_name' => $user['company_name'],
- 'company_cnpj' => $user['company_cnpj'],
- 'company_logo' => $user['company_logo'],
- 'company_created_at' => $user['company_created_at'],
- ],
- ];
- }
- public function changePassword(int $userId, string $currentPassword, string $newPassword): string
- {
- $stmt = $this->pdo->prepare(
- "SELECT user_password
- FROM \"user\"
- WHERE user_id = :user_id
- AND user_deleted_at = 'infinity'
- LIMIT 1"
- );
- $stmt->execute(['user_id' => $userId]);
- $userPasswordHash = $stmt->fetchColumn();
- if (!is_string($userPasswordHash) || $userPasswordHash === '') {
- return 'not_found';
- }
- if (!password_verify($currentPassword, $userPasswordHash)) {
- return 'invalid_current_password';
- }
- $newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
- try {
- $updateStmt = $this->pdo->prepare(
- "UPDATE \"user\"
- SET user_password = :user_password
- WHERE user_id = :user_id
- AND user_deleted_at = 'infinity'"
- );
- $updateStmt->execute([
- 'user_password' => $newPasswordHash,
- 'user_id' => $userId,
- ]);
- } catch (\PDOException $e) {
- Logger::error('Failed to update user password', ['user_id' => $userId, 'error' => $e->getMessage()]);
- return 'error';
- }
- return 'updated';
- }
- }
|