Overview

Namespaces

  • Genetsis
    • core
      • activityid
      • user
  • None

Classes

  • Genetsis\ActivityApi
  • Genetsis\AutoloaderClass
  • Genetsis\Config
  • Genetsis\core\AccessToken
  • Genetsis\core\activityid\Address
  • Genetsis\core\activityid\ContextType
  • Genetsis\core\activityid\Device
  • Genetsis\core\activityid\Location
  • Genetsis\core\activityid\ObjectType
  • Genetsis\core\activityid\Position
  • Genetsis\core\activityid\QualityType
  • Genetsis\core\activityid\Request
  • Genetsis\core\activityid\Response
  • Genetsis\core\activityid\SocialNetwork
  • Genetsis\core\activityid\Verbs
  • Genetsis\core\ClientToken
  • Genetsis\core\Encryption
  • Genetsis\core\FileCache
  • Genetsis\core\LogConfig
  • Genetsis\core\LoginStatus
  • Genetsis\core\LoginStatusType
  • Genetsis\core\OAuth
  • Genetsis\core\OAuthConfig
  • Genetsis\core\OauthTemplate
  • Genetsis\core\RefreshToken
  • Genetsis\core\Request
  • Genetsis\core\StoredToken
  • Genetsis\core\Things
  • Genetsis\core\User
  • Genetsis\core\user\Brand
  • Genetsis\core\user\QueryUserData
  • Genetsis\Identity
  • Genetsis\URLBuilder
  • Genetsis\UserApi
  • Logger
  • LoggerAppender
  • LoggerAppenderConsole
  • LoggerAppenderDailyFile
  • LoggerAppenderDailyRollingFile
  • LoggerAppenderEcho
  • LoggerAppenderFile
  • LoggerAppenderFirePHP
  • LoggerAppenderMail
  • LoggerAppenderMailEvent
  • LoggerAppenderMongoDB
  • LoggerAppenderNull
  • LoggerAppenderPDO
  • LoggerAppenderPhp
  • LoggerAppenderPool
  • LoggerAppenderRollingFile
  • LoggerAppenderSocket
  • LoggerAppenderSyslog
  • LoggerAutoloader
  • LoggerConfigurable
  • LoggerConfigurationAdapterINI
  • LoggerConfigurationAdapterPHP
  • LoggerConfigurationAdapterXML
  • LoggerConfiguratorDefault
  • LoggerFilter
  • LoggerFilterDenyAll
  • LoggerFilterLevelMatch
  • LoggerFilterLevelRange
  • LoggerFilterStringMatch
  • LoggerFormattingInfo
  • LoggerHierarchy
  • LoggerLayout
  • LoggerLayoutHtml
  • LoggerLayoutPattern
  • LoggerLayoutSerialized
  • LoggerLayoutSimple
  • LoggerLayoutTTCC
  • LoggerLayoutXml
  • LoggerLevel
  • LoggerLocationInfo
  • LoggerLoggingEvent
  • LoggerMDC
  • LoggerNDC
  • LoggerOptionConverter
  • LoggerPatternConverter
  • LoggerPatternConverterClass
  • LoggerPatternConverterCookie
  • LoggerPatternConverterDate
  • LoggerPatternConverterEnvironment
  • LoggerPatternConverterFile
  • LoggerPatternConverterLevel
  • LoggerPatternConverterLine
  • LoggerPatternConverterLiteral
  • LoggerPatternConverterLocation
  • LoggerPatternConverterLogger
  • LoggerPatternConverterMDC
  • LoggerPatternConverterMessage
  • LoggerPatternConverterMethod
  • LoggerPatternConverterNDC
  • LoggerPatternConverterNewLine
  • LoggerPatternConverterProcess
  • LoggerPatternConverterRelative
  • LoggerPatternConverterRequest
  • LoggerPatternConverterServer
  • LoggerPatternConverterSession
  • LoggerPatternConverterSessionID
  • LoggerPatternConverterSuperglobal
  • LoggerPatternConverterThrowable
  • LoggerPatternParser
  • LoggerReflectionUtils
  • LoggerRendererDefault
  • LoggerRendererException
  • LoggerRendererMap
  • LoggerRoot
  • LoggerThrowableInformation
  • LoggerUtils

