-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOauth2Authentication.php
More file actions
executable file
·154 lines (142 loc) · 5.59 KB
/
Copy pathOauth2Authentication.php
File metadata and controls
executable file
·154 lines (142 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: Oauth2Authentication.tt
// Build date: 2017-10-08
// PHP generator version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
*
* @return A google client object.
*/
function getGoogleClient($credentialsPath = __DIR__ . '/credentials.json') {
$client = getOauth2Client($credentialsPath);
if (!$client->getRefreshToken()) {
// error_log('[StopLight] No Refresh token found...');
}
// Refresh the token if it's expired.
if ($client && $client->isAccessTokenExpired()) {
// error_log('[StopLight] Refreshing Token...');
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
writeToCredentials($client, $credentialsPath);
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY,
* Google_Service_Analytics::ANALYTICS) List of Google Scopes:
* https://developers.google.com/identity/protocols/googlescopes
*
* @return A google client object.
*/
function buildClient() {
$client = new Google_Client([
'access_type' => 'offline',
'approval_prompt' => 'force',
'include_granted_scopes' => true,
'scopes' => [
Google\Service\Calendar::CALENDAR_READONLY,
Google\Service\Calendar::CALENDAR_EVENTS_READONLY
],
'credentials' => __DIR__ . '/client_secret.json',
'redirect_uri' => getRedirectUri()
]);
return $client;
}
/**
* Builds the redirect uri.
* Documentation:
* https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to
* oauth2callback.php
*
* @return A redirect uri.
*/
function getRedirectUri() {
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if (strrpos($url, '?') > 0) {
$url = substr($url, 0, strrpos($url, '?'));
} // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/')); // Removing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder . '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
*
* @return A google client object.
*/
function getOauth2Client($credentialsPath = __DIR__ . '/credentials.json') {
try {
$client = buildClient();
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
return $client;
}
else {
$credentials = json_decode(@file_get_contents($credentialsPath), true);
if (!empty($credentials->access_token)) {
$client->setAccessToken($credentials);
return $client;
}
else {
// We do not have access request access.
header('Location: ' . filter_var($client->getRedirectUri(), FILTER_SANITIZE_URL));
}
}
}
catch (Exception $e) {
error_log('[StopLight] ' . $e->getMessage());
print "An error occurred: " . $e->getMessage();
}
}
function writeToCredentials($client, $credentialsPath) {
unset($_SESSION['access_token']);
if (file_exists($credentialsPath)) {
unlink($credentialsPath);
}
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
// Add access token and refresh token to session.
$_SESSION['access_token'] = $client->getAccessToken();
if (!file_exists($credentialsPath)) {
error_log('[StopLight] Unable to create credentials file.');
}
}