Passed
Pull Request — master (#72)
by
unknown
03:30
created

GmailConnection::saveAccessToken()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 8
nop 1
dl 0
loc 25
rs 9.4222
c 0
b 0
f 0
1
<?php
2
3
namespace Dacastro4\LaravelGmail;
4
5
use Dacastro4\LaravelGmail\Traits\Configurable;
6
use Google_Client;
7
use Google_Service_Gmail;
8
use Illuminate\Container\Container;
9
use Illuminate\Support\Facades\Request;
10
use Illuminate\Support\Facades\Storage;
11
12
class GmailConnection extends Google_Client
13
{
14
15
	use Configurable {
16
		__construct as configConstruct;
17
	}
18
19
	protected $emailAddress;
20
	protected $refreshToken;
21
	protected $app;
22
	protected $accessToken;
23
	protected $token;
24
	private $configuration;
25
26
	public function __construct( $config = null )
27
	{
28
		$this->app = Container::getInstance();
29
30
		$this->configConstruct( $config );
31
32
		$this->configuration = $config;
33
34
		parent::__construct( $this->getConfigs() );
35
36
		$this->configApi();
37
38
		if($this->checkPreviouslyLoggedIn()){
39
			$this->refreshTokenIfNeeded();
40
		}
41
42
	}
43
44
	public function getAccessToken()
45
	{
46
		$token = parent::getAccessToken() ?: $this->config();
47
48
		return $token;
49
	}
50
51
	/**
52
	 * @return array|string
53
	 * @throws \Exception
54
	 */
55
	public function makeToken()
56
	{
57
		if ( ! $this->check() ) {
58
			$request = Request::capture();
59
			$code = (string) $request->input( 'code', null );
60
			if ( ! is_null( $code ) && ! empty( $code ) ) {
0 ignored issues
show
introduced by
The condition is_null($code) is always false.
Loading history...
61
				$accessToken = $this->fetchAccessTokenWithAuthCode( $code );
62
				$me = $this->getProfile();
63
				if ( property_exists( $me, 'emailAddress' ) ) {
64
					$this->emailAddress = $me->emailAddress;
65
					$accessToken[ 'email' ] = $me->emailAddress;
66
				}
67
				$this->setBothAccessToken( $accessToken );
68
69
				return $accessToken;
70
			} else {
71
				throw new \Exception( 'No access token' );
72
			}
73
		} else {
74
			return $this->getAccessToken();
75
		}
76
	}
77
78
	public function setToken( $token )
79
	{
80
		$this->setAccessToken( $token );
81
	}
82
83
	/**
84
	 * Check and return true if the user has previously logged in without checking if the token needs to refresh
85
	 *
86
	 * @return bool
87
	 */
88
	public function checkPreviouslyLoggedIn()
89
	{
90
		$fileName = $this->getFileName();
91
		$file = "gmail/tokens/$fileName.json";
92
		$allowJsonEncrypt = $this->_config[ 'gmail.allow_json_encrypt' ];
93
94
		if ( Storage::disk( 'local' )->exists( $file ) ) {
95
			if ( $allowJsonEncrypt ) {
96
				$savedConfigToken = json_decode(decrypt(Storage::disk( 'local' )->get( $file )),true);
97
			} else {
98
				$savedConfigToken = json_decode(Storage::disk( 'local' )->get( $file ), true);
99
			}
100
101
			return !empty($savedConfigToken['access_token']);
102
103
		}
104
		return false;
105
	}
106
107
	/**
108
	 * Check
109
	 *
110
	 * @return bool
111
	 */
112
	public function check()
113
	{
114
		return ! $this->isAccessTokenExpired();
115
	}
116
117
	/**
118
	 * Check if token exists and is expired
119
	 * Throws an AuthException when the auth file its empty or with the wrong token
120
	 *
121
	 *
122
     * @return bool Returns True if the access_token is expired.
123
	 */
124
	public function isAccessTokenExpired()
125
	{
126
		$token = $this->getToken();
127
128
		if ( $token ) {
129
			$this->setAccessToken( $token );
130
		}
131
132
		return parent::isAccessTokenExpired();
133
	}
134
135
	/**
136
	 * Revokes user's permission and logs them out
137
	 */
138
	public function logout()
139
	{
140
		$this->revokeToken();
141
	}
142
143
	public function getToken()
144
	{
145
		return parent::getAccessToken() ?: $this->config();
146
	}
147
148
	/**
149
	 * Refresh the auth token if needed
150
	 *
151
	 * @return mixed|null
152
	 */
153
	private function refreshTokenIfNeeded()
154
	{
155
		if ( $this->isAccessTokenExpired() ) {
156
			$this->fetchAccessTokenWithRefreshToken( $this->getRefreshToken() );
157
			$token = $this->getAccessToken();
158
            $this->setBothAccessToken( $token );
159
            return $token;
160
		}
161
		return $this->token;
162
	}
163
164
	/**
165
	 * Gets user profile from Gmail
166
	 *
167
	 * @return \Google_Service_Gmail_Profile
168
	 */
169
	public function getProfile()
170
	{
171
		$service = new Google_Service_Gmail( $this );
172
173
		return $service->users->getProfile( 'me' );
174
	}
175
176
	/**
177
	 * @param array|string $token
178
	 */
179
	public function setAccessToken( $token )
180
	{
181
		parent::setAccessToken( $token );
182
	}
183
184
	/**
185
	 * @param $token
186
	 */
187
	public function setBothAccessToken( $token )
188
	{
189
        $this->setAccessToken( $token );
190
		$this->saveAccessToken( $token );
191
	}
192
193
	/**
194
	 * Save the credentials in a file
195
	 *
196
	 * @param array $config
197
	 */
198
	public function saveAccessToken( array $config )
199
	{
200
		$fileName = $this->getFileName();
201
		$file = "gmail/tokens/$fileName.json";
202
		$allowJsonEncrypt = $this->_config[ 'gmail.allow_json_encrypt' ];
203
        $config[ 'email' ] = $this->emailAddress;
204
205
        if ( Storage::disk( 'local' )->exists( $file ) ) {
206
207
            if(empty($config['email'])){
208
                if ( $allowJsonEncrypt ) {
209
                    $savedConfigToken = json_decode(decrypt(Storage::disk( 'local' )->get( $file )),true);
210
                } else {
211
                    $savedConfigToken = json_decode(Storage::disk( 'local' )->get( $file ), true);
212
                }
213
                $config['email'] = $savedConfigToken['email'];
214
            }
215
216
            Storage::disk( 'local' )->delete( $file );
217
        }
218
219
		if ( $allowJsonEncrypt ) {
220
			Storage::disk( 'local' )->put( $file, encrypt( json_encode( $config ) ) );
221
		} else {
222
			Storage::disk( 'local' )->put( $file, json_encode( $config ) );
223
		}
224
225
	}
226
227
	/**
228
	 * Delete the credentials in a file
229
	 */
230
	public function deleteAccessToken()
231
	{
232
		$fileName = $this->getFileName();
233
		$file = "gmail/tokens/$fileName.json";
234
235
		$allowJsonEncrypt = $this->_config[ 'gmail.allow_json_encrypt' ];
236
237
		if ( Storage::disk( 'local' )->exists( $file ) ) {
238
			Storage::disk( 'local' )->delete( $file );
239
		}
240
241
		if ( $allowJsonEncrypt ) {
242
			Storage::disk( 'local' )->put( $file, encrypt( json_encode( [] ) ) );
243
		} else {
244
			Storage::disk( 'local' )->put( $file, json_encode( [] ) );
245
		}
246
247
	}
248
249
}
250