PHP code example of karelwintersky / arris.delight-php-auth

1. Go to this page and download the library: Download karelwintersky/arris.delight-php-auth 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/ */

    

karelwintersky / arris.delight-php-auth example snippets


     

// $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
// or
// $db = new \PDO('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password');
// or
// $db = new \PDO('sqlite:../Databases/my-database.sqlite');

// or

// $db = \Arris\DelightAuth\Db\PdoDatabase::fromDsn(new \Arris\DelightAuth\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'));
// or
// $db = \Arris\DelightAuth\Db\PdoDatabase::fromDsn(new \Arris\DelightAuth\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'));
// or
// $db = \Arris\DelightAuth\Db\PdoDatabase::fromDsn(new \Arris\DelightAuth\Db\PdoDsn('sqlite:../Databases/my-database.sqlite'));

$auth = new \Arris\DelightAuth\Auth\Auth($db);

try {
    $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
    });

    echo 'We have signed up a new user with the ID ' . $userId;
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Invalid password');
}
catch (\Arris\DelightAuth\Auth\Exceptions\UserAlreadyExistsException $e) {
    die('User already exists');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

if (\preg_match('/[\x00-\x1f\x7f\/:\\\\]/', $username) === 0) {
    // ...
}

$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

try {
    $auth->login($_POST['email'], $_POST['password']);

    echo 'User is logged in';
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Wrong email address');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Wrong password');
}
catch (\Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException $e) {
    die('Email not verified');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

try {
    $auth->confirmEmail($_GET['selector'], $_GET['token']);

    echo 'Email address has been verified';
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Arris\DelightAuth\Auth\Exceptions\UserAlreadyExistsException $e) {
    die('Email address already exists');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

if ($_POST['remember'] == 1) {
    // keep logged in for one year
    $rememberDuration = (int) (60 * 60 * 24 * 365.25);
}
else {
    // do not keep logged in after session ends
    $rememberDuration = null;
}

// ...

$auth->login($_POST['email'], $_POST['password'], $rememberDuration);

// ...

try {
    $auth->forgotPassword($_POST['email'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
    });

    echo 'Request has been generated';
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException $e) {
    die('Email not verified');
}
catch (\Arris\DelightAuth\Auth\Exceptions\ResetDisabledException $e) {
    die('Password reset is disabled');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

$url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

try {
    $auth->canResetPasswordOrThrow($_GET['selector'], $_GET['token']);

    echo 'Put the selector into a "hidden" field (or keep it in the URL)';
    echo 'Put the token into a "hidden" field (or keep it in the URL)';

    echo 'Ask the user for their new password';
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Arris\DelightAuth\Auth\Exceptions\ResetDisabledException $e) {
    die('Password reset is disabled');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) {
    echo 'Put the selector into a "hidden" field (or keep it in the URL)';
    echo 'Put the token into a "hidden" field (or keep it in the URL)';

    echo 'Ask the user for their new password';
}

try {
    $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);

    echo 'Password has been reset';
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Arris\DelightAuth\Auth\Exceptions\ResetDisabledException $e) {
    die('Password reset is disabled');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Invalid password');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

try {
    $auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);

    echo 'Password has been changed';
}
catch (\Arris\DelightAuth\Auth\Exceptions\NotLoggedInException $e) {
    die('Not logged in');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Invalid password(s)');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

try {
    if ($auth->reconfirmPassword($_POST['password'])) {
        $auth->changeEmail($_POST['newEmail'], function ($selector, $token) {
            echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email to the *new* address)';
        });

        echo 'The change will take effect as soon as the new email address has been confirmed';
    }
    else {
        echo 'We can\'t say if the user is who they claim to be';
    }
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Arris\DelightAuth\Auth\Exceptions\UserAlreadyExistsException $e) {
    die('Email address already exists');
}
catch (\Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException $e) {
    die('Account not verified');
}
catch (\Arris\DelightAuth\Auth\Exceptions\NotLoggedInException $e) {
    die('Not logged in');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

try {
    $auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
    });

    echo 'The user may now respond to the confirmation request (usually by clicking a link)';
}
catch (\Arris\DelightAuth\Auth\Exceptions\ConfirmationRequestNotFound $e) {
    die('No earlier request found that could be re-sent');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('There have been too many requests -- try again later');
}

try {
    $auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
    });

    echo 'The user may now respond to the confirmation request (usually by clicking a link)';
}
catch (\Arris\DelightAuth\Auth\Exceptions\ConfirmationRequestNotFound $e) {
    die('No earlier request found that could be re-sent');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('There have been too many requests -- try again later');
}

$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

