Completed
Pull Request — master (#4)
by
unknown
03:57
created

AzineHybridAuth::storeHybridAuthSessionData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 9.4285
ccs 0
cts 5
cp 0
cc 2
eloc 5
nc 2
nop 3
crap 6
1
<?php
2
namespace Azine\HybridAuthBundle\Services;
3
4
use Azine\HybridAuthBundle\DependencyInjection\AzineHybridAuthExtension;
5
6
use Azine\HybridAuthBundle\Entity\HybridAuthSessionData;
7
use Doctrine\Common\Persistence\ObjectManager;
8
use Symfony\Component\HttpFoundation\Cookie;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
12
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
13
use Symfony\Component\Security\Core\User\UserInterface;
14
15
class AzineHybridAuth {
16
	/**
17
	 * ID of the sessionDataCookie
18
	 */
19
	const cookieName = "azine_hybridauth_session";
20
21
	/**
22
	 * @var ObjectManager
23
	 */
24
	private $objectManager;
25
26
	/**
27
	 * @var UserInterface
28
	 */
29
	private $currentUser;
30
31
	/**
32
	 * @var bool
33
	 */
34
	private $storeForUser;
35
36
	/**
37
	 * @var bool
38
	 */
39
	private $storeAsCookie;
40
41
	/**
42
	 * @var int
43
	 */
44
	private $expiresInDays;
45
46
	/**
47
	 * Configured Instances of HybridAuth
48
	 * @var array or HybridAuth
49
	 */
50
	private $instances = array();
51
52
	/**
53
	 * HybridAuth configuration
54
	 * @var array
55
	 */
56
	private $config;
57
58
	/**
59
	 *
60
	 * @param UrlGeneratorInterface $router
61
	 * @param TokenStorageInterface $tokenStorage
62
	 * @param ObjectManager $manager
63
	 * @param array $config
64
	 * @param bool $storeForUser
65
	 * @param $storeAsCookie
66
	 */
67 2
	public function __construct(UrlGeneratorInterface $router, TokenStorageInterface $tokenStorage, ObjectManager $manager, $config, $storeForUser, $storeAsCookie){
68 2
		$base_url = $router->generate($config[AzineHybridAuthExtension::ENDPOINT_ROUTE], array(), UrlGeneratorInterface::ABSOLUTE_URL);
69 2
		$config[AzineHybridAuthExtension::BASE_URL] = $base_url;
70 2
		$this->config = $config;
71 2
		$this->objectManager = $manager;
72 2
		$this->storeForUser = $storeForUser;
73 2
		$this->storeAsCookie = $storeAsCookie;
74 2
		$user = $tokenStorage->getToken()->getUser();
75 2
		if($user instanceof UserInterface) {
76
			$this->currentUser = $user;
77
		}
78 2
	}
79
80
81
	/**
82
	 * Get a Hybrid_Auth instance initialised for the given provider.
83
	 * HybridAuthSessions will be restored from DB and/or cookies, according to the bundle configuration.
84
	 *
85
	 * @param $cookieSessionData
86
	 * @param $provider
87
	 * @return \Hybrid_Auth
88
	 */
89
	public function getInstance($cookieSessionData, $provider){
90
		if(array_key_exists($provider, $this->instances)){
91
			$hybridAuth = $this->instances[$provider];
92
		} else {
93
			$hybridAuth = new \Hybrid_Auth($this->config);
94
			$this->instances[$provider] = $hybridAuth;
95
		}
96
		$restoredFromDB = false;
97
		$sessionData = null;
98
		$isExpiredSession = false;
99
100
		$result = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
101
102
		if($result instanceof HybridAuthSessionData){
103
104
			$isExpiredSession =  $this->isExpiredSession($result);
105
		}
106
107
		if($isExpiredSession){
108
109
			$this->deleteSession($provider);
110
		}
111
112
		if(!$isExpiredSession && $this->storeForUser && $this->currentUser instanceof UserInterface){
113
			// try from database
114
			if($result){
115
				$sessionData = $result->getSessionData();
116
				$restoredFromDB = true;
117
			}
118
		}
119
		if($sessionData === null && $cookieSessionData !== null) {
120
			// try from cookie
121
			$sessionData = gzinflate($cookieSessionData);
122
123
			// user is looged in but auth session is not yet stored in db => store now
124
			if(!$restoredFromDB){
125
				$this->saveAuthSessionData($sessionData, $provider);
126
			}
127
		}
128
		if($sessionData) {
129
			$hybridAuth->restoreSessionData($sessionData);
130
		}
131
132
		return $hybridAuth;
133
	}
134
135
	/**
136
	 * @param Request $request
137
	 * @param $provider
138
	 * @param $sessionData
139
	 * @return Cookie | null
140
	 */
141
	public function storeHybridAuthSessionData(Request $request, $provider, $sessionData){
142
		$this->saveAuthSessionData($sessionData, $provider);
143
144
		if($this->storeAsCookie){
145
			return new Cookie($this->getCookieName($provider), gzdeflate($sessionData), new \DateTime($this->expiresInDays .' days'), '/', $request->getHost(), $request->isSecure(), true);
0 ignored issues
show
Documentation introduced by
new \DateTime($this->expiresInDays . ' days') is of type object<DateTime>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
146
		}
147
		return null;
148
	}
149
150
	/**
151
	 * Delete the HybridAuthSessionData entity from the database
152
	 * @param $provider
153
	 */
154
	public function deleteSession($provider){
155
		if($this->currentUser instanceof UserInterface) {
156
			$result = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
157
			if ($result) {
158
				$this->objectManager->remove($result);
159
				$this->objectManager->flush();
160
			}
161
		}
162
	}
163
164
	/**
165
	 * Save as HybridAuthSessionData entity to the database.
166
	 * Checks the bundle configuration before saving.
167
	 * @param $sessionData
168
	 * @param $provider
169
	 */
170
	private function saveAuthSessionData($sessionData, $provider){
171
		if($this->storeForUser && $this->currentUser instanceof UserInterface) {
172
			$hybridAuthData = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => strtolower($provider)));
173
			if (!$hybridAuthData) {
174
				$hybridAuthData = new HybridAuthSessionData();
175
				$hybridAuthData->setUserName($this->currentUser->getUsername());
176
				$hybridAuthData->setProvider(strtolower($provider));
177
178
				$expirationDate = new \DateTime();
179
				$expirationDate->modify('+ '. $this->expiresInDays .' day');
180
181
				$hybridAuthData->setExpiresAt($expirationDate);
182
				$this->objectManager->persist($hybridAuthData);
183
			}
184
			$hybridAuthData->setSessionData($sessionData);
185
			$this->objectManager->flush();
186
		}
187
	}
