public function testItCorrectlyReadsDataFromDefaultLocation()
 {
     $string = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3";
     $expected = array('user_agent' => array("family" => "Mobile Safari", "major" => "5", "minor" => "1", "patch" => null), "os" => array("family" => "iOS", "major" => "5", "minor" => "0", "patch" => null), "device" => array("device" => "iPhone", "brand" => "Apple", "model" => "iPhone"));
     $parser = new Parser();
     $result = $parser->parse($string);
     $this->assertEquals($expected, $result);
 }
Example #2
0
 public function testItCorrectlyParsesAMatchingString()
 {
     $regexData = array('user_agent' => array('@som(est)r(in)g@' => array('family' => 'foo', 'major' => 'bar $2', 'minor' => 1, 'patch' => 2, 'custom' => 'fizz $1')), 'device' => array('@somestring@' => array('device' => 'fizz', 'brand' => 'buzz', 'model' => 3)), 'os' => array('@(some)str(ing)@' => array('minor' => 5, 'patch' => 6)));
     $expected = array('user_agent' => array('family' => 'foo', 'major' => 'bar in', 'minor' => '1', 'patch' => '2', 'custom' => 'fizz est'), 'device' => array('device' => 'fizz', 'brand' => 'buzz', 'model' => '3'), 'os' => array('family' => 'some', 'major' => 'ing', 'minor' => '5', 'patch' => '6'));
     $string = "somestring";
     $parser = new Parser($regexData);
     $result = $parser->parse($string);
     $this->assertEquals($expected, $result);
 }
Example #3
0
 /**
  * @param $test
  * @param $type
  * @return bool
  */
 private function runTest($test, $type)
 {
     $expected = array_diff_key($test, array('user_agent_string' => 1, 'js_ua' => 1, 'js_user_agent_v1' => 1));
     $parsed = $this->parser->parse($test['user_agent_string']);
     if ($this->diff($expected, (array) $parsed[$type])) {
         $this->printError($test['user_agent_string'], $parsed[$type], $expected);
         return false;
     }
     if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
         $this->printError($test['user_agent_string'], $parsed[$type], $expected, true);
     }
     return true;
 }
function detectAgent($ua)
{
    //List of mobile browsers, tablets, and mobile devices
    //Browser list source UA Classifier project: https://bitbucket.org/Jarnar/ua-classifier
    $mobileOSs = array('windows phone 6.5', 'windows ce', 'symbian os');
    $mobileBrowsers = array('firefox mobile', 'opera mobile', 'opera mini', 'mobile safari', 'webos', 'ie mobile', 'playstation portable', 'nokia', 'blackberry', 'palm', 'silk', 'android', 'maemo', 'obigo', 'netfront', 'avantgo', 'teleca', 'semc-browser', 'bolt', 'iris', 'up.browser', 'symphony', 'minimo', 'bunjaloo', 'jasmine', 'dolfin', 'polaris', 'brew', 'chrome mobile', 'uc browser', 'tizen browser');
    $tablets = array('kindle', 'ipad', 'playbook', 'touchpad', 'dell streak', 'galaxy tab', 'xoom');
    $mobileDevices = array('iphone', 'ipod', 'ipad', 'htc', 'kindle', 'lumia', 'amoi', 'asus', 'bird', 'dell', 'docomo', 'huawei', 'i-mate', 'kyocera', 'lenovo', 'lg', 'kin', 'motorola', 'philips', 'samsung', 'softbank', 'palm', 'hp ', 'generic feature phone', 'generic smartphone');
    unset($parser);
    //unsetting if previously set, TODO: Identify in this is needed
    //Instantiate the parser object and build result
    $parser = Parser::create();
    $result = $parser->parse($ua);
    //Identify devices with the other device family
    if (strtolower($result->device->family) == "other") {
        $deviceType = 'Desktop';
    }
    //Identify devices with the spider device family
    if (strtolower($result->device->family) == 'spider') {
        $deviceType = 'Spider';
    }
    //Identify devices with the Mobile device family
    if (in_array(strtolower($result->ua->family), $mobileBrowsers) || in_array(strtolower($result->os->family), $mobileOSs) || in_array(strtolower($result->device->family), $mobileDevices)) {
        $deviceType = 'Mobile';
    }
    //Identify devices with the Tablet device family
    if (in_array(strtolower($result->device->family), $tablets)) {
        $deviceType = 'Tablet';
    }
    return $deviceType;
}
 private function getBrowserInfo()
 {
     $ua = $_SERVER['HTTP_USER_AGENT'];
     $parser = Parser::create();
     $result = $parser->parse($ua);
     $browser_info = array("browser_name" => $result->ua->family, "browser_version_major" => $result->ua->major, "browser_version_minor" => $result->ua->minor, "browser_version_patch" => $result->ua->patch, "os_name" => $result->os->family, "os_version_major" => $result->os->major, "os_version_minor" => $result->os->minor, "os_version_patch" => $result->os->patch, "device_type" => $result->device->family, "device_brand" => $result->device->brand, "device_model" => $result->device->model, "browser_ua" => $result->originalUserAgent);
     return $browser_info;
 }
