1. Go to this page and download the library: Download activecollab/authentication library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
activecollab / authentication example snippets
namespace MyApp;
class MyUsersRepository implements \ActiveCollab\Authentication\AuthenticatedUser\RepositoryInterface
{
/**
* {@inheritdoc}
*/
public function findById($user_id)
{
// Find and return user by ID
}
/**
* {@inheritdoc}
*/
public function findByUsername($username)
{
// Find and return user by username (can be an email address as well)
}
}
namespace MyApp;
use ActiveCollab\Authentication\Authorizer\AuthorizerInterface;
use ActiveCollab\Authentication\AuthenticatedUser\RepositoryInterface;
use ActiveCollab\Authentication\Exception\InvalidPasswordException;
use ActiveCollab\Authentication\Exception\UserNotFoundException;
use InvalidArgumentException;
class MyAuthorizer implements AuthorizerInterface
{
/**
* @var RepositoryInterface
*/
private $user_repository;
/**
* @param RepositoryInterface $user_repository
*/
public function __construct(RepositoryInterface $user_repository)
{
$this->user_repository = $user_repository;
}
/**
* {@inheritdoc}
*/
public function verifyCredentials(array $credentials)
{
if (empty($credentials['username'])) {
throw new InvalidArgumentException('Username not found in credentials array');
}
if (empty($credentials['password'])) {
throw new InvalidArgumentException('Password not found in credentials array');
}
$user = $this->user_repository->findByUsername($credentials['username']);
if (!$user) {
throw new UserNotFoundException();
}
if (!$user->isValidPassword($credentials['password'])) {
throw new InvalidPasswordException();
}
return $user;
}
}
namespace MyApp;
use ActiveCollab\Authentication\Authorizer\AuthorizerInterface;
use ActiveCollab\Authentication\Authorizer\RequestAware\RequestAwareInterface;
class MyAuthorizer implements AuthorizerInterface, RequestAwareInterface
{
/**
* {@inheritdoc}
*/
public function verifyCredentials(array $credentials)
{
}
/**
* {@inheritdoc}
*/
public function getRequestProcessor()
{
}
}
namespace MyApp;
use ActiveCollab\Authentication\Authorizer\AuthorizerInterface;
use ActiveCollab\Authentication\Authorizer\ExceptionAware\ExceptionAwareInterface;
use Exception;
class InvalidPasswordException extends Exception
{
}
class MyAuthorizer implements AuthorizerInterface, ExceptionAwareInterface
{
/**
* {@inheritdoc}
*/
public function verifyCredentials(array $credentials)
{
if ($this->shouldCoolDown($credentials)) {
return null;
}
if ($this->checkUserPassword($credentials['password'])) {
// Proceed with auth
} else {
throw new InvalidPasswordException('Password not valid.');
}
}
/**
* {@inheritdoc}
*/
public function handleException(array $credentials, $error_or_exception)
{
if ($error_or_exception instanceof InvalidPasswordException) {
$this->logPasswordFailure($credentials, $error_or_exception);
}
}
private function shouldCoolDown(array $credentials)
{
// Return true if incorrect password is entered multiple times, so user needs to wait before they can proceed.
}
private function logPasswordFailure(array $credentials, $error)
{
// Log
}
private function checkUserPassword(array $credentials)
{
// Check if user password is OK.
}
}
namespace MyApp;
use ActiveCollab\Authentication\Authorizer\AuthorizerInterface;
use ActiveCollab\Authentication\Authorizer\ExceptionAware\ExceptionHandler\ExceptionHandlerInterface;
use ActiveCollab\Authentication\Authorizer\LocalAuthorizer;
use Throwable;
class MyExceptionHandler implements ExceptionHandlerInterface
{
public function handleException(array $credentials, Throwable $error_or_exception): void
{
// Do something with an exception.
}
}
$local_authorizer = new LocalAuthorizer($user_repo, AuthorizerInterface::USERNAME_FORMAT_ALPHANUM, new MyExceptionHandler());
if (!$transport->isApplied()) {
list ($request, $response) = $transport->applyTo($request, $response);
}
namespace MyApp;
use ActiveCollab\Authentication\Authentication;
$auth = new Authentication([]);
$auth->onUserAuthorizationFailed(function(array $credentials) {
// Log attempt for user's username.
});
$auth->onUserAuthorizationFailed(function(array $credentials) {
// If third attempt, notify administrator that particular user has trouble logging in.
});
$auth->onUserAuthorizationFailed(function(array $credentials) {
// If fifth attempt, block IP address for a couple of minutes, to cool it down.
});
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* @package ActiveCollab\Authentication\Middleware
*/
class CheckAuthMiddleware
{
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
if (empty($request->getAttribute('authenticated_user'))) {
return $response->withStatus(401);
}
if ($next) {
$response = $next($request, $response);
}
return $response;
}
}
use ActiveCollab\Authentication\Middleware\ApplyAuthenticationMiddleware;
use ActiveCollab\ValueContainer\Request\RequestValueContainer;
$middleware_stack->add(new ApplyAuthenticationMiddleware(
new RequestValueContainer('authentication')
));
use ActiveCollab\Authentication\Middleware\ApplyAuthenticationMiddleware;
use ActiveCollab\ValueContainer\Request\RequestValueContainer;
$middleware_stack->add(new ApplyAuthenticationMiddleware(
new RequestValueContainer('authentication'),
true // Apply when exiting middleware stack.
));
$manager = new PasswordManager('global salt, if needed');
$hash = $manager->hash('easy to remember, hard to guess');
if ($manager->verify('easy to remember, hard to guess', $hash, PasswordManagerInterface::HASHED_WITH_PHP)) {
print "All good\n";
} else {
print "Not good\n";
}
$manager = new PasswordManager('global salt, if needed');
if ($manager->verify($user_provided_password, $hash_from_storage, PasswordManagerInterface::HASHED_WITH_PHP)) {
if ($manager->needsRehash($hash_from_storage, PasswordManagerInterface::HASHED_WITH_PHP)) {
// Update hash in our data storage
}
// Proceed with user authentication
} else {
print "Invalid password\n";
}
(new PasswordStrengthValidator())->isPasswordValid('weak', new PasswordPolicy()); // Will return TRUE
// Weak password, not accepted
(new PasswordStrengthValidator())->isPasswordValid('weak', new PasswordPolicy(32, true, true, true));
// Strong password, accepted
(new PasswordStrengthValidator())->isPasswordValid('BhkXuemYY#WMdU;QQd4QpXpcEjbw2XHP', new PasswordPolicy(32, true, true, true));
$validator = new PasswordStrengthValidator();
$policy = new PasswordPolicy(32, true, true, true);
// Prepare 32 characters long password that mixes case, numbers and symbols
$password = $validator->generateValidPassword(32, $policy);