PHP code example of odevnet / dulceauth

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

    

odevnet / dulceauth example snippets




$configPath = __DIR__ . '/config/config.php'; // 



// Define the project base route
define('BASE_PATH', dirname(__DIR__, 1)); // Return to the root of the project from src/config/

// Define common constants here
define('WEB_PAGE', 'yourwebsite.com'); // without http(s), without www and without ending in /
// some examples: define('WEB_PAGE', 'yourwebsite.com'); or define('WEB_PAGE', 'yourwebsite.com/myFolder');
define('EMAIL_FROM', '[email protected]');

// Error log
define('LOG_FILE', BASE_PATH . '/logs/log_file.log'); // IF IT DOES NOT EXIST, CREATE IT OR ESTABLISH A DIRECTORY AND FILE OF YOUR PREFERENCE

// A little configuration about emails...
define('JSON_FILE_VERIFICATION_EMAIL', BASE_PATH . '/config/verification_email.json'); // json template for verification email. Edit the text as you like
define('FORGOT_PASSWORD_PAGE', 'forgot.php'); // default file where the email data (token and user id) is captured
define('JSON_FILE_FORGOT_PASSWORD_EMAIL', BASE_PATH . '/config/forgot_password_email.json'); // json template for forgotten password email. Edit the text as you like
define('VERIFICATION_PAGE', 'verification.php'); // default file where the verification email data is captured

// Roles. At the moment do not modify anything!!
define('DEFAULT_ROLE', 'User'); // default role
define('DEFAULT_VISIBILITY', 'public'); // default profile visibility

// Accounts
define('VERIFIED', '0'); // 0 = unverified account, 

try {
    // ... code
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
}

try {
    $dulceAuth->register('Test', '[email protected]', '1234');
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}


$dulceAuth->register('Test', '[email protected]', '1234', ['country' => 'España']);

$dulceAuth->register('Test', '[email protected]', '1234', ['verified' => 1]);

$dulceAuth->register('Test', '[email protected]', '1234', ['verified' => 1, 'visibility' => 'private', 'country' => 'España']);

$count = 3;

for ($i = 1; $i <= $count; $i++) {
    try {

        $configPath = __DIR__ . '/config/config.php';

        $dulceAuth = new src\DulceAuth($configPath);

        $register = $dulceAuth->register("Test$i", "[email protected]", "1234", ["verified" => 1]);
        echo "User test$i registered successfully.\n";
        var_dump($register);
    } catch (Exception $ex) {
        echo "Error registering the user {$i}: {$ex->getMessage()}\n";
        Logger::error($ex->getMessage(), $ex->getTraceAsString());
    }
}

define('VERIFIED', '0'); // 0 = unverified account, 

$dulceAuth->register('Test', '[email protected]', '1234', ['verified' => 1]);

$token = $_GET['token'];
$userId = $_GET['userId'];

if ($dulceAuth->validateTokenAccount($token, $userId)) {
    // If the token is validated successfully, we verify the user's account by setting
    // the "verified" field value to 1
    $dulceAuth->verified($userId);
}