Example #6
0
 /**
  *
  * @return Parser
  */
 public function getParser()
 {
     if ($this->parser !== null) {
         return $this->parser;
     }
     $this->parser = Parser::create();
     return $this->parser;
 }
Example #7
0
function get_user_agent_version($user_agent)
{
    static $parser = null;
    if (is_null($parser)) {
        $parser = UAParser::create();
    }
    return $parser->parse($user_agent)->ua->toString();
}
Example #8
0
 public function __construct($basePath, $userAgent = null)
 {
     if (!$userAgent && isset($_SERVER['HTTP_USER_AGENT'])) {
         $userAgent = $_SERVER['HTTP_USER_AGENT'];
     }
     $this->parser = Parser::create()->parse($userAgent);
     $this->userAgent = $this->parser->ua;
     $this->operatingSystem = $this->parser->os;
     $this->device = $this->parser->device;
     $this->basePath = $basePath;
     $this->originalUserAgent = $this->parser->originalUserAgent;
 }
Example #9
0
 public function testToString_2()
 {
     $userAgentString = 'PingdomBot 1.4/Other Pingdom.com_bot_version_1.4_(http://www.pingdom.com/)';
     $result = $this->parser->parse($userAgentString);
     $this->assertSame('PingdomBot 1.4/Other', $result->toString());
     $this->assertSame('PingdomBot 1.4/Other', (string) $result);
     $this->assertSame('PingdomBot 1.4', $result->ua->toString());
     $this->assertSame('PingdomBot 1.4', (string) $result->ua);
     $this->assertSame('1.4', $result->ua->toVersion());
     $this->assertSame('Other', $result->os->toString());
     $this->assertSame('Other', (string) $result->os);
     $this->assertSame('', $result->os->toVersion());
     $this->assertSame($userAgentString, $result->originalUserAgent);
 }
Example #10
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!$input->getOption('log-file') && !$input->getOption('log-dir')) {
         throw InvalidArgumentException::oneOfCommandArguments('log-file', 'log-dir');
     }
     $parser = Parser::create();
     $undefinedClients = array();
     /** @var $file SplFileInfo */
     foreach ($this->getFiles($input) as $file) {
         $path = $this->getPath($file);
         $lines = file($path);
         if (empty($lines)) {
             $output->writeln(sprintf('Skipping empty file "%s"', $file->getPathname()));
             $output->writeln('');
             continue;
         }
         $firstLine = reset($lines);
         $reader = AbstractReader::factory($firstLine);
         if (!$reader) {
             $output->writeln(sprintf('Could not find reader for file "%s"', $file->getPathname()));
             $output->writeln('');
             continue;
         }
         $output->writeln('');
         $output->writeln(sprintf('Analyzing "%s"', $file->getPathname()));
         $count = 1;
         $totalCount = count($lines);
         foreach ($lines as $line) {
             try {
                 $userAgentString = $reader->read($line);
             } catch (ReaderException $e) {
                 $count = $this->outputProgress($output, 'E', $count, $totalCount);
                 continue;
             }
             $client = $parser->parse($userAgentString);
             $result = $this->getResult($client);
             if ($result !== '.') {
                 $undefinedClients[] = json_encode(array($client->toString(), $userAgentString), JSON_UNESCAPED_SLASHES);
             }
             $count = $this->outputProgress($output, $result, $count, $totalCount);
         }
         $this->outputProgress($output, '', $count - 1, $totalCount, true);
         $output->writeln('');
     }
     $undefinedClients = $this->filter($undefinedClients);
     $fs = new Filesystem();
     $fs->dumpFile($input->getArgument('output'), join(PHP_EOL, $undefinedClients));
 }
 public function getDeviceDetector($deviceDetetorServerPath, $propertiesToDetect = null)
 {
     require_once $deviceDetetorServerPath . '/autoload.php';
     if (empty($propertiesToDetect)) {
         $propertiesToDetect = ['type', 'browserDetails', 'osDetails', 'marketingName', 'brandName'];
     }
     $propertiesToDetectJson = json_encode($propertiesToDetect);
     if (in_array('type', $propertiesToDetect) || in_array('brandName', $propertiesToDetect)) {
         if (!isset($this->deviceDetectors['full'][$propertiesToDetectJson])) {
             $this->deviceDetectors['full'][$propertiesToDetectJson] = new DeviceDetector($propertiesToDetect, \UAParser\Parser::create(), new MobileDetect());
         }
         return $this->deviceDetectors['full'][$propertiesToDetectJson];
     } else {
         if (!isset($this->deviceDetectors['partial'][$propertiesToDetectJson])) {
             $this->deviceDetectors['partial'][$propertiesToDetectJson] = new DeviceDetector($propertiesToDetect, \UAParser\Parser::create(), new NullMobileDetect());
         }
         return $this->deviceDetectors['partial'][$propertiesToDetectJson];
     }
 }
