PHP code example of mityay2004 / delight-im_auth

1. Go to this page and download the library: Download mityay2004/delight-im_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/ */

    

mityay2004 / delight-im_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 = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
// or
// $db = new \Delight\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password');
// or
// $db = new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite');

$auth = new \Delight\Auth\Auth($db);

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

    // we have signed up a new user with the ID `$userId`
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // invalid email address
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    // user already exists
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

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

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

    // user is logged in
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // wrong email address
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // wrong password
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    // email not verified
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

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

    // email address has been verified
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    // invalid token
}
catch (\Delight\Auth\TokenExpiredException $e) {
    // token expired
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    // email address already exists
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // 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) {
        // send `$selector` and `$token` to the user (e.g. via email)
    });

    // request has been generated
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // invalid email address
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    // email not verified
}
catch (\Delight\Auth\ResetDisabledException $e) {
    // password reset is disabled
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

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

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

    // put the selector into a `hidden` field (or keep it in the URL)
    // put the token into a `hidden` field (or keep it in the URL)

    // ask the user for their new password
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    // invalid token
}
catch (\Delight\Auth\TokenExpiredException $e) {
    // token expired
}
catch (\Delight\Auth\ResetDisabledException $e) {
    // password reset is disabled
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) {
    // put the selector into a `hidden` field (or keep it in the URL)
    // put the token into a `hidden` field (or keep it in the URL)

    // ask the user for their new password
}

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

    // password has been reset
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    // invalid token
}
catch (\Delight\Auth\TokenExpiredException $e) {
    // token expired
}
catch (\Delight\Auth\ResetDisabledException $e) {
    // password reset is disabled
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

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

    // password has been changed
}
catch (\Delight\Auth\NotLoggedInException $e) {
    // not logged in
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password(s)
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

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

        // the change will take effect as soon as the new email address has been confirmed
    }
    else {
        // we can't say if the user is who they claim to be
    }
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // invalid email address
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    // email address already exists
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    // account not verified
}
catch (\Delight\Auth\NotLoggedInException $e) {
    // not logged in
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

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

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

    // the user may now respond to the confirmation request (usually by clicking a link)
}
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
    // no earlier request found that could be re-sent
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // there have been too many requests -- try again later
}

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

    // the user may now respond to the confirmation request (usually by clicking a link)
}
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
    // no earlier request found that could be re-sent
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // 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) {
    // not logged in
}

// or

try {
    $auth->logOutEverywhere();
}
catch (\Delight\Auth\NotLoggedInException $e) {
    // not logged in
}

$auth->destroySession();

if ($auth->isLoggedIn()) {
    // user is signed in
}
else {
    // user is *not* signed in yet
}

$id = $auth->getUserId();

$email = $auth->getEmail();

$email = $auth->getUsername();

if ($auth->isNormal()) {
    // user is in default state
}

if ($auth->isArchived()) {
    // user has been archived
}

if ($auth->isBanned()) {
    // user has been banned
}

if ($auth->isLocked()) {
    // user has been locked
}

if ($auth->isPendingReview()) {
    // user is pending review
}

if ($auth->isSuspended()) {
    // user has been suspended
}

if ($auth->isRemembered()) {
    // user did not sign in but was logged in through their long-lived cookie
}
else {
    // 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'])) {
        // the user really seems to be who they claim to be
    }
    else {
        // we can't say if the user is who they claim to be
    }
}
catch (\Delight\Auth\NotLoggedInException $e) {
    // the user is not signed in
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // too many requests
}

if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) {
    // the user is a super moderator
}

// or

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

// or

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

$auth->getRoles();

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

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

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

// ...

if (canEditArticle($auth)) {
    // the user can edit articles here
}

// ...

if (canEditArticle($auth)) {
    // ... and here
}

// ...

if (canEditArticle($auth)) {
    // ... and here
}

namespace My\Namespace;

final class MyRole {

    const CUSTOMER_SERVICE_AGENT = \Delight\Auth\Role::REVIEWER;
    const FINANCIAL_DIRECTOR = \Delight\Auth\Role::COORDINATOR;

    private function __construct() {}

}

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

\Delight\Auth\Role::REVIEWER;
// and
\Delight\Auth\Role::COORDINATOR;

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

        // the setting has been changed
    }
    else {
        // we can't say if the user is who they claim to be
    }
}
catch (\Delight\Auth\NotLoggedInException $e) {
    // the user is not signed in
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // 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);

    // do something with the resource or feature
}
catch (\Delight\Auth\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']);

    // we have signed up a new user with the ID `$userId`
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // invalid email address
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    // user already exists
}

try {
    $auth->admin()->deleteUserById($_POST['id']);
}
catch (\Delight\Auth\UnknownIdException $e) {
    // unknown ID
}

try {
    $auth->admin()->deleteUserByEmail($_POST['email']);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // unknown email address
}

try {
    $auth->admin()->deleteUserByUsername($_POST['username']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    // unknown username
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    // ambiguous username
}

try {
    $auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownIdException $e) {
    // unknown user ID
}

// or

try {
    $auth->admin()->addRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // unknown email address
}

// or

try {
    $auth->admin()->addRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    // unknown username
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    // ambiguous username
}

try {
    $auth->admin()->removeRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownIdException $e) {
    // unknown user ID
}

// or

try {
    $auth->admin()->removeRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // unknown email address
}

// or

try {
    $auth->admin()->removeRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    // unknown username
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    // ambiguous username
}

try {
    if ($auth->admin()->doesUserHaveRole($userId, \Delight\Auth\Role::ADMIN)) {
        // the specified user is an administrator
    }
    else {
        // the specified user is *not* an administrator
    }
}
catch (\Delight\Auth\UnknownIdException $e) {
    // unknown user ID
}

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

try {
    $auth->admin()->logInAsUserById($_POST['id']);
}
catch (\Delight\Auth\UnknownIdException $e) {
    // unknown ID
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    // email address not verified
}

// or

try {
    $auth->admin()->logInAsUserByEmail($_POST['email']);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // unknown email address
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    // email address not verified
}

// or

try {
    $auth->admin()->logInAsUserByUsername($_POST['username']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    // unknown username
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    // ambiguous username
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    // email address not verified
}

try {
    $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
}
catch (\Delight\Auth\UnknownIdException $e) {
    // unknown ID
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}

// or

try {
    $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    // unknown username
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    // ambiguous username
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}

\session_name();

\Delight\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 = \Delight\Auth\Auth::createRandomString($length);

$uuid = \Delight\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');