Added: Signin Up, connection to the DB, validator, base controller, base view, environment file, User model
This commit is contained in:
parent
d7b8aba072
commit
5bca9b12aa
@ -1,19 +1,68 @@
|
||||
<?php
|
||||
|
||||
class AuthController {
|
||||
class AuthController extends Controller {
|
||||
public function signin() {
|
||||
$view = new View();
|
||||
$data = [
|
||||
'title' => 'Log In'
|
||||
];
|
||||
$view->render('auth/signin', $data);
|
||||
if($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$email = $_POST['email'] ?? '';
|
||||
$password = $_POST['password'] ?? '';
|
||||
|
||||
$user = new User();
|
||||
$result = $user->login($email, $password);
|
||||
|
||||
if($result === true) {
|
||||
$this->redirect('/dashboard');
|
||||
} else {
|
||||
$this->view('auth/signin', ['error' => $result]);
|
||||
}
|
||||
} else {
|
||||
$this->view('auth/signin', ['title' => 'Log In']);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function signup() {
|
||||
$view = new View();
|
||||
$data = [
|
||||
'title' => 'Register'
|
||||
];
|
||||
$view->render('auth/signup', $data);
|
||||
}
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$username = $_POST['username'] ?? '';
|
||||
$email = $_POST['email'] ?? '';
|
||||
$password = $_POST['password'] ?? '';
|
||||
$password2 = $_POST['password-2'] ?? '';
|
||||
|
||||
// Perform validations
|
||||
$validator = new Validator();
|
||||
|
||||
$validator->required('username', $username);
|
||||
$validator->email('email', $email);
|
||||
$validator->required('password', $password);
|
||||
$validator->minLength('password', $password, 8);
|
||||
$validator->alphanumeric('password', $password);
|
||||
|
||||
if ($password !== $password2) {
|
||||
$validator->errors()['password_confirmation'] = 'Passwords do not match.';
|
||||
}
|
||||
|
||||
if (!$validator->passes()) {
|
||||
$this->view('auth/signup', [
|
||||
'error' => 'Please correct the errors below.',
|
||||
'validationErrors' => $validator->errors() ?: [],
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$user = new User();
|
||||
$result = $user->register($username, $email, $password);
|
||||
|
||||
if ($result === true) {
|
||||
$this->redirect('/auth/signin');
|
||||
} else {
|
||||
$this->view('auth/signup', [
|
||||
'error' => $result,
|
||||
'validationErrors' => [],
|
||||
]);
|
||||
}
|
||||
} else {
|
||||
$this->view('auth/signup', [
|
||||
'title' => 'Register',
|
||||
'validationErrors' => [],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
45
app/models/User.php
Normal file
45
app/models/User.php
Normal file
@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
require_once '../core/Database.php';
|
||||
|
||||
class User {
|
||||
private $db;
|
||||
|
||||
public function __construct() {
|
||||
$this->db = Database::getInstance()->getConnection();
|
||||
|
||||
if ($this->db) {
|
||||
error_log("Database connection established successfully.");
|
||||
} else {
|
||||
error_log("Failed to connect to the database.");
|
||||
}
|
||||
}
|
||||
|
||||
public function register($username, $email, $password) {
|
||||
// Check if email already exists
|
||||
$stmt = $this->db->prepare("SELECT id FROM users WHERE email = ?");
|
||||
$stmt->bind_param("s", $email);
|
||||
$stmt->execute();
|
||||
$result = $stmt->get_result();
|
||||
$stmt->close();
|
||||
|
||||
if ($result->num_rows > 0) {
|
||||
return "Email is already registered";
|
||||
}
|
||||
|
||||
// Hash the password
|
||||
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
|
||||
|
||||
$stmt = $this->db->prepare("INSERT INTO users (username, email, password, points, created_at) VALUES (?, ?, ?, 0, NOW())");
|
||||
$stmt->bind_param("sss", $username, $email, $hashedPassword);
|
||||
|
||||
if ($stmt->execute()) {
|
||||
return true;
|
||||
} else {
|
||||
return "Error: " . $stmt->error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
|
@ -1,11 +1,33 @@
|
||||
<section class="signup">
|
||||
<form>
|
||||
<label for="username">Username</label>
|
||||
<input type="text" name="username" id="username">
|
||||
<label for="password">Password</label>
|
||||
<input type="password" name="password" id="password">
|
||||
<label for="password-2">Password again</label>
|
||||
<input type="password" name="password-2" id="password-2">
|
||||
<input type="submit" value="Sign Up" id="submit-signup">
|
||||
</form>
|
||||
<?php if ($this->get('error')): ?>
|
||||
<div class="error"><?= $this->get('error') ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<form action="/auth/signup" method="POST">
|
||||
<label for="username">Username</label>
|
||||
<input type="text" name="username" id="username" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required>
|
||||
<?php if (isset($this->get('validationErrors')['username'])): ?>
|
||||
<small class="error"><?= $this->get('validationErrors')['username'] ?></small>
|
||||
<?php endif; ?>
|
||||
|
||||
<label for="email">Email</label>
|
||||
<input type="email" name="email" id="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
|
||||
<?php if (isset($this->get('validationErrors')['email'])): ?>
|
||||
<small class="error"><?= $this->get('validationErrors')['email'] ?></small>
|
||||
<?php endif; ?>
|
||||
|
||||
<label for="password">Password</label>
|
||||
<input type="password" name="password" id="password" required>
|
||||
<?php if (isset($this->get('validationErrors')['password'])): ?>
|
||||
<small class="error"><?= $this->get('validationErrors')['password'] ?></small>
|
||||
<?php endif; ?>
|
||||
|
||||
<label for="password-2">Password again</label>
|
||||
<input type="password" name="password-2" id="password-2" required>
|
||||
<?php if (isset($this->get('validationErrors')['password_confirmation'])): ?>
|
||||
<small class="error"><?= $this->get('validationErrors')['password_confirmation'] ?></small>
|
||||
<?php endif; ?>
|
||||
|
||||
<input type="submit" value="Sign Up">
|
||||
</form>
|
||||
</section>
|
||||
|
1
config/.gitignore
vendored
Normal file
1
config/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
environment.php
|
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
class Controller {
|
||||
/**
|
||||
* Redirect to a given URL
|
||||
*
|
||||
* @param string $url
|
||||
*/
|
||||
public function redirect($url) {
|
||||
header("Location: $url");
|
||||
exit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a view
|
||||
*
|
||||
* @param string $viewName
|
||||
* @param array $data
|
||||
*/
|
||||
public function view($viewName, $data = []) {
|
||||
$view = new View();
|
||||
$view->render($viewName, $data);
|
||||
}
|
||||
}
|
101
core/Database.php
Normal file
101
core/Database.php
Normal file
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
class Database {
|
||||
private static $instance = null;
|
||||
private $connection;
|
||||
|
||||
private function __construct() {
|
||||
$this->initializeConnection();
|
||||
$this->checkAndCreateDatabase();
|
||||
$this->checkAndCreateTables();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the singleton instance of the Database
|
||||
* @return Database
|
||||
*/
|
||||
public static function getInstance() {
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new Database();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the active database connection
|
||||
* @return mysqli
|
||||
*/
|
||||
public function getConnection() {
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the connection to the database
|
||||
*/
|
||||
private function initializeConnection() {
|
||||
$this->connection = new mysqli(DB_HOST, DB_USER, DB_PASS);
|
||||
|
||||
if ($this->connection->connect_error) {
|
||||
die("Database connection failed: " . $this->connection->connect_error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check and create the database if it doesn't exist
|
||||
*/
|
||||
private function checkAndCreateDatabase() {
|
||||
$query = "CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "`";
|
||||
if (!$this->connection->query($query)) {
|
||||
die("Failed to create or access database: " . $this->connection->error);
|
||||
}
|
||||
|
||||
$this->connection->select_db(DB_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check and create required tables if they don't exist
|
||||
*/
|
||||
private function checkAndCreateTables() {
|
||||
// Create users table
|
||||
$usersTableQuery = "CREATE TABLE IF NOT EXISTS users (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(50) NOT NULL,
|
||||
email VARCHAR(100) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
points INT DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB;";
|
||||
|
||||
if (!$this->connection->query($usersTableQuery)) {
|
||||
die("Failed to create users table: " . $this->connection->error);
|
||||
}
|
||||
|
||||
// Create progress table
|
||||
$progressTableQuery = "CREATE TABLE IF NOT EXISTS progress (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id INT NOT NULL,
|
||||
habit_id INT NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
status ENUM('Done', 'Pending') DEFAULT 'Pending',
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
) ENGINE=InnoDB;";
|
||||
|
||||
if (!$this->connection->query($progressTableQuery)) {
|
||||
die("Failed to create progress table: " . $this->connection->error);
|
||||
}
|
||||
|
||||
// Add more table creation logic as needed
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevent cloning of the singleton instance
|
||||
*/
|
||||
private function __clone() {}
|
||||
|
||||
/**
|
||||
* Prevent unserialization of the singleton instance
|
||||
*/
|
||||
public function __wakeup() {}
|
||||
|
||||
}
|
55
core/Validator.php
Normal file
55
core/Validator.php
Normal file
@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
class Validator {
|
||||
private $errors = [];
|
||||
|
||||
/**
|
||||
* Check if a field is not empty
|
||||
*/
|
||||
public function required($field, $value, $message = null) {
|
||||
if (empty(trim($value))) {
|
||||
$this->errors[$field] = $message ?? "$field is required.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a field meets minimum length
|
||||
*/
|
||||
public function minLength($field, $value, $length, $message = null) {
|
||||
if (strlen($value) < $length) {
|
||||
$this->errors[$field] = $message ?? "$field must be at least $length characters.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a field contains letters and numbers
|
||||
*/
|
||||
public function alphanumeric($field, $value, $message = null) {
|
||||
if (!preg_match('/^(?=.*[a-zA-Z])(?=.*\d).+$/', $value)) {
|
||||
$this->errors[$field] = $message ?? "$field must contain letters and numbers.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an email
|
||||
*/
|
||||
public function email($field, $value, $message = null) {
|
||||
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
||||
$this->errors[$field] = $message ?? "Invalid email format.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors
|
||||
*/
|
||||
public function errors() {
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if validation passed
|
||||
*/
|
||||
public function passes() {
|
||||
return empty($this->errors);
|
||||
}
|
||||
}
|
@ -1,10 +1,11 @@
|
||||
<?php
|
||||
class View
|
||||
{
|
||||
public function render($view, $data = [], $layout = 'base')
|
||||
{
|
||||
// Extract variables to be accessible in the view
|
||||
extract($data);
|
||||
private $data = [];
|
||||
|
||||
public function render($view, $data = [], $layout = 'base') {
|
||||
// Store the data
|
||||
$this->data = $data;
|
||||
|
||||
// Capture the view content
|
||||
ob_start();
|
||||
@ -12,6 +13,13 @@ class View
|
||||
$content = ob_get_clean();
|
||||
|
||||
// Include the base layout and inject the view content
|
||||
require_once views . "layouts/$layout.php";
|
||||
require_once views . "layouts/$layout.php";
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely get a value from the data array
|
||||
*/
|
||||
public function get($key) {
|
||||
return $this->data[$key] ?? null;
|
||||
}
|
||||
}
|
||||
|
@ -7,10 +7,17 @@ ini_set('error_log', '../storage/logs/error_log.log');
|
||||
define('models', __DIR__ . '/../app/models/');
|
||||
define('views', __DIR__ . '/../app/views/');
|
||||
define('controllers', __DIR__ . '/../app/controllers/');
|
||||
define('config', __DIR__ . '/../config/');
|
||||
|
||||
require_once config . 'environment.php';
|
||||
|
||||
require_once '../core/Validator.php';
|
||||
require_once '../core/Router.php';
|
||||
require_once '../core/View.php';
|
||||
require_once '../core/Controller.php';
|
||||
require_once '../core/Database.php';
|
||||
|
||||
require_once models . 'User.php';
|
||||
|
||||
// Initialize router
|
||||
$router = new Router();
|
||||
|
Loading…
Reference in New Issue
Block a user