ERROR Class app\Auth not found - slim framework v3 middleware - php

I am using slim framework and trying to implement slim token authentication as middleware, now whenever i go to
localhost/project/restrict
i get the message "Token Not Found" which seems to be working fine however when i try to pass the token in the authorization parameter as per the middleware documentation
locahost/project/restrict?authorization=usertokensecret
i always get the error Class 'app\Auth' not found and in my error trace the below,
0 /Applications/AMPPS/www/project/vendor/dyorg/slim-token-authentication/src/TokenAuthentication.php(66):
{closure}(Object(Slim\Http\Request),
Object(Slim\Middleware\TokenAuthentication))
1 [internal function]: Slim\Middleware\TokenAuthentication->__invoke(Object(Slim\Http\Request),
Object(Slim\Http\Response), Object(Slim\App))
2 /Applications/AMPPS/www/project/vendor/slim/slim/Slim/DeferredCallable.php(43):
call_user_func_array(Object(Slim\Middleware\TokenAuthentication),
Array)
3 [internal function]: Slim\DeferredCallable->__invoke(Object(Slim\Http\Request),
Object(Slim\Http\Response), Object(Slim\App))
4 /Applications/AMPPS/www/project/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(73):
call_user_func(Object(Slim\DeferredCallable),
Object(Slim\Http\Request), Object(Slim\Http\Response),
Object(Slim\App))
5 /Applications/AMPPS/www/project/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(122):
Slim\App->Slim{closure}(Object(Slim\Http\Request),
Object(Slim\Http\Response))
6 /Applications/AMPPS/www/project/vendor/slim/slim/Slim/App.php(370): Slim\App->callMiddlewareStack(Object(Slim\Http\Request),
Object(Slim\Http\Response))
7 /Applications/AMPPS/www/project/vendor/slim/slim/Slim/App.php(295): Slim\App->process(Object(Slim\Http\Request),
Object(Slim\Http\Response))
8 /Applications/AMPPS/www/project/index.php(81): Slim\App->run()
9 {main}
here the code i am using
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require_once './vendor/autoload.php';
$app = new \Slim\App;
use Slim\App;
use Slim\Middleware\TokenAuthentication;
$config = [
'settings' => [
'displayErrorDetails' => true
]
];
$app = new App($config);
$authenticator = function($request, TokenAuthentication $tokenAuth){
$token = $tokenAuth->findToken($request);
$auth = new \app\Auth();
$auth->getUserByToken($token);
};
/**
* Add token authentication middleware
*/
$app->add(new TokenAuthentication([
'path' => '/restrict',
'authenticator' => $authenticator
]));
/**
* Public route example
*/
$app->get('/', function($request, $response){
$output = ['msg' => 'It is a public area'];
$response->withJson($output, 200, JSON_PRETTY_PRINT);
});
/**
* Restrict route example
* Our token is "usertokensecret"
*/
$app->get('/restrict', function($request, $response){
$output = ['msg' => 'It\'s a restrict area. Token authentication works!'];
$response->withJson($output, 200, JSON_PRETTY_PRINT);
});
$app->run();
?>

The reason that \app\Auth cannot be found is because it doesn't exist in the current composer autoload path.
First move the app to the root folder, where core and the root vendor folders are.
Then add
"autoload": {
"classmap": [
"app"
]
}
to the root composer.json.
Last, run composer dump-autoload -o in the root folder.
After that, \app\Auth should be in the autoload path and everything should work as expected.

Related

Uncaught RuntimeException: Callable does not exist

