Skip to content

User_AccessToken

StefansArya edited this page Apr 19, 2019 · 2 revisions

You may need to import this feature on top of your code.

use \Scarlets\Library\User\AccessToken;

The AccessToken configuration are stored on /config/auth.php.
When you're using this library, it will automatically add token_table table and app_table on the database if not exist.

token_table

Column Description
token_id AccessToken ID
app_id Application ID
user_id User ID
expiration Expiration timestamp
permissions AccessToken permissions

But before you can get an AccessToken you must define your application in the app_table for the AccessToken.

app_table

Column Description
app_id Application ID
app_secret Application Secret Key

Create new AccessToken

When creating access token usually you will have different App in your database, sometime it could be an application created by another developer. So you need to define set $appID and it's $appSecret in app_table database. The token information will be saved in token_table database.

AccessToken::create($appID, $appSecret, $userData);

# Example
AccessToken::create(1, 'H8^0b D(@.;{', [
    'userID'=>1,
    'username'=>'hello',
    'permissions'=>'|1|3|5|7|' // Wrapped PermissionID
]);

The AccessToken will only valid in one day. You can define your own PermissionID somewhere on your Application. The $userData is required, and permissions can also be |*| if the user has any permission.

Parsing AccessToken

If you already have the user access token you can parse and validate it like below.

AccessToken::parse($accessToken);

But if the AccessToken still in the request query ?access_token=AccessToken or the request header Authentication: bearer AccessToken. You can utilize framework's feature.

AccessToken::parseAvailableToken();

Extend AccessToken expiration

It's usual if AccessToken have an expiration time, but instead of creating new AccessToken it's better to extend the expiration time before it's expired.

AccessToken::refresh($expires_in = 2592000);

Obtaining user data from AccessToken

After the AccessToken was parsed by the framework, you can easily obtain data for the current AccessToken.

AccessToken::$appID = 0;
AccessToken::$tokenID = 0;
AccessToken::$userID = 0;
AccessToken::$expiration = 0;

Check allowed user permissions

To check if an user was allowed to do something, you need to use AccessToken::isAllowed with the permissionID.

AccessToken::isAllowed($permissionID);

# Example
$PermissionID = [0=>'posting', 1=>'deleting', 2=>'modify'];
if(AccessToken::isAllowed(2))
    die("User allowed for modify stuff");

Revoke AccessToken

Usually the expired AccessToken will need to be removed manually by setting up a cronjob. But if you want to remove AccessToken from the database even it haven't expired, you can use revoke function.

AccessToken::revoke($tokenID = false);