$auth->logOut();

// or

try {
    $auth->logOutEverywhereElse();
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('Not logged in');
}

// or

try {
    $auth->logOutEverywhere();
}
catch (\Arris\DelightAuth\Auth\Exceptions\NotLoggedInException $e) {
    die('Not logged in');
}

$auth->destroySession();

if ($auth->isLoggedIn()) {
    echo 'User is signed in';
}
else {
    echo 'User is not signed in yet';
}

$id = $auth->getUserId();

$email = $auth->getEmail();

$username = $auth->getUsername();

if ($auth->isNormal()) {
    echo 'User is in default state';
}

if ($auth->isArchived()) {
    echo 'User has been archived';
}

if ($auth->isBanned()) {
    echo 'User has been banned';
}

if ($auth->isLocked()) {
    echo 'User has been locked';
}

if ($auth->isPendingReview()) {
    echo 'User is pending review';
}

if ($auth->isSuspended()) {
    echo 'User has been suspended';
}

if ($auth->isRemembered()) {
    echo 'User did not sign in but was logged in through their long-lived cookie';
}
else {
    echo 'User signed in manually';
}

$ip = $auth->getIpAddress();

    function getUserInfo(\Delight\Auth\Auth $auth) {
        if (!$auth->isLoggedIn()) {
            return null;
        }

        if (!isset($_SESSION['_internal_user_info'])) {
            // TODO: load your custom user information and assign it to the session variable below
            // $_SESSION['_internal_user_info'] = ...
        }

        return $_SESSION['_internal_user_info'];
    }
    

try {
    if ($auth->reconfirmPassword($_POST['password'])) {
        echo 'The user really seems to be who they claim to be';
    }
    else {
        echo 'We can\'t say if the user is who they claim to be';
    }
}
catch (\Arris\DelightAuth\Auth\Exceptions\NotLoggedInException $e) {
    die('The user is not signed in');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) {
    echo 'The user is a super moderator';
}

// or

if ($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
    echo 'The user is either a developer, or a manager, or both';
}

// or

if ($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
    echo 'The user is both a developer and a manager';
}

$auth->getRoles();

\Arris\DelightAuth\Auth\Role::ADMIN;
\Arris\DelightAuth\Auth\Role::AUTHOR;
\Arris\DelightAuth\Auth\Role::COLLABORATOR;
\Arris\DelightAuth\Auth\Role::CONSULTANT;
\Arris\DelightAuth\Auth\Role::CONSUMER;
\Arris\DelightAuth\Auth\Role::CONTRIBUTOR;
\Arris\DelightAuth\Auth\Role::COORDINATOR;
\Arris\DelightAuth\Auth\Role::CREATOR;
\Arris\DelightAuth\Auth\Role::DEVELOPER;
\Arris\DelightAuth\Auth\Role::DIRECTOR;
\Arris\DelightAuth\Auth\Role::EDITOR;
\Arris\DelightAuth\Auth\Role::EMPLOYEE;
\Arris\DelightAuth\Auth\Role::MAINTAINER;
\Arris\DelightAuth\Auth\Role::MANAGER;
\Arris\DelightAuth\Auth\Role::MODERATOR;
\Arris\DelightAuth\Auth\Role::PUBLISHER;
\Arris\DelightAuth\Auth\Role::REVIEWER;
\Arris\DelightAuth\Auth\Role::SUBSCRIBER;
\Arris\DelightAuth\Auth\Role::SUPER_ADMIN;
\Arris\DelightAuth\Auth\Role::SUPER_EDITOR;
\Arris\DelightAuth\Auth\Role::SUPER_MODERATOR;
\Arris\DelightAuth\Auth\Role::TRANSLATOR;

\Arris\DelightAuth\Auth\Role::getMap();
// or
\Arris\DelightAuth\Auth\Role::getNames();
// or
\Arris\DelightAuth\Auth\Role::getValues();

function canEditArticle(\Arris\DelightAuth\Auth\Auth $auth) {
    return $auth->hasAnyRole(
        \Arris\DelightAuth\Auth\Role::MODERATOR,
        \Arris\DelightAuth\Auth\Role::SUPER_MODERATOR,
        \Arris\DelightAuth\Auth\Role::ADMIN,
        \Arris\DelightAuth\Auth\Role::SUPER_ADMIN
    );
}

// ...

if (canEditArticle($auth)) {
    echo 'The user can edit articles here';
}

// ...

if (canEditArticle($auth)) {
    echo '... and here';
}

// ...

if (canEditArticle($auth)) {
    echo '... and here';
}

namespace My\Namespace;

final class MyRole {

