65 lines
2.4 KiB
PHP
Executable File
65 lines
2.4 KiB
PHP
Executable File
<?php
|
|
// File: app/Helpers/oauth_helper.php
|
|
// require 'vendor/autoload.php';
|
|
use Google\Client as GoogleClient;
|
|
use Google\Service\Oauth2;
|
|
|
|
// Check if the function exists, to prevent redeclaration
|
|
if (!function_exists('googleOauthLogin')) {
|
|
|
|
function googleOAuthLogin($oauthToken)
|
|
{
|
|
|
|
// Retrieve configuration values from environment variables
|
|
$appName = getenv('GOOGLE_OAUTH_APP_NAME');
|
|
$clientID = getenv('GOOGLE_OAUTH_CLIENT_ID');
|
|
$clientSecret = getenv('GOOGLE_OAUTH_CLIENT_SECRET');
|
|
$redirectUri = getenv('GOOGLE_OAUTH_REDIRECT_URI');
|
|
$scopes = getenv('GOOGLE_OAUTH_SCOPES');
|
|
|
|
// Convert the scopes string into an array
|
|
$scopesArray = explode(',', $scopes);
|
|
|
|
// Initialize a new Google client
|
|
$client = new GoogleClient();
|
|
$client->setApplicationName($appName);
|
|
$client->setClientId($clientID);
|
|
$client->setClientSecret($clientSecret);
|
|
$client->setRedirectUri($redirectUri);
|
|
$client->addScope($scopesArray);
|
|
// $client->setApprovalPrompt('force');
|
|
$client->setPrompt('consent');
|
|
$client->setAccessType('offline');
|
|
|
|
// Check if an OAuth token is provided
|
|
if ($oauthToken) {
|
|
try {
|
|
// Attempt to fetch the access token with the provided OAuth token
|
|
$token = $client->fetchAccessTokenWithAuthCode($oauthToken);
|
|
session()->set('access_token', $token['access_token']);
|
|
if(isset($token['refresh_token'])){
|
|
session()->set('refresh_token', $token['refresh_token']);
|
|
}
|
|
$client->setAccessToken($token);
|
|
|
|
$oauth = new Oauth2($client);
|
|
|
|
// Get user information using the OAuth2 service
|
|
$user_info = $oauth->userinfo->get();
|
|
return $user_info;
|
|
|
|
} catch (\Exception $e) {
|
|
// Handle exceptions and return an error message
|
|
return 'Error fetching access token: ' . $e->getMessage();
|
|
}
|
|
} else {
|
|
// If no OAuth token is provided, generate the authentication URL
|
|
$url = $client->createAuthUrl();
|
|
// Redirect the user to the authentication URL
|
|
return redirect()->to(filter_var($url, FILTER_SANITIZE_URL));
|
|
}
|
|
}
|
|
}
|
|
|
|
?>
|