Completed
Push — master ( cb56f8...e7e2cc )
by Dominik
08:03
created

AzineHybridAuth::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2.0145

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 11
cts 13
cp 0.8462
rs 9.4285
cc 2
eloc 11
nc 2
nop 7
crap 2.0145
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 2
	public function __construct(UrlGeneratorInterface $router, TokenStorageInterface $tokenStorage, ObjectManager $manager, $config, $storeForUser, $storeAsCookie, $expiresInDays){
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
        $this->expiresInDays = $expiresInDays;
79 2
	}
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
100
        // try to get session-info from database
101
        if($this->currentUser instanceof UserInterface) {
102
            $isExpiredSession = false;
103
            $username = $this->currentUser->getUsername();
104
            $result = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $username, 'provider' => $provider));
105
106
            if ($result instanceof HybridAuthSessionData) {
107
                $isExpiredSession = $this->isExpiredSession($result);
108
            }
109
110
111
            if ($isExpiredSession) {
112
                $this->deleteSession($provider);
113
            }
114
115
            if (!$isExpiredSession && $this->storeForUser) {
116
                if ($result) {
117
                    $sessionData = $result->getSessionData();
118
                    $restoredFromDB = true;
119
                }
120
            }
121
        }
122
		if($sessionData === null && $cookieSessionData !== null) {
123
			// try from cookie
124
			$sessionData = gzinflate($cookieSessionData);
125
126
			// user is looged in but auth session is not yet stored in db => store now
127
			if(!$restoredFromDB){
128
				$this->saveAuthSessionData($sessionData, $provider);
129
			}
130
		}
131
		if($sessionData) {
132
			$hybridAuth->restoreSessionData($sessionData);
133
		}
134
135
		return $hybridAuth;
136
	}
137
138
	/**
139
	 * @param Request $request
140
	 * @param $provider
141
	 * @param $sessionData
142
	 * @return Cookie | null
143
	 */
144
	public function storeHybridAuthSessionData(Request $request, $provider, $sessionData){
145
		$this->saveAuthSessionData($sessionData, $provider);
146
147
		if($this->storeAsCookie){
148
			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...
149
		}
150
		return null;
151
	}
152
153
    /**
154
     * Delete the HybridAuthSessionData entity from the database
155
     * @param $provider
156
     */
157
    public function deleteSession($provider){
158
        if($this->currentUser instanceof UserInterface) {
159
            $result = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => $provider));
160
            if ($result) {
161
                $this->objectManager->remove($result);
162
                $this->objectManager->flush();
163
            }
164
        }
165
    }
166
167
    /**
168
     * Save as HybridAuthSessionData entity to the database.
169
     * Checks the bundle configuration before saving.
170
     * @param $sessionData
171
     * @param $provider
172
     */
173
	private function saveAuthSessionData($sessionData, $provider){
174
        if($this->storeForUser && $this->currentUser instanceof UserInterface) {
175
            $hybridAuthData = $this->objectManager->getRepository("AzineHybridAuthBundle:HybridAuthSessionData")->findOneBy(array('username' => $this->currentUser->getUsername(), 'provider' => strtolower($provider)));
176
            if (!$hybridAuthData) {
177
                $hybridAuthData = new HybridAuthSessionData();
178
                $hybridAuthData->setUserName($this->currentUser->getUsername());
179
                $hybridAuthData->setProvider(strtolower($provider));
180
                $hybridAuthData->setExpiresAt(new \DateTime('+ '. $this->expiresInDays .' days'));
181
                $this->objectManager->persist($hybridAuthData);
182
            }
183
            $hybridAuthData->setSessionData($sessionData);
184
            $this->objectManager->flush();
185
        }
186
	}
187
188
	public function getCookieName($provider){
189
		return self::cookieName."_".strtolower($provider);
190
	}
191
192
	/**
193
	 * Use this function to get access to a HybridAuthProvider.
194
	 *
195
	 * Calling this method will log the user in (make a roundtrip to the providers site and back to your site again)
196
	 * and call the page again that you came from.
197
	 *
198
	 * When logged (allready) it will return the hybridAuth provider.
199
	 *
200
	 * @param $authSessionData
201
	 * @param string $provider_id
202
	 * @param boolean $require_login
203
	 * @return \Hybrid_Provider_Model
204
	 */
205
	public function getProvider($authSessionData, $provider_id, $require_login = true){
206
		$adapter = $this->getInstance($authSessionData, $provider_id)->getAdapter($provider_id);
207
		if($require_login && !$adapter->isUserConnected()){
208
			$adapter->login();
209
		}
210
		return $adapter;
211
	}
212
213
	/**
214
	 * Check if the current user has allowed access to the given provider
215
	 * @param Request $request
216
	 * @param string $provider_id
217
	 * @return bool true if access to the provider is granted for this app.
218
	 */
219
	public function isConnected(Request $request, $provider_id){
220
        $sessionData = $request->cookies->get($this->getCookieName($provider_id));
221
		$adapter = $this->getInstance($sessionData, $provider_id)->getAdapter($provider_id);
222
		$connected = $adapter->isUserConnected();
223
		return $connected;
224
	}
225
226
	/**
227
     * Get the Xing Adapter
228
     * @return \Hybrid_Providers_XING
229
     */
230
	public function getXing(){
231
		return $this->getProvider(null, "xing");
232
	}
233
234
	/**
235
	 * Get the Xing api (OAuthClient)
236
	 *
237
	 * @return \OAuth1Client
238
	 */
239
	public function getXingApi(){
240
		return $this->getXing()->api();
241
	}
242
243
	/**
244
	 * Get the LinkedIn Adapter
245
	 *
246
	 * @return \Hybrid_Providers_LinkedIn
247
	 */
248
	public function getLinkedIn(){
249
		return $this->getProvider(null, "linkedin");
250
	}
251
252
    /**
253
     * Get the LinkedIn api (LinkedIn PHP-client)
254
     *
255
     * @return \LinkedIn
256
     */
257
	public function getLinkedInApi(){
258
		return $this->getLinkedIn()->api();
259
	}
260
261
	/**
262
	 * Get if auth token is expired
263
	 * @param HybridAuthSessionData $data
264
	 *
265
	 * @return boolean
266
	 */
267 2
	public function isExpiredSession(HybridAuthSessionData $data)
268
	{
269 2
		if($data->getExpiresAt() <  new \DateTime()){
270
271 1
			return true;
272
		}
273
274 1
		return false;
275
	}
276
}