54 lines
1.3 KiB
PHP
54 lines
1.3 KiB
PHP
<?php
|
|
namespace App\Controllers;
|
|
|
|
session_start();
|
|
|
|
use App\Models\User;
|
|
|
|
class AuthController {
|
|
private $userModel;
|
|
|
|
public function __construct() {
|
|
$this->userModel = new User();
|
|
}
|
|
|
|
public function register($name, $email, $password) {
|
|
if ($this->userModel->findByEmail($email)) {
|
|
return ['error' => 'Email already exists'];
|
|
}
|
|
|
|
$result = $this->userModel->register($name, $email, $password);
|
|
|
|
if ($result) {
|
|
$user = $this->userModel->findByEmail($email);
|
|
$_SESSION['user_id'] = $user['id'];
|
|
return ['success' => true, 'user' => $user];
|
|
}
|
|
|
|
return ['error' => 'Registration failed'];
|
|
}
|
|
|
|
public function login($email, $password) {
|
|
$user = $this->userModel->login($email, $password);
|
|
|
|
if ($user) {
|
|
$_SESSION['user_id'] = $user['id'];
|
|
return ['success' => true, 'user' => $user];
|
|
}
|
|
|
|
return ['error' => 'Invalid credentials'];
|
|
}
|
|
|
|
public function logout() {
|
|
session_destroy();
|
|
return ['success' => true];
|
|
}
|
|
|
|
public static function isAuthenticated() {
|
|
return isset($_SESSION['user_id']);
|
|
}
|
|
|
|
public static function getCurrentUserId() {
|
|
return $_SESSION['user_id'] ?? null;
|
|
}
|
|
} |