I try to make an web application which use google api for the user system.
Actually, I can only connect my google account to one route, here it is :
$app->get('/home', function () use($client,$app){
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if(!isset($_SESSION['token'])){
$url = $client->createAuthUrl();
$output = '<a href="'.$url.'">Se connecter </a>';
} else {
$client->setAccessToken($_SESSION['token']);
$token = json_decode($_SESSION['token']['access_token']);
$output = "";
require "../view/planning.php";
}
return $output;
});
Here is my $client :
$client = new Google_Client();
$client->setApplicationName("Application de test");
$client->setClientId(MY_CLIENT_ID);
$client->setClientSecret(MY_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/calendar.readonly');
$client->addScope('https://www.googleapis.com/auth/userinfo.email');
$client->setRedirectUri(MY_REDIRECT_URI);
$client->setAccessType('online');
And my question is : how I can keep the current client to the whole application ? For exemple, if I have this route :
$app->get('/accueil', function () use($client){
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if(!isset($_SESSION['token'])){
$url = $client->createAuthUrl();
$output = '<a href="'.$url.'">Se connecter </a>';
} else {
$client->setAccessToken($_SESSION['token']);
$token = json_decode($_SESSION['token']['access_token']);
require ('../view/accueil.php');
$output = "";
}
return $output;
});
But this route not working, it show me the link to login. I understand that the application cannot get 'code'
from the url, because there is nothing.
I also tried to keep the 'code'
like this :
if(isset($_GET['code']) || isset($_SESSION['code'])){
$client->authenticate($_GET['code']);
$_SESSION['code'] = $_GET['code'];
$_SESSION['token'] = $client->getAccessToken();
}
How can I keep the user logged ?
Well, after a long night, I find the solution.
It seemes like the redirect on 127.0.0.1 is different than redirect to localhost, so session variables are reset.