ForgeAuth

Complete authentication system with login, registration, password reset, and session management for Forge applications.

Overview

ForgeAuth provides authentication for Forge applications with user registration, login functionality, session management, and security features.

Key Capabilities

User registration
Login/logout functionality
Session management
Password hashing (bcrypt)
Rate limiting protection
Session security

Features

Authentication

  • • User registration with validation
  • • Secure login with bcrypt password hashing
  • • Session-based authentication
  • • Remember me functionality

Security

  • • Rate limiting for login attempts
  • • Session regeneration on login
  • • CSRF protection integration
  • • Secure password storage

User Management

  • • User profile management
  • • Metadata storage
  • • User status tracking
  • • Profile relationships

Integration

  • • Service container integration
  • • Middleware support
  • • Route registration
  • • Event system integration

Installation

Use Forge Package Manager or manually download and install the module.

Using Forge Package Manager

# Install the latest version
php forge install:module ForgeAuth

# Install a specific version
php forge install:module ForgeAuth@0.1.2

Manual Installation

# Clone the repository
git clone https://github.com/forge-engine/modules.git

# Copy the ForgeAuth module to your modules directory
cp -r modules/ForgeAuth /path/to/your/forge/modules/

Dependencies: ForgeAuth requires the Session module to be installed and configured for proper session management.

Configuration

Modify configuration file or use environment variables.

Basic Configuration

// config/forge_auth.php
return [
    "forge_auth" => [
        "example" => "hi"
    ]
];

Security Configuration

Configure security settings in your main application configuration:

// config/security.php
return [
    "security" => [
        "password" => [
            "max_login_attempts" => 5,    // Maximum failed login attempts
            "lockout_time" => 300,        // Lockout time in seconds (5 minutes)
        ]
    ]
];

Environment Variables

# Session configuration
SESSION_LIFETIME=120
SESSION_SECURE=true
SESSION_HTTP_ONLY=true

# Security settings
SECURITY_PASSWORD_MAX_ATTEMPTS=5
SECURITY_PASSWORD_LOCKOUT_TIME=300

Usage

Use ForgeAuth for user authentication and management.

Basic Authentication

use App\Modules\ForgeAuth\Contracts\ForgeAuthInterface;

// Inject the authentication service
class UserController
{
    public function __construct(
        private ForgeAuthInterface $auth
    ) {}

    public function register(Request $request)
    {
        try {
            $credentials = [
                'identifier' => $request->post('username'),
                'email' => $request->post('email'),
                'password' => $request->post('password'),
                'metadata' => [
                    'first_name' => $request->post('first_name'),
                    'last_name' => $request->post('last_name')
                ]
            ];

            $success = $this->auth->register($credentials);
            
            if ($success) {
                return redirect('/login')->with('success', 'Registration successful!');
            }
        } catch (UserRegistrationException $e) {
            return redirect('/register')->with('error', 'Registration failed');
        }
    }

    public function login(Request $request)
    {
        try {
            $credentials = [
                'identifier' => $request->post('username'),
                'password' => $request->post('password')
            ];

            $user = $this->auth->login($credentials);
            
            return redirect('/dashboard')->with('success', 'Welcome back!');
        } catch (LoginException $e) {
            return redirect('/login')->with('error', 'Invalid credentials');
        }
    }
}

User Session Management

// Get current user
$user = $this->auth->user();

if ($user) {
    echo "Welcome, " . $user->identifier;
    echo "Email: " . $user->email;
    echo "Status: " . $user->status;
}

// Logout user
$this->auth->logout();

// Check if user is authenticated
$isAuthenticated = $this->auth->user() !== null;

Dependency Injection

// ForgeAuth automatically binds the interface to implementation
// in your module's register method:

public function register(Container $container): void
{
    $container->bind(ForgeAuthInterface::class, ForgeAuthService::class);
}

// Now you can inject the interface anywhere:
class MyService
{
    public function __construct(
        private ForgeAuthInterface $auth
    ) {}
}

Controllers