Example #12
0
 /**
  * Lookup active sessions.
  *
  * @return array
  */
 public function getActiveSessions()
 {
     $this->deleteExpiredSessions();
     $query = sprintf('SELECT * FROM %s', $this->authtokentable);
     $sessions = $this->db->fetchAll($query);
     // Parse the user-agents to get a user-friendly Browser, version and platform.
     $parser = UAParser\Parser::create();
     foreach ($sessions as $key => $session) {
         $ua = $parser->parse($session['useragent']);
         $sessions[$key]['browser'] = sprintf('%s / %s', $ua->ua->toString(), $ua->os->toString());
     }
     return $sessions;
 }
 /**
  * @param $userAgent
  *
  * @return \Application\Entity\ParticipantEntity
  */
 public function setUserAgent($userAgent)
 {
     $this->userAgent = $userAgent;
     $parser = \UAParser\Parser::create();
     $detect = new \Mobile_Detect();
     $userAgentInfo = $parser->parse($userAgent);
     $userAgentMobileInfo = $detect->setUserAgent($userAgent);
     $this->userAgentUa = $userAgentInfo->ua->family;
     $this->userAgentOs = $userAgentInfo->os->family;
     $this->userAgentDevice = $userAgentInfo->device->family;
     if ($detect->isMobile()) {
         $this->userAgentDeviceType = 'Mobile';
     } elseif ($detect->isTablet()) {
         $this->userAgentDeviceType = 'Tablet';
     }
     return $this;
 }
Example #14
0
 /**
  * Lookup active sessions.
  *
  * @return array
  */
 public function getActiveSessions()
 {
     // Parse the user-agents to get a user-friendly Browser, version and platform.
     $parser = UAParser\Parser::create();
     $this->repositoryAuthtoken->deleteExpiredTokens();
     $sessions = $this->repositoryAuthtoken->getActiveSessions() ?: [];
     foreach ($sessions as &$session) {
         $ua = $parser->parse($session->getUseragent());
         $session->setBrowser(sprintf('%s / %s', $ua->ua->toString(), $ua->os->toString()));
     }
     return $sessions;
 }
Example #15
0
 /**
  *
  * @return object данные из User Agent
  */
 public function parseUaData()
 {
     $parser = Parser::create();
     return $parser->parse($this->userAgentData);
 }
Example #16
0
 /**
  * @param string $user_agent
  */
 public function __construct($user_agent = '')
 {
     $this->user_agent = $user_agent;
     $this->detector = Parser::create()->parse($this->user_agent);
 }
