Skip to main content

Overview

The School Management Platform provides comprehensive user management capabilities for students and teachers, featuring role-based access control, secure authentication, and automated session management.

Student Management

Create, view, search, and delete student accounts

Teacher Management

Manage teacher accounts and assignments

Authentication

Secure login with password hashing and session control

Role-Based Access

Three-tier permission system: Admin, Teacher, Student

User Roles

The platform supports three distinct user roles, each with specific permissions:
Full system access including:
  • Create and manage students and teachers
  • Manage courses and enrollments
  • Create and modify timetables
  • Generate student bulletins
  • View all system data
Course-specific access including:
  • View assigned courses
  • Enter and update student grades
  • View course rosters
  • Access personal timetable
  • Cannot modify system structure
Personal data access including:
  • View enrolled courses
  • View personal grades
  • Access personal timetable
  • View academic bulletin
  • Read-only access to personal data

Authentication System

Login Process

The authentication system implements secure login with session management:
// AuthController.php - authenticate()
public function authenticate()
{
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';

    $userModel = new User();
    $user = $userModel->findByEmail($email);

    // Verify credentials with password hashing
    if (!$user || !password_verify($password, $user['password'])) {
        echo "Invalid email or password";
        return;
    }

    // Prevent session fixation attacks
    session_regenerate_id(true);

    // Store user session
    $_SESSION['user'] = [
        'id' => $user['id'],
        'name' => $user['name'],
        'email' => $user['email'],
        'role' => strtolower($user['role']),
    ];

    $_SESSION['LAST_ACTIVITY'] = time();

    // Redirect to role-specific dashboard
    header("Location: /dashboard/{$_SESSION['user']['role']}");
}
Security Features:
  • Passwords are hashed using PASSWORD_DEFAULT algorithm (currently bcrypt)
  • Session regeneration prevents session fixation attacks
  • Automatic session timeout after 30 minutes of inactivity

Session Timeout

Automatic logout after 30 minutes of inactivity:
// Auth.php - check()
public static function check()
{
    if (!isset($_SESSION['user'])) {
        self::redirectLogin();
    }

    // Auto logout after 30 minutes (1800 seconds)
    if (isset($_SESSION['LAST_ACTIVITY']) && 
        (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
        session_unset();
        session_destroy();
        self::redirectLogin();
    }

    // Update last activity timestamp
    $_SESSION['LAST_ACTIVITY'] = time();
}

Role-Based Authorization

Access control is enforced at the controller level:
// Auth.php - Role verification methods
public static function admin()
{
    self::check();
    if ($_SESSION['user']['role'] !== 'admin') {
        self::redirectLogin();
    }
}

public static function teacher()
{
    self::check();
    if ($_SESSION['user']['role'] !== 'teacher') {
        self::redirectLogin();
    }
}

public static function student()
{
    self::check();
    if ($_SESSION['user']['role'] !== 'student') {
        self::redirectLogin();
    }
}

Student Management

Creating Students

Admins can create student accounts with automatic password hashing:
// StudentController.php - create()
public function create()
{
    Auth::admin(); // Only admins can create students

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $this->model->create(
            $_POST['name'],
            $_POST['email'],
            $_POST['password']
        );

        header("Location: /students");
        exit;
    }

    require __DIR__ . '/../views/students/create.php';
}
// Student.php - create()
public function create($name, $email, $password)
{
    // 1. Insert into users table
    $stmt = $this->db->prepare(
        "INSERT INTO users (name, email, password, role) 
         VALUES (?, ?, ?, 'student')"
    );
    $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT)]);

    $userId = $this->db->lastInsertId();

    // 2. Insert into students table
    $stmt = $this->db->prepare("INSERT INTO students (id) VALUES (?)");
    return $stmt->execute([$userId]);
}
Student creation is a two-step process:
  1. Create user account in users table with role ‘student’
  2. Create student entry in students table for role-specific data

Viewing All Students

// Student.php - getAll()
public function getAll()
{
    $sql = "SELECT users.id, users.name, users.email 
            FROM users 
            JOIN students ON users.id = students.id
            ORDER BY users.name";

    return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}

Searching Students

