Class Authenticate in ./frmwrk;
<?php
namespace frmwrk;
use frmwrk\db;
class Authenticate {
public static function isAuthenticated(): bool {
session_start();
return isset($_SESSION['user_id']);
}
public static function requireAuth(): void {
if (!self::isAuthenticated()) {
header('Location: /login');
exit;
}
}
public function login( string $email, string $password): bool {
$db = new db();
$user = $db->query("SELECT * FROM users WHERE email = :email", [
'email' => $email,
])->first();
if ($user && password_verify($_POST['password'], $user['password'])) {
// If authentication is successful, set user session and redirect
$_SESSION['user'] = [
'uid' => $user['uid'],
'name' => $user['name'],
'email' => $user['email'],
'password' => $user['password'],
];
return true;
}
return false;
}
public function logout() {
// Logic for logging out the user
unset($_SESSION['user']);
session_destroy();
}
}
AuthController in ./app/Controllers;
<?php
namespace app\Controllers;
use frmwrk\Authenticate;
use frmwrk\db;
use frmwrk\validator;
class AuthController {
public function login() {
// Logic for displaying the login form
view('login');
}
public function authenticate() {
$validator = new validator($_POST, [
'email'=> 'required|email',
'password'=> 'required|min:6',
]);
if ($validator->fails()) {
$errors = $validator->errors();
// Handle validation errors (e.g., redirect back with errors)
view('login', ['errors' => $errors]);
return;
}
$db = new db();
if ( $validator->wentThrough()) {
$login = ( new Authenticate())->login(
$_POST['email'], $_POST['password']
);
if ($login) {
// Authentication successful
redirect('/');
} else {
// Authentication failed
view('login', ['error' => $validator->errors()]);
return;
}
redirect('/login');
}
} public function logout() {
// Logic for logging out the user
(new Authenticate())->logout();
redirect('/login');
}
}