Example #17
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $result = Parser::create()->parse($input->getArgument('user-agent'));
     $output->writeln(json_encode($result, JSON_PRETTY_PRINT));
 }
 function parseUserAgentInfo($detect)
 {
     $database = DB::getInstance();
     $db = $database->getConnection();
     $parser = Parser::create();
     $result = $parser->parse($detect->getUserAgent());
     //If is not mobile or tablet
     if (!$detect->isMobile() && !$detect->isTablet()) {
         switch ($result->device->family) {
             //Is Bot
             case 'Bot':
                 $type = "4";
                 $result->device->family = "Bot";
                 break;
                 //Is Desktop
             //Is Desktop
             case 'Other':
                 $type = "1";
                 $result->device->family = "Desktop";
                 break;
         }
     } else {
         //If tablet
         if ($detect->isTablet()) {
             $type = "3";
             //If mobile
         } else {
             $type = "2";
         }
     }
     //Select from DB and return ID's
     $mysql['browser'] = $db->real_escape_string($result->ua->family);
     $mysql['platform'] = $db->real_escape_string($result->os->family);
     $mysql['device'] = $db->real_escape_string($result->device->family);
     $mysql['device_type'] = $db->real_escape_string($type);
     //Get browser ID
     $browser_sql = "SELECT browser_id FROM 202_browsers WHERE browser_name='" . $mysql['browser'] . "'";
     $browser_result = _mysqli_query($browser_sql);
     $browser_row = $browser_result->fetch_assoc();
     if ($browser_row) {
         $browser_id = $browser_row['browser_id'];
     } else {
         $browser_sql = "INSERT INTO 202_browsers SET browser_name='" . $mysql['browser'] . "'";
         $browser_result = _mysqli_query($browser_sql);
         $browser_id = $db->insert_id;
     }
     //Get platform ID
     $platform_sql = "SELECT platform_id FROM 202_platforms WHERE platform_name='" . $mysql['platform'] . "'";
     $platform_result = _mysqli_query($platform_sql);
     $platform_row = $platform_result->fetch_assoc();
     if ($platform_row) {
         $platform_id = $platform_row['platform_id'];
     } else {
         $platform_sql = "INSERT INTO 202_platforms SET platform_name='" . $mysql['platform'] . "'";
         $platform_result = _mysqli_query($platform_sql);
         $platform_id = $db->insert_id;
     }
     //Get device model ID
     $device_sql = "SELECT device_id, device_type FROM 202_device_models WHERE device_name='" . $mysql['device'] . "'";
     $device_result = _mysqli_query($device_sql);
     $device_row = $device_result->fetch_assoc();
     if ($device_row) {
         $device_id = $device_row['device_id'];
         $device_type = $device_row['device_type'];
     } else {
         $device_sql = "INSERT INTO 202_device_models SET device_name='" . $mysql['device'] . "', device_type='" . $mysql['device_type'] . "'";
         $device_result = _mysqli_query($device_sql);
         $device_id = $db->insert_id;
         $device_type = $type;
     }
     $data = array('browser' => $browser_id, 'platform' => $platform_id, 'device' => $device_id, 'type' => $device_type);
     return $data;
 }