I am trying a simple Slim application as shown below.
index.php
<?php
use Slim\Factory\AppFactory;
require './vendor/autoload.php';
$app = AppFactory::create();
$app->get('/', [TestController::class, 'showBlank']);
$app->run();
And below is the TestController.php.
<?php
use \Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Http\Interfaces\ResponseInterface;
class TestController
{
protected $c;
public function __construct(ContainerInterface $c)
{
$this->c = $c;
}
public function showBlank(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
return $response;
}
}
Below is the project structure.
C:\laragon\www\chum>ls
composer.json composer.lock index.php TestController.php vendor
Since I am trying slim for first time, I am keep the example to very minimal and so the composer.json file.
{
"require": {
"slim/slim": "^4.11",
"slim/psr7": "^1.6",
"slim/twig-view": "^3.3",
"slim/http": "^1.3"
}
}
Given these, I am getting the below exceptio when I try to access the root page(\).
Fatal error: Uncaught RuntimeException: Callable TestController::showBlank() does not exist in C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php:138
Stack trace:
#0 C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php(90): Slim\CallableResolver->resolveSlimNotation('TestController:...')
#1 C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php(63): Slim\CallableResolver->resolveByPredicate('TestController:...', Array, 'handle')
#2 C:\laragon\www\chum\vendor\slim\slim\Slim\Routing\Route.php(340): Slim\CallableResolver->resolveRoute(Array)
#3 C:\laragon\www\chum\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): Slim\Routing\Route->handle(Object(Slim\Http\ServerRequest))
#4 C:\laragon\www\chum\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#5 C:\laragon\www\chum\vendor\slim\slim\Slim\Routing\Route.php(315): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#6 C:\laragon\www\chum\vendor\slim\slim\Slim\Routing\RouteRunner.php(68): Slim\Routing\Route->run(Object(Slim\Http\ServerRequest))
#7 C:\laragon\www\chum\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): Slim\Routing\RouteRunner->handle(Object(Slim\Http\ServerRequest))
#8 C:\laragon\www\chum\vendor\slim\slim\Slim\App.php(199): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#9 C:\laragon\www\chum\vendor\slim\slim\Slim\App.php(183): Slim\App->handle(Object(Slim\Http\ServerRequest))
#10 C:\laragon\www\chum\index.php(56): Slim\App->run() #11 {main} thrown in C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php on line 138
Thanks Alvaro for the great tips in comments, I was able to solve it with some further help from Google based on that.
I was under assumption flat project structure does not need namespaces to be configured. But I was wrong.
I did the below updates to composer.json file and ran composer dump-autoload -o.
"autoload": {
"psr-4": {
"App\\": ""
}
},

Difference between getMethod() and getRealMethod() in Symphony5

I am not able to understand the difference between getMethod() and getRealMethod() in Symphony5.
I am using:
Symfony 5
PHP 7.4.3
I have already read through this StackOverflow post, but I am still facing strange issues.
What I want to achieve: Currently if I give an empty body to a
POST/PUT request then symfony gives a 500 Internal Server Error. But,
I want to give a 400 Bad Request Error to the user along with a custom
error message like "Empty request body with PUT/POST not allowed"
I have created this Request Listener,
namespace App\EventListener;
use Exception;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
class RequestListener
{
/**
* #var LoggerInterface $logger
*/
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function __invoke(RequestEvent $event): ?Response
{
$request = $event->getRequest();
$method = $request->getMethod();
$realMethod = $request->getRealMethod();
// this echo below is just to know the values for $method and $realMethod for debugging
echo("method = $method and real method = $realMethod");
if (in_array($method, [Request::METHOD_POST, Request::METHOD_PUT]) && $request->get('data') === null) {
$this->logger->info("Method PUT/POST with an empty body");
return new Response(null, Response::HTTP_BAD_REQUEST);
}
}
}
I have also added this Request Listener to the services.yaml file as,
App\EventListener\RequestListener:
tags:
- { name: kernel.event_listener }
Now when I try to test this with postman I have the following response,
as you can see, the method I used is clearly shown as POST, symfony returns it as GET both for getMethod() and getRealMethod() (by the way, I am not sure why I get the echo message "method = GET and real method = GET" twice). And thus I am not able to check for the empty body for POST/PUT.
EDITED:
Running bin/console debug:event-dispatcher gives this output:
"kernel.request" event
----------------------
------- ---------------------------------------------------------------------------------------------- ----------
Order Callable Priority
------- ---------------------------------------------------------------------------------------------- ----------
#1 Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure() 2048
#2 Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest() 256
#3 Nelmio\CorsBundle\EventListener\CorsListener::onKernelRequest() 250
#4 Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelRequest() 128
#5 Symfony\Component\HttpKernel\EventListener\LocaleListener::setDefaultLocale() 100
#6 Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest() 32
#7 ApiPlatform\Core\EventListener\QueryParameterValidateListener::onKernelRequest() 16
#8 Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest() 16
#9 Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelRequest() 15
#10 Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::configureLogoutUrlGenerator() 8
#11 Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelRequest() 8
#12 ApiPlatform\Core\EventListener\AddFormatListener::onKernelRequest() 7
#13 ApiPlatform\Core\EventListener\ReadListener::onKernelRequest() 4
#14 ApiPlatform\Core\Security\EventListener\DenyAccessListener::onSecurity() 3
#15 ApiPlatform\Core\EventListener\DeserializeListener::onKernelRequest() 2
#16 ApiPlatform\Core\Security\EventListener\DenyAccessListener::onSecurityPostDenormalize() 1
#17 App\EventSubscriber\EmptyRequestBodySubscriber::handleEmptyRequestBody() 1
#18 App\EventListener\RequestListener::__invoke() 0
#19 ApiPlatform\Core\Bridge\Symfony\Bundle\EventListener\SwaggerUiListener::onKernelRequest() 0
------- ---------------------------------------------------------------------------------------------- ----------
As you can see, my listener is found registered at #18,
#18 App\EventListener\RequestListener::__invoke() 0