Search functionality supports name and email filtering:
// StudentController.php - search()
public function search()
{
    Auth::admin();

    $keyword = $_GET['q'] ?? '';

    if ($keyword !== '') {
        $students = $studentModel->search($keyword);
    } else {
        $students = $studentModel->getAll();
    }

    require __DIR__ . '/../views/students/index.php';
}
// Student.php - search()
public function search($keyword)
{
    $stmt = $this->db->prepare("
        SELECT students.*, users.name, users.email
        FROM students
        JOIN users ON students.id = users.id
        WHERE users.name LIKE ? OR users.email LIKE ?
    ");
    $stmt->execute(["%$keyword%", "%$keyword%"]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Deleting Students

// StudentController.php - delete()
public function delete()
{
    Auth::admin();

    $this->model->delete($_GET['id']);
    header("Location: /students");
    exit;
}
Cascade Deletion: When a student is deleted from the users table, related records in students, enrollments, and grades tables are automatically removed via database foreign key constraints.

Teacher Management

Creating Teachers

Similar to student creation with teacher role assignment:
// TeacherController.php - create()
public function create()
{
    Auth::admin();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $teacherModel = new Teacher();
        $teacherModel->create(
            $_POST['name'],
            $_POST['email'],
            $_POST['password']
        );

        header("Location: /teachers");
        exit;
    }

    require __DIR__ . '/../views/teachers/create.php';
}
// Teacher.php - create()
public function create($name, $email, $password)
{
    // Insert into users table with 'teacher' role
    $stmt = $this->db->prepare(
        "INSERT INTO users (name, email, password, role) 
         VALUES (?, ?, ?, 'teacher')"
    );
    $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT)]);

    $userId = $this->db->lastInsertId();

    // Insert into teachers table
    $stmt = $this->db->prepare("INSERT INTO teachers (id) VALUES (?)");
    $stmt->execute([$userId]);
}

Viewing All Teachers

// Teacher.php - all()
public function all()
{
    return $this->db->query("
        SELECT users.id, users.name, users.email
        FROM teachers
        JOIN users ON teachers.id = users.id
    ")->fetchAll(PDO::FETCH_ASSOC);
}

Deleting Teachers

// TeacherController.php - delete()
public function delete()
{
    Auth::admin();

    $teacherModel = new Teacher();
    $teacherModel->delete($_GET['id']);

    header("Location: /teachers");
    exit;
}

User Model

The User model provides common authentication and lookup methods:
// User.php
class User
{
    // Find user by email (for login)
    public function findByEmail($email)
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Find user by ID
    public function findById($id)
    {
        $stmt = $this->db->prepare(
            "SELECT id, name, email FROM users WHERE id = ?"
        );
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Get all students (for bulletin generation)
    public function getAllStudents()
    {
        $stmt = $this->db->query(
            "SELECT id, name, email FROM users WHERE role = 'student'"
        );
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

Database Schema

The user management system uses the following tables:
-- Users table (stores all users)
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    role ENUM('admin', 'teacher', 'student') NOT NULL
);

-- Students table (extends users)
CREATE TABLE students (
    id INT PRIMARY KEY,
    FOREIGN KEY (id) REFERENCES users(id) ON DELETE CASCADE
);

-- Teachers table (extends users)
CREATE TABLE teachers (
    id INT PRIMARY KEY,
    FOREIGN KEY (id) REFERENCES users(id) ON DELETE CASCADE
);

Security Best Practices

Password Security

  • Passwords hashed with bcrypt
  • Never stored in plain text
  • Verified using password_verify()

Session Management

  • Session regeneration on login
  • 30-minute inactivity timeout
  • Secure session storage

Access Control

  • Role-based authorization
  • Controller-level protection
  • Automatic redirects for unauthorized access

SQL Injection Prevention

  • Prepared statements for all queries
  • Parameter binding
  • PDO with parameterized queries

API Endpoints

Student Endpoints

MethodEndpointAccessDescription
GET/studentsAdminList all students
GET/students/createAdminShow create form
POST/students/createAdminCreate new student
GET/students/delete?id={id}AdminDelete student
GET/students/search?q={keyword}AdminSearch students

Teacher Endpoints

MethodEndpointAccessDescription
GET/teachersAdminList all teachers
GET/teachers/createAdminShow create form
POST/teachers/createAdminCreate new teacher
GET/teachers/delete?id={id}AdminDelete teacher

Authentication Endpoints

MethodEndpointAccessDescription
GET/loginPublicShow login form
POST/loginPublicAuthenticate user
GET/logoutAuthenticatedEnd session
All endpoints are protected by the authentication middleware. Unauthorized access attempts are automatically redirected to the login page.

Build docs developers (and LLMs) love