188
189
	public function getCookieName($provider){
190
		return self::cookieName."_".strtolower($provider);
191
	}
192
193
	/**
194
	 * Use this function to get access to a HybridAuthProvider.
195
	 *
196
	 * Calling this method will log the user in (make a roundtrip to the providers site and back to your site again)
197
	 * and call the page again that you came from.
198
	 *
199
	 * When logged (allready) it will return the hybridAuth provider.
200
	 *
201
	 * @param $authSessionData
202
	 * @param string $provider_id
203
	 * @param boolean $require_login
204
	 * @return \Hybrid_Provider_Model
205
	 */
206
	public function getProvider($authSessionData, $provider_id, $require_login = true){
207
		$adapter = $this->getInstance($authSessionData, $provider_id)->getAdapter($provider_id);
208
		if($require_login && !$adapter->isUserConnected()){
209
			$adapter->login();
210
		}
211
		return $adapter;
212
	}
213
214
	/**
215
	 * Check if the current user has allowed access to the given provider
216
	 * @param Request $request
217
	 * @param string $provider_id
218
	 * @return bool true if access to the provider is granted for this app.
219
	 */
220
	public function isConnected(Request $request, $provider_id){
221
		$sessionData = $request->cookies->get($this->getCookieName($provider_id));
222
		$adapter = $this->getInstance($sessionData, $provider_id)->getAdapter($provider_id);
223
		$connected = $adapter->isUserConnected();
224
		return $connected;
225
	}
226
227
	/**
228
	 * Get the Xing Adapter
229
	 * @return \Hybrid_Providers_XING
230
	 */
231
	public function getXing(){
232
		return $this->getProvider(null, "xing");
233
	}
234
235
	/**
236
	 * Get the Xing api (OAuthClient)
237
	 *
238
	 * @return \OAuth1Client
239
	 */
240
	public function getXingApi(){
241
		return $this->getXing()->api();
242
	}
243
244
	/**
245
	 * Get the LinkedIn Adapter
246
	 *
247
	 * @return \Hybrid_Providers_LinkedIn
248
	 */
249
	public function getLinkedIn(){
250
		return $this->getProvider(null, "linkedin");
251
	}
252
253
	/**
254
	 * Get the LinkedIn api (LinkedIn PHP-client)
255
	 *
256
	 * @return \LinkedIn
257
	 */
258
	public function getLinkedInApi(){
259
		return $this->getLinkedIn()->api();
260
	}
261
262
	/**
263
	 * Get if auth token is expired
264
	 * @param HybridAuthSessionData $data
265
	 *
266
	 * @return boolean
267
	 */
268 2
	public function isExpiredSession(HybridAuthSessionData $data)
269
	{
270 2
		if($data->getExpiresAt() <  new \DateTime()){
271
272 1
			return true;
273
		}
274
275 1
		return false;
276
	}
277
}