(Laravel 5)
I wanted to use Socialite to create and link user accounts with the Google API, but also wanted to use the accounts to retrieve Analytics data from Google.
I started off by researching if there was a way to use Socialite to access the Google API. No such luck, it pretty much just links user accounts with their accounts from various other social sites on the web.
For this project I am using the following packages (in addition to default ones):
"google/apiclient": "^1.1"
"laravel/socialite": "~2.0"
Goal: Avoid authenticating users twice during app signup and usage.
Solution:
- Use a Google API Web App account
- Use the same credentials and scopes in the config for both laravel/socialite and google/apiclient
- Make sure the user is logged into the Laravel App before querying GA (this means their tokens, etc are already up to date)
Use a Google API Web App account
JavaScript API won't work on back end, and a Service account will only let us access one analytics account (our users authenticate with Google and they can see their data from all of their accounts), so the API Web App method is the best choice.
Use the same credentials and scopes in the config for both laravel/socialite and google/apiclient
These are the scopes I used:
```php
'
https://www.googleapis.com/auth/plus.profile.emails.read',
'
https://www.googleapis.com/auth/analytics.readonly',
'
https://www.googleapis.com/auth/userinfo.email'
```
Locations:
Socialite: vendor/laravel/socialite/src/Two/GoogleProvider.php
Google API: config/google.php
Make sure the user is logged into the Laravel App before querying GA (this means their tokens, etc are already up to date)
I basically just add logic to my routes.php that will only allow the routes with access to Analytics API functions if the user is logged in.
Here's an excerpt:
// Routes that require Auth
Route::group( [ 'middleware' => 'auth' ], function() {
// Dashboard/Google Auth
Route::get( 'dashboard', 'DashboardController@index', [ 'as' => 'dashboard' ] );
Route::get( 'google_cb_2', 'DashboardController@callback', [ 'as' => 'google_cb_2' ] );
// Sites/Reports
Route::get( 'sites', function() { return redirect( 'dashboard' ); });
Route::get( 'sites/add', [ 'as' => 'sites/add', function() { return view( 'sites/add' ); } ]);
Route::post( 'sites/add', [ 'uses' => 'SiteController@store' ] );
Route::get( 'sites/{site_id}/remove', [ 'uses' => 'SiteController@removeConfirm' ] );
Route::delete( 'sites/{site_id}', [ 'uses' => 'SiteController@remove' ] );
Route::get( 'sites/{site_id}', [ 'uses' => 'SiteController@overview' ] );
Route::get( 'sites/{site_id}/bounce', [ 'uses' => 'SiteController@bounce' ] );
});
Feedback welcome!