PHP code example of ybelenko / oauth2_email_grant

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

    

ybelenko / oauth2_email_grant example snippets


use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\UserEntityInterface;
use Ybelenko\OAuth2\Server\Grant\CustomEmailGrant;

// if you want to use class method instead of anonymous functions
// do $onAccessToken = \Closure::fromCallable([$this, 'onAccessToken'])
// or when method is static $onAccessToken = \Closure::fromCallable([UserClass::class, 'onAccessToken'])

$grant = new CustomEmailGrant(
    $userRepository, // repository used in your oauth2 server implementation
    static function (
        string $email,
        AccessTokenEntityInterface $accessToken,
        ClientEntityInterface $client, 
        UserEntityInterface $user,
        array $scopes
    ) {
        // send access token to user via email
        // or do something else
    },
    static function (string $email) {
        // validate email the way you want
        // throw an exception or return true|false
        // everything beside true return will stop token creation
    }
);

// all other repos should be added from auth server automatically
// right after you call
$server->enableGrantType($grant, new \DateInterval('PT1H'));

/**
 * {@inheritdoc}
 */
public function getUserEntityByUserCredentials(
    $username,
    $password,
    $grantType,
    ClientEntityInterface $clientEntity
) {
    if ($grantType === 'custom_email') {
        // password is empty string now
        // just for readability
        $email = $username;
        // if user with provided email exists return new entity
        // otherwise return null
        // don't need to check password since we send token
        // to provided email, works like common account recover flow
        $user = new FakeUserEntity();
        $user->setIdentifier($email);
        return $user;
    }

    // handle other grants also check password from now

    return null;
}