Skip to content

Commit

Permalink
Log adicionado, ta salvando no banco;
Browse files Browse the repository at this point in the history
Criado uma classe para conexão do banco de dados;
  • Loading branch information
ramosbrp committed Jun 28, 2024
1 parent f50fc7f commit acbb2b4
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 16 deletions.
42 changes: 42 additions & 0 deletions classes/DatabaseConnection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php
namespace Classes;

use PDO;
use PDOException;

require_once '../vendor/autoload.php';

class DatabaseConnection
{

private $dbHost;
private $dbDatabase;
private $dbUser;
private $dbPassword;
private $conn;

function __construct()
{
$this->dbHost = getenv('DB_HOST');
$this->dbDatabase = getenv('DB_DATABASE');
$this->dbUser = getenv('DB_USERNAME');
$this->dbPassword = getenv('DB_PASSWORD');
$this->conn = new PDO("sqlsrv:server = tcp:$this->dbHost; Database = $this->dbDatabase", $this->dbUser, $this->dbPassword);

}

public function getConnection()
{
try {
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// echo"<script>console.log('Conectado ao banco de dados.')</script>";
return $this->conn;
} catch (PDOException $e) {
// $client->trackException($e);
error_log("Error connecting to SQL Server: " . $e->getMessage());
die("Error connecting to SQL Server.");
}
}

}
39 changes: 39 additions & 0 deletions classes/Logger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace classes;

use Exception;

class Logger
{

public function __construct()
{
}

public function logEvent($userID, $action, $details)
{
try {

$db = new DatabaseConnection();
$conn = $db->getConnection();

$query = "INSERT into UserLogs (user_id, action, log_date, details) VALUES (:userID, :action, GETDATE(), :details)";

$stmt = $conn->prepare($query);
$stmt->bindParam(":userID", $userID);
$stmt->bindParam(":action", $action);
$stmt->bindParam(":details", $details);
$stmt->execute();


// $this->client->trackEvent("Salvar log.");
} catch (Exception $e) {
// $this->client->trackException("Erro ao Salvar log: $e");
return $e->getMessage();
} finally {
// $this->client->flush();
}
}
}
?>
7 changes: 6 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@
"phpmailer/phpmailer": "^6.9",
"vlucas/phpdotenv": "^5.6",
"microsoft/application-insights": "^0.4.5"
},
"autoload": {
"psr-4": {
"classes\\": "classes/"
}
}
}
}
33 changes: 19 additions & 14 deletions controllers/login.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<?php

session_start();

use classes\Logger;
use classes\DatabaseConnection;

use ApplicationInsights\Telemetry_Client;

require_once '../vendor/autoload.php';
Expand All @@ -11,28 +15,22 @@
$dotenv->load();
}

$instrumentalKey = getenv('INSTRUMENTATION_KEY');

// Configuração do Application Insights
$client = new Telemetry_Client();
$client->getContext()->setInstrumentationKey($instrumentalKey);
// $client = new Telemetry_Client();
// $instrumentalKey = getenv('INSTRUMENTATION_KEY');
// $client->getContext()->setInstrumentationKey($instrumentalKey);

// Função para criar conexão com o banco de dados
function createDatabaseConnection()
{
$dbHost = getenv('DB_HOST');
$dbDatabase = getenv('DB_DATABASE');
$dbUser = getenv('DB_USERNAME');
$dbPassword = getenv('DB_PASSWORD');

global $client; // Usar o cliente de telemetria global
try {
$conn = new PDO("sqlsrv:server = tcp:$dbHost; Database = $dbDatabase", $dbUser, $dbPassword);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db = new DatabaseConnection();
$conn = $db->getConnection();
return $conn;
} catch (PDOException $e) {
$client->trackException($e);
// $client->trackException($e);
error_log("Error connecting to SQL Server: " . $e->getMessage());
die("Error connecting to SQL Server.");
// echo"<script>console.log()</script>";
Expand All @@ -42,9 +40,9 @@ function createDatabaseConnection()
// Função para validar o login do usuário
function validateUser($login, $password)
{
global $client; // Usar o cliente de telemetria global
$conn = createDatabaseConnection();

$logger = new Logger();
try {
$query = "SELECT * FROM usuario WHERE login = :login";
$stmt = $conn->prepare($query);
Expand All @@ -58,6 +56,13 @@ function validateUser($login, $password)
if (password_verify($password, $user['senha'])) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $login;


$userID = $user['id']; // ID do usuário que logou
$action = "Login";
$details = "Login efetuado com sucesso.";

$logger->logEvent($userID, $action, $details);
return ['success' => true, 'message' => 'Login bem-sucedido!', 'username' => $login];
} else {
return ['success' => false, 'message' => 'Senha incorreta.'];
Expand All @@ -66,7 +71,7 @@ function validateUser($login, $password)
return ['success' => false, 'message' => "Usuário $login não encontrado."];
}
} catch (PDOException $e) {
$client->trackException($e);
// $client->trackException($e);
error_log("Database query error: " . $e->getMessage());
return ['success' => false, 'message' => 'Erro ao acessar o banco de dados.'];
}
Expand Down
2 changes: 1 addition & 1 deletion js/logincadastroapp.js
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ const logar = async (formElement) => {
method: 'POST',
body: formData
})

// console.log(response.text() );
if (!response.ok)
throw new Error("Error");
const data = await response.json();
Expand Down

0 comments on commit acbb2b4

Please sign in to comment.