try {
    $token = $_GET['token'];
    $userId = $_GET['userId'];

    if ((!empty($token) && isset($token)) && (!empty($userId) && isset($userId))) {
        if ($dulceAuth->validateTokenAccount($token, $userId)) {
            echo 'Account verified';
            $dulceAuth->verified($userId);
        }
    } else {
        echo 'The token or userID is empty';
    }
} catch (RelationShipTokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenExpiredException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $token = $_GET['token'];
    $userId = $_GET['userId'];

    if ((!empty($token) && isset($token)) && (!empty($userId) && isset($userId))) {
        if ($dulceAuth->validateTokenAccount($token, $userId)) {
            echo 'Account verified';
            $dulceAuth->verified($userId);
        }
    } else {
        echo 'The token or userID is empty';
    }
} catch (TokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $verification = $dulceAuth->generateVerificationToken('[email protected]');
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RuntimeException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (InvalidArgumentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

$verification = $dulceAuth->generateVerificationToken('[email protected]', false); // return ['userId' => $userId, 'token' => $token];

try {
    $verification = $dulceAuth->generateVerificationToken('[email protected]', false);

    if ($verification) {

        $mail = $dulceAuth->dulceMail();
        $mail->from('[email protected]')
            ->to('[email protected]')
            ->subject('Validate your account')
            ->message("Click on the following link:
            yourwebsite.com/verification.php?token=" . $verification['token'] . "&userId=" . $verification['userId'] . "
            to validate your account and be able to login.");
        $mail->send();

        if ($mail->send()) {
            echo "We have just sent you an email to confirm your account.
        Please check your email.";
        }
    }
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RuntimeException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (InvalidArgumentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

$dulceAuth->login('[email protected]', '1234');

$dulceAuth->isLoggedIn();

if ($dulceAuth->isLoggedIn()) {
        echo "You are logged in!";
    }

$dulceAuth->logout();

$dulceAuth->currentUser()->name;

$dulceAuth->currentUser()->country;

foreach ($dulceAuth->showUsers() as $user) {
        echo 'ID: ' . $user->id . '<br>';
        echo 'Name: ' . $user->name . '<br>';
        echo 'Email: ' . $user->email . '<br>';
        echo 'Country: ' . $user->country . '<br>';
    }

$dulceAuth->showUsersById();

$dulceAuth->showUsersByName();

$dulceAuth->showUsersByEmail();

$dulceAuth->userIdExists(5); // check if a user with ID 5 exists

$dulceAuth->userEmailExists('[email protected]');

try {
    $dulceAuth->editUser(1, [
        'name' => 'Test',
        'email' => '[email protected]',
        'country' => 'Spain'
    ]);
} catch (EditUserException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (ArrayOptionsUserException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->editUser(1, [
        'name' => 'Test',
        'email' => '[email protected]',
        'country' => 'Spain'
    ]);
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->deleteUser(1);
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->createUser('Test', '[email protected]', '1234', [
        'verified' => 1,
        'phone' => '6XXXXXXXX'
    ]);
} catch (DuplicateEmailException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (CreateUserException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->changePassword(1, '1234', '1234da#');
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    echo $dulceAuth->latestChange(1)->changes_count;
} catch (LimitChangesPasswordException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $forgotPassword = $dulceAuth->forgotPassword('[email protected]');
} catch (TokenSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RuntimeException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (InvalidArgumentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

$forgotPassword = $dulceAuth->forgotPassword('[email protected]', false); // return ['userId' => $userId, 'token' => $token];

$forgotPassword = $dulceAuth->forgotPassword('[email protected]');

$token = $_GET['token'];
$userId = $_GET['userId'];

if ($dulceAuth->validateTokenPassword($token, $userId)) {
    // If it has been validated successfully, here you can display a form to enter the new password...
}

try {
    $token = $_GET['token'];
    $userId = $_GET['userId'];

    if ((!empty($token) && isset($token)) && (!empty($userId) && isset($userId))) {
        if ($dulceAuth->validateTokenPassword($token, $userId)) {
            $dulceAuth->insertNewPassword('new password', $userId);
            echo 'Password changed successfully';
        }
    } else {
        echo 'The token or userID is empty';
    }
} catch (RelationShipTokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenExpiredException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (TokenException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $forgotPassword = $dulceAuth->forgotPassword('[email protected]', false); // return ['userId' => $userId, 'token' => $token];
    // We check that `$forgotPassword` returns the userId and the token.
    if ($forgotPassword) {
        $mail = $dulceAuth->dulceMail();
        $mail->from('[email protected]')
            ->to('[email protected]')
            ->subject('Password Regeneration')
            ->message("You received this email because you forgot your password and a token has been generated to reset it.
        Click on the following link: yourwebsite.com/forgot.php?token=" . $forgotPassword['token'] . "&userId=" . $forgotPassword['userId'] . " \n
        If it wasn't you, please contact administration urgently as your account may be at risk.");
        $mail->send();
        // If the sending is successful, we can display a message in the browser.
        if ($mail->send()) {
            echo "We have just sent you an email.
        Please check your email to create a new password that you will remember.";
        }
    }
} catch (TokenSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RuntimeException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (InvalidArgumentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->createRole('new_role_name');
} catch (EmptyRoleNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RoleSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UsedRoleNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->createRole('new_role_name');
} catch (RolesException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->editRole(10, 'new_name');
} catch (RoleNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (EmptyRoleNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UsedRoleNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RoleSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $dulceAuth->editRole(10, 'new_name');
} catch (RolesException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $eliminarRol = $dulceAuth->deleteRole(8);
    if ($eliminarRol) {
        echo 'Role successfully deleted...';
    }
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $asignarRol = $dulceAuth->assignRoleToUser(27, [4, 5, 7]);
    if ($asignarRol) {
        echo 'Role(s) successfully assigned.';
    }
} catch (RoleNotSelectedException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RoleAssignmentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $eliminarRol = $dulceAuth->removeRoleToUser(27, [2, 7]);
    if ($eliminarRol) {
        echo 'Role(s) successfully removed from the user.';
    }
} catch (RoleNotSelectedException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RoleNotAssignedException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $newPermission = $dulceAuth->createPermission('Post news', 'Allows you to publish news on the site');
    if ($newPermission) {
        echo 'Permission created successfully!';
    }
} catch (EmptyPermissionNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UsedPermissionNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (PermissionSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $editPermission = $dulceAuth->editPermission(13, 'Post article');
    if ($editPermission) {
        echo 'Permission edited successfully!';
    }
} catch (InvalidArgumentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (EmptyPermissionNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (UsedPermissionNameException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (PermissionSaveException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (PermissionNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}


try {
    $editPermission = $dulceAuth->editPermission(13, 'Post article');
    if ($editPermission) {
        echo 'Permission edited successfully!';
    }
} catch (Exception $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $removePermission = $dulceAuth->deletePermission(13);
    if ($removePermission) {
        echo 'Permission removed successfully!';
    }
} catch (PermissionNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $assignPermissionToRole = $dulceAuth->assignPermissionToRole(4, 14);
    if ($assignPermissionToRole) {
        echo 'Permission successfully assigned to role';
    }
} catch (MissingRoleOrPermissionException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RoleNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (PermissionNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RolePermissionAlreadyExistsException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

try {
    $removeRolePermission = $dulceAuth->removePermissionFromRole(4, 14);
    if ($removeRolePermission) {
        echo 'Permission successfully REMOVED from the role';
    }
} catch (MissingRoleOrPermissionException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (RoleNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (PermissionNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

$roles = $dulceAuth->showRoles();

foreach ($roles as $role) {
    echo "ROLE ID: $role->id | NAME: $role->name <br>";
}

$permissions = $duleAuth->showPermissions();

foreach ($permissions as $permission) {
    echo "PERMISSION ID: $permission->id | PERMISSION NAME: $permission->name <br>";
}

try {
    $roles = $dulceAuth->userRoles(2);
    echo 'The user with ID 2 has the following roles: <br>';
    foreach ($roles as $role) {
        echo "ROLE: $role->name <br>";
    }
} catch (UserNotFoundException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

if ($dulceAuth->hasRole('Admin')) {
    echo 'You are an administrator.';
    // Here you can add an administration area or anything else...
} else {
    echo 'You do not have the ole('Admin')) {
        echo 'You are an administrator.';
        // Here you can add an administration area or anything else...
    } else {
        echo 'You do not have the 

if ($dulceAuth->hasRole('SuperAdmin', 1)) {
    echo 'The user has the role!';
} else {
    echo 'The user does not have the role! :-(';
}

if ($dulceAuth->hasPermission('Create user')) {
    echo 'You have the necessary permission to create users.';
} else {
    echo 'You do not have permission to perform this action.';
}

$dulceAuth->session()->set('color', 'red');

echo $dulceAuth->session()->get('color');

$dulceAuth->session()->has('color'); // returns true or false

if ($dulceAuth->session()->has('color')) {
    echo 'It exists!';
} else {
    echo 'It does not exist!';
}

$dulceAuth->session()->remove('name');

$dulceAuth->session()->destroy(); // destroys the entire session.

echo $dulceAuth->session()->get('userId');

$dulceAuth->session()->get('expire_time');

echo $dulceAuth->session()->expirationTime(); // displays time in format: Y-m-d H:i:s

if ($dulceAuth->session()->isValid()) {
        echo 'The session is active';
        // We can do anything here...
    } else {
        echo 'The session has expired';
    }

$mail = $dulceAuth->dulceMail();
// We prepare the email: sender, recipient, subject and message
$mail->from('[email protected]')->to('[email protected]')->subject('Subject/topic')->message('Any message...');
// and we send it
$mail->send();

try {
    $mail = $dulceAuth->dulceMail();

    $mail->from('[email protected]')->to('[email protected]')->subject('Subject/topic')->message('Any message...');

    $send = $mail->send();
    // If the sending is successful, we can display a message in the browser.
    if ($send) {
        echo 'We just sent you an email.';
    }
} catch (RuntimeException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
} catch (InvalidArgumentException $ex) {
    Logger::error($ex->getMessage(), $ex->getTraceAsString());
    echo $ex->getMessage();
}

$dulceAuth->dulce->addService('Name of the service', function ($dulce) {
    return new espacioDeNombres\Servicio();
});

$dulceAuth->dulce->addService('Forms', function ($dulce) {
    return new helpers\Form();
});

echo $dulceAuth->dulce->get('Forms');
yourwebsite.com/verification.php?token=TOKENGENERADO&userId=IDUSUARIO
yourwebsite.com/verification.php?token=GENERATEDTOKEN&userId=USERID
editUser(int $userId, array $options)