1. Go to this page and download the library: Download slimphp-api/slim-oauth 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/ */
slimphp-api / slim-oauth example snippets
use Slim\App;
use SlimApi\OAuth\OAuthFactory;
use SlimApi\OAuth\OAuthMiddleware;
$app = new App();
$container = $app->getContainer();
// these should all probably be in some configuration class
$container['oAuthCreds'] = [
'github' => [
'key' => 'abc',
'secret' => '123',
]
];
$container[SlimApi\OAuth\OAuthFactory::class] = function($container)
{
return new OAuthFactory($container->get('oAuthCreds'));
};
$container[SlimApi\OAuth\UserServiceInterface::class] = function($container)
{
//user service should implement SlimApi\OAuth\UserServiceInterface
//user model should have a token variable to hold the random token sent to the client
return new Foo\Service\UserService($container->get('Foo\Model\User'));
};
$container[SlimApi\OAuth\OAuthMiddleware::class] = function($container)
{
return new OAuthMiddleware($container->get('SlimApi\OAuth\OAuthFactory'), $container->get('SlimApi\OAuth\UserServiceInterface'));
};
$app->add($container->get('SlimApi\OAuth\OAuthMiddleware'));
$app->run();
namespace Foo\Service;
use SlimApi\OAuth\UserServiceInterface;
use OAuth\Common\Service\ServiceInterface;
class UserService implements UserServiceInterface {
public function __construct($userModel)
{
$this->userModel = $userModel;
}
public function createUser(ServiceInterface $service)
{
// request the user information from github
// could go further with this and check org/team membership
$user = json_decode($service->request('user'), true);
// try to find user by the oauth server's user id,
// best way since oauth token might have been invalidated
$models = $this->userModel->byRemoteId($user['id'])->get();
$model = $models->first();
if (!$model) {
// create and save a new user
$model = new $this->userModel([
'remote_id' => $user['id']
]);
}
$model->oauth_token = $service->getStorage()->retrieveAccessToken('GitHub')->getAccessToken();
$model->token = 'randomstringj0'; // this isn't really random, but it should be!
$model->save();
return $model;
}
public function findOrNew($authToken)
{
// retrieve the user by the authToken provided
// this could also be from some fast access redis db
$users = $this->userModel->byToken($authToken)->get();
$user = $users->first();
// or return a blank entry if it doesn't exist
return ($user ?: new $this->userModel);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.