sealandia-framework/auth.php

78 lines
2.1 KiB
PHP

<?php
use PDO;
class Auth{
private $pdo;
/**
* Constructor method to initialize the database connection and start the session
*/
public function __construct($host, $dbname, $username, $password){
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
/**
* Instantiate the PDO object with the DSN, username, and password, and set attributes.
* Then start a new session
*/
$this->pdo = new PDO($dsn, $username. $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
session_start();
}
/**
* Method to autenticate the user based on the provided routes.
*/
public function login($username, $password){
$sql = "SELECT * FROM users WHERE username = :username or email = :email LIMIT 1";
/**
* Prepare the SQL query for execution.
* Then txecute the query with the provided username and password parameters and
* fetch the user record from the database.
*/
$query = $this->pdo->prepare($query);
$query->execute([
":username" => $username,
":password" => $password
]);
$user = $query->fetch();
/**
* Check if the provided password is verified against the hashed password in the database.
* If correct, store user information in a session.
*
* Return true indicating a successful login
*/
if($user && password_verify($password, $user['password'])){
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['token'] = bin2hex(random_bytes(32));
return true;
}
return false;
}
}
/**
* Example CSRF token in a form:
* <input type="hidden" name="csrf" value="<?php echo $_SESSION["csrf_token"]; ?>">
*
* Possible check for CSRF in a request:
* if (!empty($_REQUEST["csrf"]) && hash_equals($_REQUEST["csrf_token"], $_SESSION["csrf_token"])) {
*/
?>