PHP code example of casdoor / casdoor-php-sdk

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

    

casdoor / casdoor-php-sdk example snippets


use Casdoor\Client;

$client = new Client(
    endpoint: 'http://localhost:8000',
    clientId: '<client-id>',
    clientSecret: '<client-secret>',
    certificate: file_get_contents('/path/to/cert.pem'),
    organizationName: 'my-organization',
    applicationName: 'my-application',
);

$users = $client->getUsers();
echo 'Found ' . count($users) . " users\n";

$client->setCustomHeaders([
    'Accept-Language' => 'de',     // localized error messages
    'X-Trace-ID'      => 'trace-abc-123',
]);

header('Location: ' . $client->getSigninUrl('http://localhost:8080/callback'));

$token  = $client->getOAuthToken($_GET['code'], $_GET['state']);
$claims = $client->parseJwtToken($token->getToken());

echo $claims['name'], $claims['email'], $claims['owner'];

// e.g. save the user in the session
$_SESSION['user'] = $claims;

// Resource Owner Password Credentials grant, the application must enable the "Password" grant type
$token = $client->getOAuthTokenByPassword('alice', 'password');

// Sign in as any user of the organization with the organization's master password
$token = $client->impersonateUser('alice', '<master password>');

$newToken = $client->refreshOAuthToken($token->getRefreshToken());

$result = $client->introspectToken($token->getToken(), 'access_token');

$userClient = $client->withAccessToken($token->getToken());

// "Who am I"
$account = $userClient->getAccount();

// Any other API can be called in the same way
$users = $userClient->getUsers();

$client->logout($accessToken);                // sign the user out of all the applications and devices (SSO logout)
$client->logoutCurrentSession($accessToken);  // only sign out the session of this access token

$client->getRole('my-role');            // "my-organization/my-role"
$client->getRole('other-org/my-role');  // "other-org/my-role"

$role        = new Casdoor\Role();
$role->owner = 'other-org';
$role->name  = 'my-role';
$client->addRole($role);                // created in "other-org"

use Casdoor\User;

$client->getUsers();
[$users, $total] = $client->getPaginationUsers(1, 10);
$client->getUser('alice');
$client->getUserByEmail('[email protected]');
$client->getUserByPhone('2025550123');
$client->getUserByUserId('<user id>');
$client->getSortedUsers('created_time', 10);
$client->getGlobalUsers();     // users of all organizations
$client->getUserCount('1');    // '1' for online users, '0' for offline users, '' for all users

$user              = new User();
$user->name        = 'alice';
$user->displayName = 'Alice';
$user->password    = '123456';
$client->addUser($user);
$client->updateUser($user);
$client->updateUserForColumns($user, ['displayName', 'email']);
$client->updateUserById('my-organization/alice', $user);
$client->updateUserByUserId('my-organization', '<user id>', $user);
$client->deleteUser($user);

$client->checkUserPassword($user);  // true or false
$client->setPassword('my-organization', 'alice', '123456', '654321');

$client->getPermissionsByRole('admin');

// Check a request against a permission (or a model / resource / enforcer / owner)
$allowed = $client->enforce('my-organization/read-data', '', '', '', '', ['my-organization/alice', 'data1', 'read']);
$results = $client->batchEnforce('my-organization/read-data', '', '', '', '', [
    ['my-organization/alice', 'data1', 'read'],
    ['my-organization/bob', 'data1', 'read'],
]);

use Casdoor\CasbinRule;

$client->getPolicies('my-enforcer', '');
$client->getFilteredPolicies('my-organization/my-enforcer', [['ptype' => 'p', 'fieldIndex' => 0, 'fieldValues' => ['alice']]]);
$client->addPolicy($enforcer, CasbinRule::new('p', 'alice', 'data1', 'read'));
$client->updatePolicy($enforcer, $oldPolicy, $newPolicy);
$client->removePolicy($enforcer, $policy);

// Place an order of products for a user and pay it with a payment provider
$order   = $client->placeOrder([['name' => 'my-product', 'quantity' => 1]], 'alice');
$payment = $client->payOrder($order['name'], 'my-payment-provider');
$client->cancelOrder($order['name']);

$client->getUserOrders('alice');
$client->getUserPayments('alice');
$client->getUserTransactions('alice');

// Validate a transaction (e.g. the balance) without saving it
$client->addTransactionWithDryRun($transaction, true);
[$affected, $name] = $client->addTransaction($transaction);

$client->sendEmail('Hello', 'Hello world', 'Casdoor', ['[email protected]']);
$client->sendEmailByProvider('Hello', 'Hello world', 'Casdoor', 'my-email-provider', ['[email protected]']);
$client->sendSms('123456', ['+12025550123']);
$client->sendSmsByProvider('123456', 'my-sms-provider', ['+12025550123']);
$client->sendNotification('Hello', 'alice');

[$fileUrl, $name] = $client->uploadResource('alice', 'avatar', 'user', '/avatar/alice.png', file_get_contents('avatar.png'));

$client->getResources('my-organization', 'alice', '', '', '', '');
$client->deleteResourceWithTag($resource, 'Direct');

$client->getLdaps();
$client->getLdapUsers('<ldap id>');
$client->syncLdapUsersFromServer('<ldap id>');  // fetch and sync all the LDAP users

$setup = $client->initiate('my-organization', 'app', 'alice')['data'];
$client->verify('my-organization', 'app', 'alice', $setup['secret'], '<passcode>');
$client->enable('my-organization', 'app', 'alice', $setup['secret'], $setup['recoveryCodes'][0]);
$client->setPreferred('my-organization', 'app', 'alice');
$client->delete('my-organization', 'alice');
bash
composer