Interfaces

  • Genetsis\core\iTokenTypes
  • LoggerConfigurationAdapter
  • LoggerConfigurator
  • LoggerRenderer

Exceptions

  • Genetsis\core\InvalidGrantException
  • LoggerException
  • Overview
  • Namespace
  • Class
  1: <?php
  2: /**
  3:  * GID library for PHP
  4:  *
  5:  * @package    GIDSdk
  6:  * @copyright  Copyright (c) 2012 Genetsis
  7:  * @version    2.0
  8:  * @see       http://developers.genetsisid.com
  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:  * This is the main class of the Genetsis ID library.
 31:  *
 32:  * It's the class that wraps the whole set of classes of the library and
 33:  * that you'll have to use the most. With it, you'll be able to check if a
 34:  * user is logged, log them out, obtain the personal data of any user,
 35:  * and check if a user has enough data to take part in a promotion, upload
 36:  * content or carry out an action that requires a specific set of personal
 37:  * data.
 38:  *
 39:  * Sample usage:
 40:  * <code>
 41:  *    Identity::init();
 42:  *    // ...
 43:  * </code>
 44:  *
 45:  * @package  Genetsis
 46:  * @version  2.0
 47:  * @access   public
 48:  */
 49: class Identity
 50: {
 51:     /** @var Things Object to store Genetsis ID's session data. */
 52:     private static $gid_things;
 53:     /** @var \Logger Object for logging actions. */
 54:     private static $logger;
 55:     /** @var boolean Inidicates if Identity has been initialized */
 56:     private static $initialized = false;
 57:     /** @var boolean Inidicates if synchronizeSessionWithServer has been called */
 58:     private static $synchronized = false;
 59: 
 60:     /**
 61:      * When you initialize the library with this method, only the configuration defined in "oauthconf.xml" file of the gid_client is loaded
 62:      * You must synchronize data with server if you need access to client or access token. This method is used for example, in ckactions.php actions.
 63:      *
 64:      * @param string $gid_client
 65:      * @throws Exception
 66:      */
 67:     public static function initConfig($gid_client = 'default')
 68:     {
 69:         self::init($gid_client, false);
 70:     }
 71: 
 72:     /**
 73:      * When you initialize the library, the configuration defined in "oauthconf.xml" file of the gid_client is loaded
 74:      * and by default this method auto-sync data (client_token, access_token,...) with server
 75:      *
 76:      * @param string $gid_client GID Client to load
 77:      * @param boolean $sync Indicates if automatic data synchronization with the server is enabled
 78:      * @param string $ini_path path of the configuration of the library (gid.ini file) if no argument passed, the default path and file will be /config/gid.ini
 79:      * @throws Exception
 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:                 // Init config library
 91:                 Config::init($gid_client, $ini_path);
 92: 
 93:                 // Initialize Logger, if we create 'gidlog' cookie, we enabled log.
 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:                 // Initialize Cache.
106:                 FileCache::init(Config::cachePath(), Config::environment());
107:                 // Initialize OAuth Config
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:      * This method verifies the authorization tokens (client_token,
124:      * access_token and refresh_token). Also updates the web client status,
125:      * storing the client_token, access_token and refresh tokend and
126:      * login_status in Things {@link Things}.
127:      *
128:      * Is INVOKE ON EACH REQUEST in order to check and update
129:      * the status of the user (not logged, logged or connected), and
130:      * verify that every token that you are gonna use before is going to be
131:      * valid.
132:      *
133:      * @return void
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:      * Checks and updates the "client_token" and cache if we have a valid one
175:      * If we don not have a Client Token in session, we check if we have a cookie
176:      * If we don not have a client Token in session or in a cookie, We request a new Client Token.
177:      * This method set the Client Token in Things
178:      *
179:      * @return void
180:      * @throws \Exception
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:      * Checks if user is logged via SSO (datr cookie) - Single Sign On
212:      *
213:      * The method obtain the "access_token" of the logged user in
214:      * "*.cocacola.es" through the cookie, with Grant Type EXCHANGE_SESSION
215:      * To SSO on domains that are not under .cocacola.es the site must include this file
216:      * <script type="text/javascript" src="https://register.cocacola.es/login/sso"></script>
217:      *
218:      * @return void
219:      * @throws /Exception
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:      * Checks if a token has expired.
247:      *
248:      * @param integer $expiresAt The expiration date. In UNIX timestamp.
249:      * @return boolean TRUE if is expired or FALSE otherwise.
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:      * Checks and refresh the user's "access_token".
261:      *
262:      * @return void
263:      * @throws /Exception
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:      * Deletes the local data of the user's session.
284:      *
285:      * @return void
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:      * Checks the user's status from Validate Bearer.
309:      * Update Things {@link Things} login status
310:      *
311:      * @return void
312:      * @throws /Exception
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:      * Helper to check if the user is connected (logged on Genetsis ID)
333:      *
334:      * @return boolean TRUE if is logged, FALSE otherwise.
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:      * Helper to access library data
348:      *
349:      * @return \Genetsis\core\Things
350:      */
351:     public static function getThings()
352:     {
353:         return self::$gid_things;
354:     }
355: 
356:     /**
357:      * In that case, the url of "post-login" will retrieve an authorization
358:      * code as a GET parameter.
359:      *
360:      * Once the authorization code is provided to the web client, the SDK
361:      * will send it again to Genetsis ID at "token_endpoint" to obtain the
362:      * "access_token" of the user and create the cookie.
363:      *
364:      * This method is needed to authorize user when the web client takes
365:      * back the control of the browser.
366:      *
367:      * @param string $code Authorization code returned by Genetsis ID.
368:      * @return void
369:      * @throws /Exception
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:      * Checks if the user have been completed all required fields for that
396:      * section.
397:      *
398:      * The "scope" (section) is a group of fields configured in Genetsis ID for
399:      * a web client.
400:      *
401:      * A section can be also defined as a "part" (section) of the website
402:      * (web client) that only can be accesed by a user who have filled a
403:      * set of personal information configured in Genetsis ID (all of the fields
404:      * required for that section).
405:      *
406:      * This method is commonly used for promotions or sweepstakes: if a
407:      * user wants to participate in a promotion, the web client must
408:      * ensure that the user have all the fields filled in order to let him
409:      * participate.
410:      *
411:      * @param $scope string Section-key identifier of the web client. The
412:      *     section-key is located in "oauthconf.xml" file.
413:      * @throws \Exception
414:      * @return boolean TRUE if the user have already completed all the
415:      *     fields needed for that section, false in otherwise
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:      * Performs the logout process.
434:      *
435:      * It makes:
436:      * - The logout call to Genetsis ID
437:      * - Clear cookies
438:      * - Purge Tokens and local data for the logged user
439:      *
440:      * @return void
441:      * @throws Exception
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:      * Returns a clientToken if user is not logged, and accessToken if user is logged
460:      *
461:      * @return mixed An instance of {@link AccessToken} or
462:      *     {@link ClientToken}
463:      * @throws \Exception if we have not a valid Token
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:      * Helper to access an static instance of Logger
483:      *
484:      * @return \Logger
485:      */
486:     public static function getLogger()
487:     {
488:         return self::$logger;
489:     }
490: 
491:     /**
492:      * Update the user's "access_token" from persistent data (SESSION or
493:      * COOKIE)
494:      *
495:      * @return void
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: }
API documentation generated by ApiGen