brammo/auth

Authentication plugin for CakePHP

Maintainers

Package info

github.com/brammo/auth

Type:cakephp-plugin

pkg:composer/brammo/auth

Statistics

Installs: 12

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.1.0 2025-11-27 12:43 UTC

This package is auto-updated.

Last update: 2026-04-20 14:51:13 UTC


README

A comprehensive authentication plugin for CakePHP 5.x applications, providing user authentication, login/logout functionality, and configurable authentication services.

License: MIT CakePHP PHP Version

Features

  • Complete Authentication System - Login/logout functionality out of the box
  • User Status Management - Built-in support for user status (active, new, blocked) with configurable finders
  • Highly Configurable - Customize routes, templates, password hashers, and more
  • Secure - Uses CakePHP's authentication library with bcrypt password hashing
  • Flexible - Easy to integrate into existing applications

Requirements

  • PHP 8.1 or higher
  • CakePHP 5.0 or higher
  • CakePHP Authentication 3.0 or higher

Installation

Install the plugin using Composer:

composer require brammo/auth

Load the plugin in your application's src/Application.php:

public function bootstrap(): void
{
    parent::bootstrap();
    
    $this->addPlugin('Brammo/Auth');
}

Configuration

Basic Setup

The plugin comes with sensible defaults, but you can customize it by creating a configuration file at config/auth.php in your application:

<?php
return [
    'Auth' => [
        'Users' => [
            'table' => 'Users',  // Your users table
            'controller' => 'Users',  // Your users controller
        ],
        'Routes' => [
            'login' => '/login',
            'logout' => '/logout',
            'loginRedirect' => '/',
        ],
        'Authentication' => [
            'fields' => [
                'username' => 'email',
                'password' => 'password',
            ],
            'passwordHasher' => [
                'className' => 'Authentication.Default',
            ],
            'sessionKey' => 'Auth',       // Change when using multiple instances
            'cookieName' => 'CookieAuth', // Change when using multiple instances
        ],
        'Templates' => [
            'login' => 'Users/login',  // Your login template
        ],
    ],
];

Authentication Middleware

Add the Authentication middleware to your application's middleware queue in src/Application.php:

use Authentication\Middleware\AuthenticationMiddleware;
use Brammo\Auth\AuthenticationServiceProvider;

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
    $middlewareQueue
        // ... other middleware
        ->add(new AuthenticationMiddleware(new AuthenticationServiceProvider()))

    return $middlewareQueue;
}

Database Schema

The plugin includes migrations to create the users table. Run the migrations:

# Run migrations from the plugin
bin/cake migrations migrate -p Brammo/Auth

# Or seed with sample users (for development/testing)
bin/cake migrations seed -p Brammo/Auth --seed UsersSeed

The migration creates a users table with the following structure:

  • id - Primary key
  • name - User's display name (optional)
  • email - Unique email address (required)
  • password - Hashed password (required)
  • status - User status: 'active', 'new', or 'blocked' (default: 'new')
  • created - Timestamp of creation
  • modified - Timestamp of last modification

Sample users created by the seed:

  • Admin User: email: admin@example.com, password: admin123
  • Test User: email: user@example.com, password: password

Alternatively, create the table manually:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'new',
    created DATETIME,
    modified DATETIME
);

Or use CakePHP's bake command:

bin/cake bake migration CreateUsers name:string email:string:unique password:string created modified
bin/cake migrations migrate

Usage

Login Template

The plugin provides simple login form template. You can create a custom login template at templates/Users/login.php (or your configured path):

<?php
/**
 * @var \App\View\AppView $this
 */
?>
<div class="users form">
    <?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your email and password') ?></legend>
        <?= $this->Form->control('email', ['required' => true]) ?>
        <?= $this->Form->control('password', ['required' => true]) ?>
    </fieldset>
    <?= $this->Form->submit(__('Login')); ?>
    <?= $this->Form->end() ?>
</div>

Controller Usage

The plugin provides a UserController with login and logout actions. You can extend or override it:

namespace App\Controller;

use Brammo\Auth\Controller\UserController as BrammoUserController;

class UsersController extends BrammoUserController
{
    // Override or extend as needed
}

Protecting Routes

In your controllers, use the Authentication component to protect actions:

public function beforeFilter(\Cake\Event\EventInterface $event)
{
    parent::beforeFilter($event);
    
    // Allow unauthenticated access to specific actions
    $this->Authentication->allowUnauthenticated(['index', 'view']);
}

Checking Authentication

Check if a user is authenticated:

$user = $this->Authentication->getIdentity();
if ($user) {
    // User is logged in
    $email = $user->email;
}

In templates:

<?php if ($this->Identity->isLoggedIn()): ?>
    <p>Welcome, <?= h($this->Identity->get('name')) ?>!</p>
    <?= $this->Html->link('Logout', ['controller' => 'Users', 'action' => 'logout']) ?>
<?php else: ?>
    <?= $this->Html->link('Login', ['controller' => 'Users', 'action' => 'login']) ?>
<?php endif; ?>

Advanced Configuration

Custom Password Hashers

Use legacy password hashers or multiple hashers:

'Authentication' => [
    'passwordHasher' => [
        'className' => 'Authentication.Fallback',
        'hashers' => [
            'Authentication.Default',
            [
                'className' => 'Authentication.Legacy',
                'hashType' => 'sha1',
            ],
        ],
    ],
],

Custom Login Redirect

Redirect users to different locations after login:

// In your login URL /login?redirect=/dashboard

// Or configure default in config/auth.php
'Routes' => [
    'loginRedirect' => '/dashboard',
],

Cookie-Based Authentication

The plugin includes cookie-based authentication by default. Configure it in your Authentication service if needed.

Multiple Instances (Frontend & Admin)

When using the plugin in multiple parts of the same application (e.g., a frontend and an admin panel), you need separate session keys and cookie names to avoid conflicts between authenticated users.

Configure sessionKey and cookieName per context in your application's config/auth.php:

// Admin plugin configuration (e.g., in plugins/Admin/config/bootstrap.php)
Configure::write('Auth', [
    'Authentication' => [
        'sessionKey' => 'AdminAuth',
        'cookieName' => 'AdminCookieAuth',
    ],
    'Routes' => [
        'login' => '/admin/login',
        'logout' => '/admin/logout',
        'loginRedirect' => '/admin',
    ],
]);

Each instance of AuthenticationServiceProvider will use its own session and cookie, so users can be logged into the frontend and admin areas independently.

Option Default Description
Auth.Authentication.sessionKey Auth Session key for storing user identity
Auth.Authentication.cookieName CookieAuth Name of the "remember me" cookie

User Status

The plugin supports user status management with three built-in statuses:

  • active - User can log in
  • new - Newly registered user (default), cannot log in until activated
  • blocked - Blocked user, cannot log in

Configure the authentication finder to only allow active users:

// In config/auth.php
'Authentication' => [
    'finder' => 'active',  // Only allow active users to log in
],

Configure custom error messages for blocked and inactive users:

// In config/auth.php
'Messages' => [
    'invalidCredentials' => 'Invalid email or password',
    'blocked' => 'Your account has been blocked. Please contact support.',
    'notActivated' => 'Your account is not yet activated. Please check your email.',
],

Use status constants in your code:

use Brammo\Auth\Model\Entity\User;

// Check user status
if ($user->isActive()) {
    // User is active
}

if ($user->isBlocked()) {
    // User is blocked
}

// Set user status
$user->status = User::STATUS_ACTIVE;
$user->status = User::STATUS_NEW;
$user->status = User::STATUS_BLOCKED;

Query only active users:

$activeUsers = $this->Users->find('active')->all();

Testing

Run the test suite:

composer test

Run static analysis with PHPStan:

composer stan

Run static analysis with Psalm:

composer psalm

Run all static analysis tools:

composer analyse

Check code style:

composer cs-check

Fix code style issues:

composer cs-fix

Run all checks:

composer check

API Documentation

Plugin Class

The main plugin class handles:

  • Loading plugin configuration
  • Registering authentication routes
  • Bootstrap process

AuthenticationServiceProvider

Provides the authentication service with:

  • Session authenticator
  • Form authenticator
  • Cookie authenticator
  • Password identifier with ORM resolver

UserController

Handles authentication actions:

  • login() - Display login form and process authentication
  • logout() - Log out user and redirect to login

User Entity

Represents a user with:

  • Hidden password field in JSON output
  • Mass-assignable fields (email, password, name, status)
  • Status constants: STATUS_ACTIVE, STATUS_NEW, STATUS_BLOCKED
  • Helper methods: isActive(), isBlocked()

UsersTable

Manages user data with:

  • Email validation
  • Unique email constraint
  • Timestamp behavior
  • Validation rules
  • findActive() finder for querying active users only
  • Status validation (active, new, blocked)

Troubleshooting

Users Not Authenticating

  1. Ensure password is hashed correctly:
$user = $this->Users->newEntity([
    'email' => 'user@example.com',
    'password' => 'plaintext',  // Will be hashed automatically
]);
  1. Check that Authentication middleware is loaded
  2. Verify configuration matches your database schema

Redirect Loop

Ensure login action is allowed for unauthenticated users:

public function beforeFilter(\Cake\Event\EventInterface $event)
{
    parent::beforeFilter($event);
    $this->Authentication->allowUnauthenticated(['login']);
}

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

Support

For issues, questions, or contributions, please visit:

Changelog

Version 1.2.0

  • Added Auth.Authentication.sessionKey config option for custom session keys
  • Added Auth.Authentication.cookieName config option for custom cookie names
  • Support for using the plugin in multiple contexts (e.g., frontend and admin)
  • Added Auth.Authentication.rehashPasswords config option to control password rehashing
  • Fixed PHPStan and Psalm errors

Version 1.1.0

  • Added user status field with values: 'active', 'new', 'blocked'
  • Added findActive() finder to query only active users
  • Added configurable authentication finder
  • Added configurable error messages for blocked/inactive users
  • Added status helper methods on User entity (isActive(), isBlocked())
  • Added status validation
  • Added migration for status field

Version 1.0.0

  • Initial release
  • Complete authentication system
  • Login/logout functionality
  • Configurable routes and templates
  • Password rehashing support
  • Comprehensive test suite