Completed
Push — master ( 66b057...cb56f8 )
by Dominik
9s
created

AzineHybridAuth::isExpiredSession()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
ccs 0
cts 0
cp 0
cc 2
eloc 4
nc 2
nop 1
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\TokenStorageInterface;
12
use Symfony\Component\Security\Core\User\UserInterface;
13
14
class AzineHybridAuth {
15
	/**
16
	 * ID of the sessionDataCookie
17
	 */
18
	const cookieName = "azine_hybridauth_session";
19
20
	/**
21
	 * @var ObjectManager
22
	 */
23
	private $objectManager;
24
25
	/**
26
	 * @var UserInterface
27
	 */
28
	private $currentUser;
29
30
	/**
31
	 * @var bool
32
	 */
33
	private $storeForUser;
34
35
	/**
36
	 * @var bool
37
	 */
38
	private $storeAsCookie;
39
40
	/**
41
	 * @var int
42
	 */
43
	private $expiresInDays;
44
45
	/**
46
	 * Configured Instances of HybridAuth
47
	 * @var array or HybridAuth
48
	 */
49
	private $instances = array();
50
51
	/**
52
	 * HybridAuth configuration
53
	 * @var array
54
	 */
55
	private $config;
56
57
	/**
58
	 *
59
	 * @param UrlGeneratorInterface $router
60
	 * @param TokenStorageInterface $tokenStorage
61
	 * @param ObjectManager $manager
62
	 * @param array $config
63
	 * @param bool $storeForUser
64
	 * @param $storeAsCookie
65
	 * @param $expiresInDays
66
	 */
67
	public function __construct(UrlGeneratorInterface $router, TokenStorageInterface $tokenStorage, ObjectManager $manager, $config, $storeForUser, $storeAsCookie, $expiresInDays){
68
		$base_url = $router->generate($config[AzineHybridAuthExtension::ENDPOINT_ROUTE], array(), UrlGeneratorInterface::ABSOLUTE_URL);
69
		$config[AzineHybridAuthExtension::BASE_URL] = $base_url;
70
		$this->config = $config;
71
		$this->objectManager = $manager;
72
		$this->storeForUser = $storeForUser;
73
		$this->storeAsCookie = $storeAsCookie;
74
		$user = $tokenStorage->getToken()->getUser();
75
        if($user instanceof UserInterface) {
76
			$this->currentUser = $user;
77
        }
78
        $this->expiresInDays = $expiresInDays;
79
	}
80
81
82
	/**
83
	 * Get a Hybrid_Auth instance initialised for the given provider.
84
	 * HybridAuthSessions will be restored from DB and/or cookies, according to the bundle configuration.
85
	 *
86
	 * @param $cookieSessionData
87
	 * @param $provider
88
	 * @return \Hybrid_Auth
89
	 */
90
	public function getInstance($cookieSessionData, $provider){
91
		if(array_key_exists($provider, $this->instances)){
92
			$hybridAuth = $this->instances[$provider];
93
		} else {
94
			$hybridAuth = new \Hybrid_Auth($this->config);
95
			$this->instances[$provider] = $hybridAuth;
96
		}
97
		$restoredFromDB = false;
98
		$sessionData = null;
99
        $isExpiredSession = false;
100
101
        // try to get from database
102
        $result = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
103
104
        if($result instanceof HybridAuthSessionData){
105
            $isExpiredSession =  $this->isExpiredSession($result);
106
        }
107
108
        if($isExpiredSession){
109
            $this->deleteSession($provider);
110
        }
111
112
        if(!$isExpiredSession && $this->storeForUser && $this->currentUser instanceof UserInterface){
113
			if($result){
114
				$sessionData = $result->getSessionData();
115
				$restoredFromDB = true;
116
			}
117
		}
118
		if($sessionData === null && $cookieSessionData !== null) {
119
			// try from cookie
120
			$sessionData = gzinflate($cookieSessionData);
121
122
			// user is looged in but auth session is not yet stored in db => store now
123
			if(!$restoredFromDB){
124
				$this->saveAuthSessionData($sessionData, $provider);
125
			}
126
		}
127
		if($sessionData) {
128
			$hybridAuth->restoreSessionData($sessionData);
129
		}
130
131
		return $hybridAuth;
132
	}
133
134
	/**
135
	 * @param Request $request
136
	 * @param $provider
137
	 * @param $sessionData
138
	 * @return Cookie | null
139
	 */
140
	public function storeHybridAuthSessionData(Request $request, $provider, $sessionData){
141
		$this->saveAuthSessionData($sessionData, $provider);
142
143
		if($this->storeAsCookie){
144
			return new Cookie($this->getCookieName($provider), gzdeflate($sessionData), new \DateTime($this->expiresInDays .' days'), '/', $request->getHost(), $request->isSecure(), true);
145
		}
146
		return null;
147
	}
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...
148
149
    /**
150
     * Delete the HybridAuthSessionData entity from the database
151
     * @param $provider
152
     */
153
    public function deleteSession($provider){
154
        if($this->currentUser instanceof UserInterface) {
155
            $result = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
156
            if ($result) {
157
                $this->objectManager->remove($result);
158
                $this->objectManager->flush();
159
            }
160
        }
161
    }
162
163
    /**
164
     * Save as HybridAuthSessionData entity to the database.
165
     * Checks the bundle configuration before saving.
166
     * @param $sessionData
167
     * @param $provider
168
     */
169
	private function saveAuthSessionData($sessionData, $provider){
170
        if($this->storeForUser && $this->currentUser instanceof UserInterface) {
171
            $hybridAuthData = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => strtolower($provider)));
172
            if (!$hybridAuthData) {
173
                $hybridAuthData = new HybridAuthSessionData();
174
                $hybridAuthData->setUserName($this->currentUser->getUsername());
175
                $hybridAuthData->setProvider(strtolower($provider));
176
                $hybridAuthData->setExpiresAt(new \DateTime('+ '. $this->expiresInDays .' days'));
177
                $this->objectManager->persist($hybridAuthData);
178
            }
179
            $hybridAuthData->setSessionData($sessionData);
180
            $this->objectManager->flush();
181
        }
