Completed
Push — master ( 694417...116d3c )
by Dominik
04:44
created

AzineHybridAuth::deleteSession()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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