pdo = new \PDO("sqlite:" . $dbPath); $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } /** * 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 $username, string $password): ?array { $stmt = $this->pdo->prepare("SELECT user_id, user_name, user_password FROM user WHERE user_name = :username AND user_flag = 'a'"); $stmt->execute(['username' => $username]); $user = $stmt->fetch(\PDO::FETCH_ASSOC); if ($user && password_verify($password, $user['user_password'])) { unset($user['password']); // Remove hash por segurança 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(string $username, string $password, string $flag = 'a') { // Verifica se username já existe $stmt = $this->pdo->prepare("SELECT user_id FROM user WHERE user_name = :username"); $stmt->execute(['username' => $username]); if ($stmt->fetch()) { return false; // Já existe } $hash = password_hash($password, PASSWORD_DEFAULT); // Insere usuário $stmt = $this->pdo->prepare("INSERT INTO user (user_name, user_flag, user_password) VALUES (:username, :flag, :hash)"); if (!$stmt->execute(['username' => $username, 'flag' => $flag, 'hash' => $hash])) { return false; } $userId = $this->pdo->lastInsertId(); // Gera e insere chaves API (random para HMAC) $apiKey = bin2hex(random_bytes(16)); // Ex: 32 chars hex $apiSecret = bin2hex(random_bytes(32)); // Mais longo para secret $stmt = $this->pdo->prepare("INSERT INTO api_key (user_id, api_key_user, api_key_secret) VALUES (:user_id, :api_key, :api_secret)"); if (!$stmt->execute(['user_id' => $userId, 'api_key' => $apiKey, 'api_secret' => $apiSecret])) { return false; } return [ 'user_id' => $userId, 'user_name' => $username, 'api_key_user' => $apiKey, 'api_key_secret' => $apiSecret // Retorne para o usuário (apenas uma vez!) ]; } }