    const CUSTOMER_SERVICE_AGENT = \Arris\DelightAuth\Auth\Role::REVIEWER;
    const FINANCIAL_DIRECTOR = \Arris\DelightAuth\Auth\Role::COORDINATOR;

    private function __construct() {}

}

\My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT;
// and
\My\Namespace\MyRole::FINANCIAL_DIRECTOR;

\Arris\DelightAuth\Auth\Role::REVIEWER;
// and
\Arris\DelightAuth\Auth\Role::COORDINATOR;

try {
    if ($auth->reconfirmPassword($_POST['password'])) {
        $auth->setPasswordResetEnabled($_POST['enabled'] == 1);

        echo 'The setting has been changed';
    }
    else {
        echo 'We can\'t say if the user is who they claim to be';
    }
}
catch (\Arris\DelightAuth\Auth\Exceptions\NotLoggedInException $e) {
    die('The user is not signed in');
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    die('Too many requests');
}

$auth->isPasswordResetEnabled();

try {
    // throttle the specified resource or feature to *3* requests per *60* seconds
    $auth->throttle([ 'my-resource-name' ], 3, 60);

    echo 'Do something with the resource or feature';
}
catch (\Arris\DelightAuth\Auth\Exceptions\TooManyRequestsException $e) {
    // operation cancelled

    \http_response_code(429);
    exit;
}

[ 'my-resource-name', $_SERVER['REMOTE_ADDR'] ]
// instead of
// [ 'my-resource-name' ]

try {
    $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']);

    echo 'We have signed up a new user with the ID ' . $userId;
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Invalid password');
}
catch (\Arris\DelightAuth\Auth\Exceptions\UserAlreadyExistsException $e) {
    die('User already exists');
}

try {
    $auth->admin()->deleteUserById($_POST['id']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownIdException $e) {
    die('Unknown ID');
}

try {
    $auth->admin()->deleteUserByEmail($_POST['email']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Unknown email address');
}

try {
    $auth->admin()->deleteUserByUsername($_POST['username']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}

try {
    $auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownIdException $e) {
    die('Unknown user ID');
}

// or

try {
    $auth->admin()->addRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Unknown email address');
}

// or

try {
    $auth->admin()->addRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}

try {
    $auth->admin()->removeRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownIdException $e) {
    die('Unknown user ID');
}

// or

try {
    $auth->admin()->removeRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Unknown email address');
}

// or

try {
    $auth->admin()->removeRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}

try {
    if ($auth->admin()->doesUserHaveRole($userId, \Delight\Auth\Role::ADMIN)) {
        echo 'The specified user is an administrator';
    }
    else {
        echo 'The specified user is not an administrator';
    }
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownIdException $e) {
    die('Unknown user ID');
}

$auth->admin()->getRolesForUserById($userId);

try {
    $auth->admin()->logInAsUserById($_POST['id']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownIdException $e) {
    die('Unknown ID');
}
catch (\Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException $e) {
    die('Email address not verified');
}

// or

try {
    $auth->admin()->logInAsUserByEmail($_POST['email']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidEmailException $e) {
    die('Unknown email address');
}
catch (\Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException $e) {
    die('Email address not verified');
}

// or

try {
    $auth->admin()->logInAsUserByUsername($_POST['username']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\EmailNotVerifiedException $e) {
    die('Email address not verified');
}

try {
    $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownIdException $e) {
    die('Unknown ID');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Invalid password');
}

// or

try {
    $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
}
catch (\Arris\DelightAuth\Auth\Exceptions\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}
catch (\Arris\DelightAuth\Auth\Exceptions\InvalidPasswordException $e) {
    die('Invalid password');
}

\session_name();

\Arris\DelightAuth\Auth\Auth::createRememberCookieName();

   \ini_set('session.name', 'session_v1');
   

   \session_name('session_v1');
   

   \ini_set('session.cookie_domain', 'example.com');
   

   \ini_set('session.cookie_path', '/');
   

   \ini_set('session.cookie_httponly', 1);
   

   \ini_set('session.cookie_secure', 1);
   

$length = 24;
$randomStr = \Arris\DelightAuth\Auth\Auth::createRandomString($length);

$uuid = \Arris\DelightAuth\Auth\Auth::createUuid();

function isPasswordAllowed($password) {
    if (\strlen($password) < 8) {
        return false;
    }

    $blacklist = [ 'password1', '123456', 'qwerty' ];

    if (\in_array($password, $blacklist)) {
        return false;
    }

    return true;
}

if (isPasswordAllowed($password)) {
    $auth->register($email, $password);
}

\header_remove('X-Frame-Options');

    $ composer