brammo / auth
Authentication plugin for CakePHP
Installs: 8
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
Type:cakephp-plugin
pkg:composer/brammo/auth
Requires
- php: >=8.1
- cakephp/authentication: ^3.0
- cakephp/cakephp: ^5.0
- cakephp/migrations: ^4.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^5.0
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.0
- vimeo/psalm: ^5.0
This package is auto-updated.
Last update: 2025-11-27 12:48:39 UTC
README
A comprehensive authentication plugin for CakePHP 5.x applications, providing user authentication, login/logout functionality, and configurable authentication services.
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', ], ], '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 keyname- 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 creationmodified- 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.
User Status
The plugin supports user status management with three built-in statuses:
active- User can log innew- Newly registered user (default), cannot log in until activatedblocked- 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 authenticationlogout()- 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
- Ensure password is hashed correctly:
$user = $this->Users->newEntity([ 'email' => 'user@example.com', 'password' => 'plaintext', // Will be hashed automatically ]);
- Check that Authentication middleware is loaded
- 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:
- Fork the repository
- Create a feature branch
- Write tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Credits
- Author: Roman Sidorkin
- Email: roman.sidorkin@gmail.com
- Built with: CakePHP and CakePHP Authentication
Support
For issues, questions, or contributions, please visit:
Changelog
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