slim exception not sure whats going wrong

I'm using slim 4, and the URL im using is http://localhost/MyApi/public/hello/WeAreLearningPHP
Details
Type: Slim\Exception\HttpNotFoundException
Code: 404
Message: Not found.
File: /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php
Line: 91
Trace
0 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php(57): Slim\Middleware\RoutingMiddleware->performRouting(Object(Slim\Psr7\Request))
1 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Slim\Middleware\RoutingMiddleware->process(Object(Slim\Psr7\Request), Object(Slim\Routing\RouteRunner))
2 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/selective/basepath/src/BasePathMiddleware.php(52): class#anonymous->handle(Object(Slim\Psr7\Request))
3 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Selective\BasePath\BasePathMiddleware->process(Object(Slim\Psr7\Request), Object(class#anonymous))
4 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(89): class#anonymous->handle(Object(Slim\Psr7\Request))
5 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Psr7\Request), Object(class#anonymous))
6 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/MiddlewareDispatcher.php(73): class#anonymous->handle(Object(Slim\Psr7\Request))
7 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/App.php(208): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request))
8 /Applications/XAMPP/xamppfiles/htdocs/MyApi/vendor/slim/slim/Slim/App.php(192): Slim\App->handle(Object(Slim\Psr7\Request))
9 /Applications/XAMPP/xamppfiles/htdocs/MyApi/public/index.php(28): Slim\App->run()
10 {main}
----------------index.php-------------------
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Selective\BasePath\BasePathMiddleware;
use Slim\Factory\AppFactory;
require_once __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Slim routing middleware
$app->addRoutingMiddleware();
// Set the base path to run the app in a subdirectory.
// This path is used in urlFor().
$app->add(new BasePathMiddleware($app));
$app->addErrorMiddleware(true, true, true);
// Define app routes
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('Hello, World!');
return $response;
})->setName('root');
// Run app
$app->run();

Slim framework Message: Callable Homecontroller does not exist