Example #19
0
<?php 
// Config
$outputFile = dirname(__DIR__) . '/test-cases.yaml';
$sources = ['uc-d' => 'https://raw.githubusercontent.com/ua-parser/uap-core/master/tests/test_device.yaml', 'uc-o' => 'https://raw.githubusercontent.com/ua-parser/uap-core/master/tests/test_os.yaml', 'uc-u' => 'https://raw.githubusercontent.com/ua-parser/uap-core/master/tests/test_ua.yaml'];
// Script
require dirname(dirname(__DIR__)) . '/vendor/autoload.php';
if (is_file($outputFile) && !is_writable($outputFile)) {
    throw new \RuntimeException('Output file is not writable');
}
$testData = [];
if (is_readable($outputFile)) {
    echo "Found existing file; loading data... ";
    $testData = \Symfony\Component\Yaml\Yaml::parse($outputFile);
    echo "Done\n\n";
}
$parser = \UAParser\Parser::create();
$addEntries = function ($sourceName, $sourcePath) use(&$testData, $parser) {
    echo "Starting source '{$sourceName}'; loading data... ";
    $source = \Symfony\Component\Yaml\Yaml::parse(file_get_contents($sourcePath));
    echo "Done\n";
    echo "Iterating entries...\n\n";
    $count = 0;
    foreach ($source['test_cases'] as $test) {
        $result = $parser->parse($test['user_agent_string']);
        if ($result->ua->family === 'Other') {
            //            continue;
        }
        $key = $result->device->family . '-' . $result->os->family . '-' . $result->ua->family;
        if (isset($testData[$key])) {
            continue;
        }
Example #20
0
 /**
  * @param $userAgent
  */
 private function parseUserAgentAndStoreInSession($userAgent)
 {
     $parser = Parser::create();
     $result = $parser->parse($userAgent);
     if (!isset($this->visitorSessionContainer->ua->family)) {
         $this->visitorSessionContainer->ua_major = $result->ua->major;
         $this->visitorSessionContainer->ua_minor = $result->ua->minor;
         $this->visitorSessionContainer->ua_patch = $result->ua->patch;
         $this->visitorSessionContainer->ua_family = $result->ua->family;
         $this->visitorSessionContainer->os_major = $result->os->major;
         $this->visitorSessionContainer->os_minor = $result->os->minor;
         $this->visitorSessionContainer->os_patch = $result->os->patch;
         $this->visitorSessionContainer->os_patchMinor = $result->os->patchMinor;
         $this->visitorSessionContainer->os_family = $result->os->family;
         $this->visitorSessionContainer->device_brand = $result->device->brand;
         $this->visitorSessionContainer->device_model = $result->device->model;
         $this->visitorSessionContainer->device_family = $result->device->family;
     }
 }
 /**
  * Cache the parsed results.
  */
 protected function cacheParserResults()
 {
     if (is_null($this->uaParserResult)) {
         $uaParser = Parser::create();
         $this->uaParserResult = $uaParser->parse($this->serverData['HTTP_USER_AGENT']);
     }
 }
Example #22
0
 public function getUserAgentParser()
 {
     $userAgentParser = \UAParser\Parser::create();
     return $userAgentParser;
 }
 /**
  * Parse the user agent string.
  *
  * @param string $agent Agent string
  *
  * @return \UAParser\Result\Client
  */
 public function parseAgent($agent)
 {
     return $this->parser->parse($agent);
 }
Example #24
0
 public function __construct(Request $request)
 {
     $parser = Parser::create();
     $this->uaParsedData = $parser->parse($request->headers->get('User-Agent'));
 }
Example #25
0
$rule_sql = "SELECT ru.id as rule_id,\n\t\t\t\t\t   ru.redirect_url,\n\t\t\t\t\t   ru.redirect_campaign,\n\t\t\t\t\t   ca.aff_campaign_id,\n\t\t\t\t\t   ca.aff_campaign_rotate,\n\t\t\t\t\t   ca.aff_campaign_url,\n\t\t\t\t\t   ca.aff_campaign_url_2,\n\t\t\t\t\t   ca.aff_campaign_url_3,\n\t\t\t\t\t   ca.aff_campaign_url_4,\n\t\t\t\t\t   ca.aff_campaign_url_5,\n\t\t\t\t\t   ca.aff_campaign_payout,\n\t\t\t\t\t   ca.aff_campaign_cloaking\n\t\t\t\tFROM 202_rotator_rules AS ru\n\t\t\t\tLEFT JOIN 202_aff_campaigns AS ca ON ca.aff_campaign_id = ru.redirect_campaign\n\t\t\t\tWHERE rotator_id='" . $mysql['rotator_id'] . "' AND status='1'";
$rule_row = foreach_memcache_mysql_fetch_assoc($db, $rule_sql);
if (!$rotator_row) {
    die;
}
AUTH::set_timezone($rotator_row['user_timezone']);
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
if ($rotator_row['maxmind'] == '1') {
    $IspData = getIspData($ip_address);
} else {
    $IspData = null;
}
//GEO Lookup
$GeoData = getGeoData($ip_address);
//User-agent parser
$parser = Parser::create();
//Device type
$detect = new Mobile_Detect();
$ua = $detect->getUserAgent();
$result = $parser->parse($ua);
if (!$detect->isMobile() && !$detect->isTablet()) {
    switch ($result->device->family) {
        //Is Bot
        case 'Bot':
            $result->device->family = "Bot";
            break;
            //Is Desktop
        //Is Desktop
        case 'Other':
            $result->device->family = "Desktop";
            break;
Example #26
0
});
$app['security.validator.user_password'] = $app->share(function ($app) {
    return new Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator($app['security'], $app['security.encoder_factory']);
});
$app['validator.validator_service_ids'] = array('doctrine.orm.validator.unique' => 'validator.unique_entity', 'security.validator.user_password' => 'security.validator.user_password');
/***** Url Generator *****/
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
/***** Http Cache *****/
$app->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => STORAGE_DIR . '/cache/http/'));
/***** User Provider *****/
$app['user.provider'] = $app->share(function () use($app) {
    return new \Application\Provider\UserProvider($app);
});
/*** UAParser ***/
$app['ua.parser'] = $app->share(function () use($app) {
    return \UAParser\Parser::create();
});
/*** Mobile Detect ***/
$app->register(new Binfo\Silex\MobileDetectServiceProvider());
/*** UAParser ***/
$app['ip.parser'] = $app->share(function () use($app) {
    return new \Application\IPParser();
});
/***** Security *****/
$securityFirewalls = array();
/*** Members Area ***/
$securityFirewalls['members-area'] = array('pattern' => '^/', 'anonymous' => true, 'form' => array('login_path' => '/members-area/login', 'check_path' => '/members-area/login/check', 'failure_path' => '/members-area/login', 'default_target_path' => '/members-area', 'use_referer' => true, 'username_parameter' => 'username', 'password_parameter' => 'password', 'csrf_protection' => true, 'csrf_parameter' => 'csrf_token', 'with_csrf' => true, 'use_referer' => true), 'logout' => array('logout_path' => '/members-area/logout', 'target' => '/members-area', 'invalidate_session' => true, 'csrf_parameter' => 'csrf_token'), 'remember_me' => $app['rememberMeOptions'], 'switch_user' => array('parameter' => 'switch_user', 'role' => 'ROLE_ALLOWED_TO_SWITCH'), 'users' => $app['user.provider']);
$app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => $securityFirewalls));
$app['security.access_rules'] = array(array('^/members-area/login', 'IS_AUTHENTICATED_ANONYMOUSLY'), array('^/members-area/register', 'IS_AUTHENTICATED_ANONYMOUSLY'), array('^/members-area/reset-password', 'IS_AUTHENTICATED_ANONYMOUSLY'), array('^/members-area', 'ROLE_USER'), array('^/members-area/oauth', 'ROLE_USER'));
$app['security.role_hierarchy'] = array('ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'), 'ROLE_ADMIN' => array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'));
/* Voters */
Example #27
0
 /**
  * Adds the user agent hash and user agent to a list for retrieval in the demo (or for any reason i guess)
  *
  * @param \Wurfl\Request\GenericRequest $request
  *
  * @return \StdClass The core template object 'filled out' from ua-parser
  * @throws \BrowscapPHP\Exception
  */
 private function createUAProperties(GenericRequest $request)
 {
     //$request->getDeviceUserAgent() . '||||' . $request->getBrowserUserAgent()
     $useragent = $request->getBrowserUserAgent();
     $parser = Parser::create();
     // classify the user agent string so we can learn more what device this really is. more for readability than anything
     /** @var \UAParser\Result\Client $client */
     $client = $parser->parse($useragent);
     $obj = new \StdClass();
     if ($request->getDeviceUserAgent() === $request->getBrowserUserAgent()) {
         $obj->originalUserAgent = $request->getBrowserUserAgent();
     } else {
         $obj->originalUserAgent = new \StdClass();
         $obj->originalUserAgent->browser = $request->getBrowserUserAgent();
         $obj->originalUserAgent->device = $request->getDeviceUserAgent();
     }
     // save properties from ua-parser
     $obj->uaparser = new \StdClass();
     $obj->uaparser->ua = new \StdClass();
     $obj->uaparser->ua->major = $client->ua->major;
     $obj->uaparser->ua->minor = $client->ua->minor;
     $obj->uaparser->ua->patch = $client->ua->patch;
     $obj->uaparser->ua->family = $client->ua->toString();
     $obj->uaparser->os = new \StdClass();
     $obj->uaparser->os->major = $client->os->major;
     $obj->uaparser->os->minor = $client->os->minor;
     $obj->uaparser->os->patch = $client->os->patch;
     $obj->uaparser->os->patchMinor = $client->os->patchMinor;
     $obj->uaparser->os->family = $client->os->toString();
     $obj->uaparser->device = new \StdClass();
     $obj->uaparser->device->brand = $client->device->brand;
     $obj->uaparser->device->model = $client->device->model;
     $obj->uaparser->device->family = $client->device->toString();
     // Now, load an INI file into BrowscapPHP\Browscap for testing the UAs
     /*
             $browscap = new Browscap();
             $browscap
                 ->setCache($this->cache)
                 ->setLogger($this->logger)
             ;
     
             $actualProps = (array) $browscap->getBrowser($useragent);
     
             $obj->browscap = new \StdClass();
     
             foreach ($actualProps as $property => $value) {
                 $obj->browscap->$property = $value;
             }
             /**/
     return $obj;
 }
 private function createPolicyManager()
 {
     return new PolicyManager(new UserAgentParser(new UAFamilyParser(Parser::create())));
 }
