1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10: namespace Genetsis;
11:
12: require_once(dirname(__FILE__) . "/Autoloader.php");
13:
14: use Exception;
15: use Genetsis\core\ClientToken;
16: use Genetsis\core\Things;
17: use Genetsis\core\FileCache;
18: use Genetsis\core\InvalidGrantException;
19: use Genetsis\core\iTokenTypes;
20: use Genetsis\core\LogConfig;
21: use Genetsis\core\LoginStatusType;
22: use Genetsis\core\OAuth;
23: use Genetsis\core\OAuthConfig;
24:
25: if (session_id() === '') {
26: session_start();
27: }
28:
29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48:
49: class Identity
50: {
51:
52: private static $gid_things;
53:
54: private static $logger;
55:
56: private static $initialized = false;
57:
58: private static $synchronized = false;
59:
60: 61: 62: 63: 64: 65: 66:
67: public static function initConfig($gid_client = 'default')
68: {
69: self::init($gid_client, false);
70: }
71:
72: 73: 74: 75: 76: 77: 78: 79: 80:
81: public static function init($gid_client = 'default', $sync = true, $ini_path = null)
82: {
83: try {
84: if (!self::$initialized) {
85: if (!isset($ini_path)) $ini_path = dirname(__FILE__) . '/../../../../config/gid.ini';
86: Config::$ini_path = $ini_path;
87: self::$initialized = true;
88: AutoloaderClass::init();
89:
90:
91: Config::init($gid_client, $ini_path);
92:
93:
94: if ((Config::logLevel() === 'OFF') && (!isset($_COOKIE['gidlog']))) {
95: include_once dirname(__FILE__) . '/core/log4php/LoggerEmpty.php';
96: } else {
97: if (!class_exists('Logger')) {
98: include_once dirname(__FILE__) . '/core/log4php/Logger.php';
99: }
100: \Logger::configure('main', new LogConfig(Config::logLevel(), Config::logPath()));
101: }
102:
103: self::$logger = \Logger::getLogger("main");
104:
105:
106: FileCache::init(Config::cachePath(), Config::environment());
107:
108: OAuthConfig::init();
109:
110: self::$gid_things = new Things();
111:
112: if ($sync) {
113: self::synchronizeSessionWithServer();
114: }
115: }
116: } catch (Exception $e) {
117: self::$logger->error($e->getMessage());
118: throw $e;
119: }
120: }
121:
122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134:
135: public static function synchronizeSessionWithServer()
136: {
137: if (!self::$synchronized) {
138: self::$synchronized = true;
139:
140: try {
141: self::$logger->debug('Synchronizing session with server');
142: self::checkAndUpdateClientToken();
143:
144: self::loadUserTokenFromPersistence();
145:
146: if (self::$gid_things->getAccessToken() == null) {
147: self::$logger->debug('User is not logged, check SSO');
148: self::checkSSO();
149: if (self::$gid_things->getRefreshToken() != null) {
150: self::$logger->debug('User not logged but has Refresh Token');
151: self::checkAndRefreshAccessToken();
152: }
153: } else {
154: if (self::isExpired(self::$gid_things->getAccessToken()->getExpiresAt())) {
155: self::$logger->debug('User logged but Access Token is expires');
156: self::checkAndRefreshAccessToken();
157: } else {
158: self::$logger->debug('User logged - check Validate Bearer');
159: self::checkLoginStatus();
160: }
161: if (!self::isConnected()) {
162: self::$logger->warn('User logged but is not connected (something wrong) - clear session data');
163: self::clearLocalSessionData();
164: }
165: }
166: } catch (Exception $e) {
167: self::$logger->error($e->getMessage());
168: }
169: $_SESSION['Things'] = @serialize(self::$gid_things);
170: }
171: }
172:
173: 174: 175: 176: 177: 178: 179: 180: 181:
182: private static function checkAndUpdateClientToken()
183: {
184: try {
185: self::$logger->debug('Checking and update client_token.');
186: if (!(($client_token = unserialize(FileCache::get('client_token'))) instanceof ClientToken) || ($client_token->getValue() == '')) {
187: self::$logger->debug('Get Client token');
188:
189: if ((self::$gid_things->getClientToken() == null) || (OAuth::getStoredToken(iTokenTypes::CLIENT_TOKEN) == null)) {
190: self::$logger->debug('Not has clientToken in session or cookie');
191:
192: if (!$client_token = OAuth::getStoredToken(iTokenTypes::CLIENT_TOKEN)) {
193: self::$logger->debug('Token Cookie does not exists. Requesting a new one.');
194: $client_token = OAuth::doGetClientToken(OauthConfig::getEndpointUrl('token_endpoint'));
195: }
196: self::$gid_things->setClientToken($client_token);
197: } else {
198: self::$logger->debug('Client Token from session');
199: }
200: FileCache::set('client_token', serialize(self::$gid_things->getClientToken()), self::$gid_things->getClientToken()->getExpiresIn());
201: } else {
202: self::$logger->debug('Client Token from cache');
203: self::$gid_things->setClientToken($client_token);
204: }
205: } catch (Exception $e) {
206: throw $e;
207: }
208: }
209:
210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220:
221: private static function checkSSO()
222: {
223: try {
224: if ((isset($_COOKIE['datr']) && ($_COOKIE['datr'] != ''))||(isset($_COOKIE['datr_']) && ($_COOKIE['datr_'] != ''))) {
225: self::$logger->info('DATR cookie was found.');
226:
227: $response = OAuth::doExchangeSession(OauthConfig::getEndpointUrl('token_endpoint'), ($_COOKIE['datr'] != '') ? $_COOKIE['datr'] : $_COOKIE['datr_']);
228: self::$gid_things->setAccessToken($response['access_token']);
229: self::$gid_things->setRefreshToken($response['refresh_token']);
230: self::$gid_things->setLoginStatus($response['login_status']);
231: } else {
232: self::$logger->debug('DATR cookie not exist, user is not logged');
233: }
234: } catch (InvalidGrantException $e) {
235: unset($_COOKIE[OAuth::SSO_COOKIE_NAME]);
236: setcookie(OAuth::SSO_COOKIE_NAME, null, -1, null, '.cocacola.es');
237:
238: self::$logger->warn('Invalid Grant, check an invalid DATR');
239: throw $e;
240: } catch (Exception $e) {
241: throw $e;
242: }
243: }
244:
245: 246: 247: 248: 249: 250:
251: private static function isExpired($expiresAt)
252: {
253: if (!is_null($expiresAt)) {
254: return (time() > $expiresAt);
255: }
256: return true;
257: }
258:
259: 260: 261: 262: 263: 264:
265: private static function checkAndRefreshAccessToken()
266: {
267: try {
268: self::$logger->debug('Checking and refreshing the AccessToken.');
269:
270: $response = OAuth::doRefreshToken(OauthConfig::getEndpointUrl('token_endpoint'));
271: self::$gid_things->setAccessToken($response['access_token']);
272: self::$gid_things->setRefreshToken($response['refresh_token']);
273: self::$gid_things->setLoginStatus($response['login_status']);
274: } catch (InvalidGrantException $e) {
275: self::clearLocalSessionData();
276: throw $e;
277: } catch (Exception $e) {
278: throw $e;
279: }
280: }
281:
282: 283: 284: 285: 286:
287: private static function clearLocalSessionData()
288: {
289: self::$logger->debug('Clear Session Data');
290: self::$gid_things->setAccessToken(null);
291: self::$gid_things->setRefreshToken(null);
292: self::$gid_things->setLoginStatus(null);
293:
294: OAuth::deleteStoredToken(iTokenTypes::ACCESS_TOKEN);
295: OAuth::deleteStoredToken(iTokenTypes::REFRESH_TOKEN);
296:
297: if (isset($_SESSION)) {
298: unset($_SESSION['Things']);
299: foreach ($_SESSION as $key => $val) {
300: if (preg_match('#^headerAuth#Ui', $key) || in_array($key, array('nickUserLogged', 'isConnected'))) {
301: unset($_SESSION[$key]);
302: }
303: }
304: }
305: }
306:
307: 308: 309: 310: 311: 312: 313:
314: private static function checkLoginStatus()
315: {
316: try {
317: self::$logger->debug('Checking login status');
318: if (self::$gid_things->getLoginStatus()->getConnectState() == LoginStatusType::connected) {
319: self::$logger->debug('User is connected, check access token');
320: $loginStatus = OAuth::doValidateBearer(OauthConfig::getEndpointUrl('token_endpoint'));
321: self::$gid_things->setLoginStatus($loginStatus);
322: }
323: } catch (InvalidGrantException $e) {
324: self::$logger->warn('Invalid Grant, maybe access token is expires and sdk not checkit - call to refresh token');
325: self::checkAndRefreshAccessToken();
326: } catch (Exception $e) {
327: throw $e;
328: }
329: }
330:
331: 332: 333: 334: 335:
336: public static function isConnected()
337: {
338: if ((!is_null(self::getThings())) && (!is_null(self::getThings()->getAccessToken())) &&
339: (!is_null(self::getThings()->getLoginStatus()) && (self::getThings()->getLoginStatus()->getConnectState() == LoginStatusType::connected))
340: ) {
341: return true;
342: }
343: return false;
344: }
345:
346: 347: 348: 349: 350:
351: public static function getThings()
352: {
353: return self::$gid_things;
354: }
355:
356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370:
371: public static function authorizeUser($code)
372: {
373: try {
374: self::$logger->debug('Authorize user');
375:
376: if ($code == '') {
377: throw new Exception('Authorize Code is empty');
378: }
379:
380: $response = OAuth::doGetAccessToken(OauthConfig::getEndpointUrl('token_endpoint'), $code, OauthConfig::getRedirectUrl('postLogin'));
381: self::$gid_things->setAccessToken($response['access_token']);
382: self::$gid_things->setRefreshToken($response['refresh_token']);
383: self::$gid_things->setLoginStatus($response['login_status']);
384:
385: $_SESSION['Things'] = @serialize(self::$gid_things);
386:
387: } catch ( \Genetsis\core\InvalidGrantException $e) {
388: self::$logger->error($e->getMessage());
389: } catch (Exception $e) {
390: self::$logger->error($e->getMessage());
391: }
392: }
393:
394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416:
417: public static function checkUserComplete($scope)
418: {
419: $userCompleted = false;
420: try {
421: self::$logger->info('Checking if the user has filled its data out for this section:' . $scope);
422:
423: if (self::isConnected()) {
424: $userCompleted = OAuth::doCheckUserCompleted(OAuthConfig::getApiUrl('user-api', 'base_url') . OauthConfig::getApiUrl('api.user', 'user'), $scope);
425: }
426: } catch (Exception $e) {
427: self::$logger->error($e->getMessage());
428: }
429: return $userCompleted;
430: }
431:
432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442:
443: public static function logoutUser()
444: {
445: try {
446: if ((self::$gid_things->getAccessToken() != null) && (self::$gid_things->getRefreshToken() != null)) {
447: self::$logger->info('User Single Sign Logout');
448: UserApi::deleteCacheUser(self::$gid_things->getLoginStatus()->getCkUsid());
449:
450: OAuth::doLogout(OauthConfig::getEndpointUrl('logout_endpoint'));
451: self::clearLocalSessionData();
452: }
453: } catch (Exception $e) {
454: self::$logger->error($e->getMessage());
455: }
456: }
457:
458: 459: 460: 461: 462: 463: 464:
465: private static function getTokenUser()
466: {
467: try {
468: if (!is_null(self::$gid_things->getAccessToken())) {
469: self::$logger->debug('Get AccessToken, user logged');
470: return self::$gid_things->getAccessToken();
471: } else {
472: self::$logger->debug('Get ClientToken, user is NOT logged');
473: return self::$gid_things->getClientToken();
474: }
475: } catch (Exception $e) {
476: self::$logger->error($e->getMessage());
477: throw new Exception('Not valid token');
478: }
479: }
480:
481: 482: 483: 484: 485:
486: public static function getLogger()
487: {
488: return self::$logger;
489: }
490:
491: 492: 493: 494: 495: 496:
497: private static function loadUserTokenFromPersistence ()
498: {
499: try {
500: if (is_null(self::$gid_things->getAccessToken())){
501: self::$logger->debug('Load access token from cookie');
502:
503: if (OAuth::hasToken(iTokenTypes::ACCESS_TOKEN)) {
504: self::$gid_things->setAccessToken(OAuth::getStoredToken(iTokenTypes::ACCESS_TOKEN));
505: }
506: if (OAuth::hasToken(iTokenTypes::REFRESH_TOKEN)) {
507: self::$gid_things->setRefreshToken(OAuth::getStoredToken(iTokenTypes::REFRESH_TOKEN));
508: }
509: }
510:
511:
512: } catch (Exception $e) {
513: self::$logger->error('['.__CLASS__.']['.__FUNCTION__.']['.__LINE__.']'.$e->getMessage());
514: }
515: }
516: }