Project Structure
public/index.php
<?php
require __DIR__ . '/../vendor/autoload.php';
ini_set('display_errors', 'On');
if (PHP_SAPI == 'cli-server') {
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
session_start();
// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);
// Set up dependencies
require __DIR__ . '/../src/dependencies.php';
// Register middleware
require __DIR__ . '/../src/middleware.php';
// Register routes
require __DIR__ . '/../src/routes.php';
// Run app
$app->run();
Here we have the composer.json
{
"autoload":{
"psr-4": {
"App\\": "src"
}
},
"require": {
"php": ">=5.5.0",
"slim/slim": "^3.1",
"slim/php-view": "^2.0",
"monolog/monolog": "^1.17",
"illuminate/database": "~5.1",
"slim/twig-view": "^2.3"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"config": {
"process-timeout" : 0
},
}
Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more
<?php
namespace \App\Controllers;
class Homecontroller
{
protected $container;
// constructor receives container instance
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public function home($request, $response, $args) {
echo "locura";
// your code
// to access items in the container... $this->container->get('');
return $response;
}
public function contact($request, $response, $args) {
// your code
// to access items in the container... $this->container->get('');
return $response;
}
}
Actual configuration
In my routes.php I have put this:
$app->get('/new', \Homecontroller::class . ':home');
Before configuration
In the above code, I tried to create the controller into the container, and then use
$app->get('/new', '\HomeController:home');
And in the dependencies.php I put this code:
$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
};
but I didn't obtain any result with any configuration
I would like to load the HomeController from router
This is the error that I have when I put api.powertv/new
Type: RuntimeException
Message: Callable Homecontroller does not exist
File: /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90
i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.
Try to use absolute namespace path in your:
dependencies.php
$container['yourController'] = function ($c) {
$view = $c['view'];
return new \App\Controllers\YourController($view);
}
routes.php
$app->get('your_defined_route_name', \App\Controllers\YourController::class . ':YourControllerMethod');
The name inside the container and thoose who you use in the route must match
You've been set the container key to HomeController and used \HomeController in the route, these strings are not equal.
either self create the strings
$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
};
$app->get('/new', 'HomeController:home');
or use the ::class syntax for both:
$container[HomeController::class] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
};
$app->get('/new', [HomeController::class, 'home');
// or $app->get('/new', HomeController::class . ':home');
with the answer of Pheara I obtain another error, is the next:
Type: Error
Message: Undefined constant 'App\controllers'
File:/Users/alfonso/Sites/powertv_api/src/Controllers/HomeController.php
Line: 5
the trace of the error is the next:
/Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(444): include()
#1 /Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/Users/alfonso/...')
#2 [internal function]: Composer\Autoload\ClassLoader- >loadClass('App\\Controllers...')
#3 [internal function]: spl_autoload_call('App\\Controllers...')
#4 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(89): class_exists('App\\Controllers...')
#5 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(67): Slim\CallableResolver->resolveCallable('App\\Controllers...')
#6 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolverAwareTrait.php(45): Slim\CallableResolver->resolve('App\\Controllers...')
#7 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(330): Slim\Routable->resolveCallable('App\\Controllers...')
#8 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(313): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(495): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#11 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#12 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(388): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#13 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(296): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#14 /Users/alfonso/Sites/powertv_api/public/index.php(39): Slim\App->run()
#15 {main}
For solve this error you have to put the namespace in the 3 line:
<?php
namespace [yournamespace]
//rest of your controller

Google_Service_Exception 403 when listing groups with PHP

Getting an error when trying to list the groups of my domain through the PHP Directory API. The really weird thing is that if I list the groups using OAuth playground, it works seamlessly with these scopes:
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.group.member
Note: I'm not using a service account do this. My email address has super admin access, so I'm assuming this should be fine when trying to manage groups and group members? I'm using Slim 3 to handle the applications details. My client is initialized and authenticated (according to a quick var_dump on the object), yet I get an error when trying to do:
$service = new \Google_Service_Directory($this->client);
var_dump($service->groups->listGroups(["domain" => "example.google.com"])); // placeholder domain for SO
and here is the error I'm receiving when trying to load the page so I can list the groups:
#0 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Http/REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client))
#1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
#2 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Service/Resource.php(240): Google_Client->execute(Object(Google_Http_Request))
#6 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Service/Directory.php(2122): Google_Service_Resource->call('list', Array, 'Google_Service_...')
#7 /Applications/MAMP/htdocs/aslists/src/controllers/DashboardController.php(23): Google_Service_Directory_Groups_Resource->listGroups(Array)
#8 [internal function]: a_s\controllers\DashboardController->index(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
...
#18 {main}
Why would the query fail using the PHP API, but succeed on OAuth playground?
Update 1
My apologies in advance, this will contain a lot of code...
I spent some time tinkering around following the PHP Quickstart example where my client_secret.json file is loaded into the application like so:
$this->client->setAuthConfigFile('/path/to/client_secret.json');
$credentialsPath = $this->expandHomeDirectory('/path/to/.credentials/admin-directory_v1-php-quickstart.json');
if(file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
}
if(isset($accessToken)) {
$this->client->setAccessToken($accessToken);
}
if($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($this->client->getRefreshToken());
file_put_contents($credentialsPath, $this->client->getAccessToken());
}
$this->service = new \Google_Service_Directory($this->client);
If I use this method, it works perfectly with my application – very strange. I did additional investigation between this method and using Google to sign into the application and I was unable to find anything conclusive. Given that, it should work if I use Google to sign in, but it still doesn't.
Here is how I am initializing the client:
class GoogleController extends Controller {
private static $APP_NAME = "Lists Manager";
private static $CLIENT_ID = "...";
private static $CLIENT_SECRET = "...";
private static $REDIRECT_URI = "postmessage";
private static $ACCESS_TYPE = "offline";
private static $scopes = [
\Google_Service_Oauth2::USERINFO_PROFILE,
\Google_Service_Oauth2::USERINFO_EMAIL,
\Google_Service_Directory::ADMIN_DIRECTORY_GROUP,
\Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER,
\Google_Service_Directory::ADMIN_DIRECTORY_USER
];
protected $client;
public function __construct($container) {
parent::__construct($container);
$this->client = new \Google_Client();
$this->client->setApplicationName(self::$APP_NAME);
$this->client->setClientId(self::$CLIENT_ID);
$this->client->setClientSecret(self::$CLIENT_SECRET);
$this->client->setRedirectUri(self::$REDIRECT_URI);
$this->client->setScopes(self::$scopes);
$this->client->setAccessType(self::$ACCESS_TYPE);
}
}
From here, I have another controller which extends GoogleController that contains an ajax endpoint (i.e. where the access code it POSTed to). The code for this is shown below:
class LoginController extends GoogleController {
public function __construct($container) {
parent::__construct($container);
}
public function login($request, $response) {
if($this->client->isAccessTokenExpired()) {
unset($_SESSION[GoogleController::AS_PERSISTENT_CLIENT_OBJECT]);
$this->tokens = $this->client->authenticate($request->getBody()->getContents());
// $this->client->setAccessToken($this->token); // Not sure if I need to do this. Either way, I still get the exception
}
$_SESSION[GoogleController::AS_PERSISTENT_CLIENT_OBJECT] = serialize($this->client);
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write($this->generateJsonSuccess('dashboard'));
}
}

Categories