Example #29
0
 public function decode($encodedToken, $tokenType, $algs, $userAgent = null)
 {
     if (empty($tokenType) || $tokenType !== "access_token" && $tokenType !== "refresh_token") {
         throw new Exception("Invalid token type", 401);
     }
     if ($tokenType === "refresh_token" && empty($userAgent)) {
         throw new Exception("Invalid request", 401);
     }
     $token = JWT::decode($encodedToken, Security::salt(), $algs);
     $conditions = [$this->aliasField('user_id') => $token->id, $this->aliasField($tokenType) => $encodedToken];
     $userToken = $this->find('all')->select([$this->alias() . '.id', $this->alias() . '.access_token', $this->alias() . '.user_agent'])->where($conditions)->first();
     if (empty($userToken)) {
         throw new Exception("Invalid token", 401);
     }
     if ($tokenType !== "refresh_token") {
         return $token;
     }
     /*
      * se for refresh token
      * 1 - deletar o token para evitar novo uso
      * 2 - se nao tiver user_agent requisicao invalida
      * 3 - verificar se access token é valido
      * 4 - validar userAgent
      */
     $this->delete($userToken);
     if (empty($userToken['user_agent'])) {
         throw new Exception("Invalid token", 401);
     }
     $userAgentRegistry = $userToken['user_agent'];
     $accessToken = $userToken['access_token'];
     try {
         $accessToken = $this->decode($accessToken, 'access_token', $algs);
     } catch (ExpiredException $e) {
         $accessToken = null;
     }
     /* se acess token for valido, refresh token nao pode ser usado */
     if (!empty($accessToken)) {
         throw new Exception("Invalid request", 401);
     }
     if ($userAgent === $userAgentRegistry) {
         return $token;
     }
     $parser = Parser::create();
     $userAgent = $parser->parse($userAgent);
     $userAgentRegistry = $parser->parse($userAgentRegistry);
     if ($userAgent->device->family !== $userAgentRegistry->device->family || empty($userAgent->device->family) || empty($userAgentRegistry->device->family)) {
         throw new Exception("Invalid device family", 401);
     }
     if ($userAgent->os->family !== $userAgentRegistry->os->family || empty($userAgent->os->family) || empty($userAgentRegistry->os->family)) {
         throw new Exception("Invalid OS family", 401);
     }
     if ($userAgent->os->toVersion() < $userAgentRegistry->os->toVersion() || empty($userAgent->os->toVersion()) || empty($userAgentRegistry->os->toVersion())) {
         throw new Exception("Invalid OS version", 401);
     }
     if ($userAgent->ua->family !== $userAgentRegistry->ua->family || empty($userAgent->ua->family) || empty($userAgentRegistry->ua->family)) {
         throw new Exception("Invalid UA family", 401);
     }
     if ($userAgent->ua->toVersion() < $userAgentRegistry->ua->toVersion() || empty($userAgent->ua->toVersion()) || empty($userAgentRegistry->ua->toVersion())) {
         throw new Exception("Invalid UA version", 401);
     }
     return $token;
 }
 public static function parse($userAgentString)
 {
     $parser = UserAgentLib::create();
     $browser = $parser->parse($userAgentString);
     return array('os' => $browser->os->family, 'name' => $browser->ua->family, 'version' => $browser->ua->major . '.' . $browser->ua->minor);
 }