ForgeAuth provides pre-built controllers for common authentication workflows.

Web Login Controller

// Routes automatically registered:
// GET /auth/login - Show login form
// POST /auth/login - Process login
// POST /auth/logout - Process logout

// Usage in your application:
<a href="/auth/login">Login</a>
<form method="POST" action="/auth/login">
    <input type="text" name="username" placeholder="Username" required>
    <input type="password" name="password" placeholder="Password" required>
    <button type="submit">Login</button>
</form>

Creating Custom Controllers

use App\Modules\ForgeAuth\Contracts\ForgeAuthInterface;
use Forge\Core\Http\Request;
use Forge\Core\Http\Response;
use Forge\Core\Routing\Route;

#[Route("/custom-auth")]
class CustomAuthController
{
    public function __construct(
        private ForgeAuthInterface $auth
    ) {}

    #[Route("/custom-auth/profile", "GET")]
    public function profile(): Response
    {
        $user = $this->auth->user();
        
        if (!$user) {
            return redirect('/auth/login');
        }

        return $this->view('profile', ['user' => $user]);
    }
}

Models

ForgeAuth includes User and Profile models for managing user data.

User Model

// User model properties:
// - id: Primary key
// - identifier: Unique username/identifier
// - email: User email address
// - password: Hashed password
// - status: User status (active, inactive, banned)
// - metadata: JSON metadata storage
// - created_at: Creation timestamp
// - updated_at: Last update timestamp

// Usage examples:
$user = User::findById(1);
$user = User::findBy("identifier", "john_doe");
$user = User::findBy("email", "john@example.com");

// Create new user
$user = new User();
$user->identifier = "new_user";
$user->email = "user@example.com";
$user->password = password_hash("password", PASSWORD_BCRYPT);
$user->status = 'active';
$user->save();

Profile Model

// Profile model for extended user information
$profile = Profile::findBy("user_id", $userId);

// Create profile for user
$profile = new Profile();
$profile->user_id = $user->id;
$profile->first_name = "John";
$profile->last_name = "Doe";
$profile->bio = "Software developer";
$profile->save();

Middleware

Use ForgeAuth middleware to protect your routes and ensure only authenticated users can access certain areas.

Auth Middleware

use Forge\Core\Http\Attributes\Middleware;

#[Middleware('auth')]
class ProtectedController
{
    #[Route("/dashboard", "GET")]
    public function dashboard(): Response
    {
        // This route is protected by authentication
        $user = auth()->user();
        return $this->view('dashboard', ['user' => $user]);
    }
}

// Or apply to specific routes:
#[Route("/admin", "GET")]
#[Middleware('auth')]
public function adminPanel(): Response
{
    // Only authenticated users can access this
}

Custom Middleware

// Create custom middleware for role-based access
namespace App\Middleware;

use Forge\Core\Http\Request;
use Forge\Core\Http\Response;
use App\Modules\ForgeAuth\Contracts\ForgeAuthInterface;

class RoleMiddleware
{
    public function __construct(
        private ForgeAuthInterface $auth,
        private string $requiredRole
    ) {}

    public function handle(Request $request, callable $next): Response
    {
        $user = $this->auth->user();
        
        if (!$user || !$user->hasRole($this->requiredRole)) {
            return redirect('/')->with('error', 'Insufficient permissions');
        }

        return $next($request);
    }
}

Best Practices

Security Best Practices

  • • Always use HTTPS in production
  • • Implement proper session timeout
  • • Use strong password requirements
  • • Enable rate limiting
  • • Validate all user input

Configuration Tips

  • • Configure appropriate session lifetime
  • • Set up proper error handling
  • • Use environment variables for sensitive data
  • • Test rate limiting settings
  • • Monitor failed login attempts

Development Guidelines

  • • Always validate user credentials
  • • Handle authentication exceptions properly
  • • Use dependency injection for services
  • • Implement proper error messages
  • • Test authentication flows thoroughly

Important: Always keep your authentication system updated and monitor for security vulnerabilities. Regular security audits are recommended.