182
	}
183
184
	public function getCookieName($provider){
185
		return self::cookieName."_".strtolower($provider);
186
	}
187
188
	/**
189
	 * Use this function to get access to a HybridAuthProvider.
190
	 *
191
	 * Calling this method will log the user in (make a roundtrip to the providers site and back to your site again)
192
	 * and call the page again that you came from.
193
	 *
194
	 * When logged (allready) it will return the hybridAuth provider.
195
	 *
196
	 * @param $authSessionData
197
	 * @param string $provider_id
198
	 * @param boolean $require_login
199
	 * @return \Hybrid_Provider_Model
200
	 */
201
	public function getProvider($authSessionData, $provider_id, $require_login = true){
202
		$adapter = $this->getInstance($authSessionData, $provider_id)->getAdapter($provider_id);
203
		if($require_login && !$adapter->isUserConnected()){
204
			$adapter->login();
205
		}
206
		return $adapter;
207
	}
208
209
	/**
210
	 * Check if the current user has allowed access to the given provider
211
	 * @param Request $request
212
	 * @param string $provider_id
213
	 * @return bool true if access to the provider is granted for this app.
214
	 */
215
	public function isConnected(Request $request, $provider_id){
216
        $sessionData = $request->cookies->get($this->getCookieName($provider_id));
217
		$adapter = $this->getInstance($sessionData, $provider_id)->getAdapter($provider_id);
218
		$connected = $adapter->isUserConnected();
219
		return $connected;
220
	}
221
222
	/**
223
     * Get the Xing Adapter
224
     * @return \Hybrid_Providers_XING
225
     */
226
	public function getXing(){
227
		return $this->getProvider(null, "xing");
228
	}
229
230
	/**
231
	 * Get the Xing api (OAuthClient)
232
	 *
233
	 * @return \OAuth1Client
234
	 */
235
	public function getXingApi(){
236
		return $this->getXing()->api();
237
	}
238
239
	/**
240
	 * Get the LinkedIn Adapter
241
	 *
242
	 * @return \Hybrid_Providers_LinkedIn
243
	 */
244
	public function getLinkedIn(){
245
		return $this->getProvider(null, "linkedin");
246
	}
247
248
    /**
249
     * Get the LinkedIn api (LinkedIn PHP-client)
250
     *
251
     * @return \LinkedIn
252
     */
253
	public function getLinkedInApi(){
254
		return $this->getLinkedIn()->api();
255
	}
256
257
	/**
258
	 * Get if auth token is expired
259
	 * @param HybridAuthSessionData $data
260
	 *
261
	 * @return boolean
262
	 */
263
	public function isExpiredSession(HybridAuthSessionData $data)
264
	{
265
		if($data->getExpiresAt() <  new \DateTime()){
266
267
			return true;
268
		}
269
270
		return false;
271
	}
272
}