Пример #1
0
    protected function generate(Credentials $credentials, $scope)
    {
        $sql = 'SELECT id,
				       name,
				       password
			      FROM fusio_user
			     WHERE name = :name
			       AND status = :status';
        $user = $this->connection->fetchAssoc($sql, array('name' => $credentials->getClientId(), 'status' => User::STATUS_ADMINISTRATOR));
        if (!empty($user)) {
            if (password_verify($credentials->getClientSecret(), $user['password'])) {
                $scopes = ['backend'];
                // generate access token
                $expires = new \DateTime();
                $expires->add(new \DateInterval('PT1H'));
                $now = new \DateTime();
                $accessToken = hash('sha256', uniqid());
                $this->connection->insert('fusio_app_token', ['appId' => App::BACKEND, 'userId' => $user['id'], 'status' => AppToken::STATUS_ACTIVE, 'token' => $accessToken, 'scope' => implode(',', $scopes), 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1', 'expire' => $expires->format($this->connection->getDatabasePlatform()->getDateTimeFormatString()), 'date' => $now->format($this->connection->getDatabasePlatform()->getDateTimeFormatString())]);
                $token = new AccessToken();
                $token->setAccessToken($accessToken);
                $token->setTokenType('bearer');
                $token->setExpiresIn($expires->getTimestamp());
                $token->setScope(implode(',', $scopes));
                return $token;
            } else {
                throw new ServerErrorException('Invalid password');
            }
        } else {
            throw new ServerErrorException('Unknown user');
        }
    }
Пример #2
0
 private function getNews()
 {
     $con = $this->getRequestCondition();
     $con->add('pageId', '=', $this->page->getId());
     // archive
     $year = (int) $this->getUriFragments('year');
     $month = (int) $this->getUriFragments('month');
     // i think this software will not be used after the year 3000 if so
     // please travel back in time and slap me in the face ... nothing
     // happens ;D
     if ($year > 2010 && $year < 3000 && ($month > 0 && $month < 13)) {
         $date = new DateTime($year . '-' . ($month < 10 ? '0' : '') . $month . '-01', $this->registry['core.default_timezone']);
         $con->add('date', '>=', $date->format(DateTime::SQL));
         $con->add('date', '<', $date->add(new DateInterval('P1M'))->format(DateTime::SQL));
     }
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler()->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, SQL::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingNews', $paging, 0);
     return $result;
 }
Пример #3
0
    protected function getConsumer($consumerKey, $token)
    {
        $sql = <<<SQL
SELECT

\tapi.id             AS `apiId`,
\tapi.callback       AS `apiCallback`,
\tapi.consumerKey    AS `apiConsumerKey`,
\tapi.consumerSecret AS `apiConsumerSecret`

\tFROM {$this->registry['table.oauth']} api

\t\tWHERE api.consumerKey = ?

\t\tLIMIT 1
SQL;
        $result = $this->sql->getAll($sql, array($consumerKey));
        foreach ($result as $row) {
            $request = $this->fetchRequestValues($token);
            if (empty($request)) {
                throw new Exception('Invalid request');
            }
            // check whether the request token was requested
            // from the same ip
            if ($request['requestIp'] != $_SERVER['REMOTE_ADDR']) {
                throw new Exception('Token was requested from another ip');
            }
            // check whether the request is assigned
            // to this api
            if ($row['apiId'] != $request['requestApiId']) {
                throw new Exception('Request is not assigned to this API');
            }
            // check expire
            $now = new DateTime('NOW', $this->registry['core.default_timezone']);
            $date = new DateTime($request['requestDate'], $this->registry['core.default_timezone']);
            $date->add(new DateInterval($request['requestExpire']));
            if ($now > $date) {
                $con = new Condition(array('token', '=', $token));
                $this->sql->delete($this->registry['table.oauth_request'], $con);
                throw new Exception('The token is expired');
            }
            $this->requestId = $request['requestId'];
            $this->nonce = $request['requestNonce'];
            $this->verifier = $request['requestVerifier'];
            return new Provider\Consumer($row['apiConsumerKey'], $row['apiConsumerSecret'], $request['requestToken'], $request['requestTokenSecret']);
        }
    }
Пример #4
0
 public function onLoad()
 {
     parent::onLoad();
     // get oauth token
     $oauthToken = $this->get->oauth_token('string', array(new Filter\Length(40, 40), new Filter\Xdigit()));
     if ($this->validate->hasError()) {
         throw new Exception($this->validate->getLastError());
     }
     // check whether user is logged in if not redirect them to
     // the login form
     if ($this->user->isAnonymous()) {
         $self = $this->page->getUrl() . '/auth?oauth_token=' . $oauthToken;
         header('Location: ' . $this->page->getUrl() . '?redirect=' . urlencode($self));
         exit;
     }
     if ($this->user->hasRight('login_view')) {
         // add path
         $this->path->add('Auth', $this->page->getUrl() . '/auth');
         try {
             if (!empty($oauthToken)) {
                 // check token
                 $row = $this->getHandler('AmunService\\Oauth\\Request')->getOneByToken($oauthToken, array('apiId', 'status', 'callback', 'token', 'expire', 'date'));
                 if (!empty($row)) {
                     $this->template->assign('token', $row['token']);
                     // assign api id
                     $this->apiId = $row['apiId'];
                     // check token status so if a token has access status we
                     // can not access this page
                     if (!in_array($row['status'], array(Oauth\Record::TEMPORARY, Oauth\Record::APPROVED))) {
                         throw new Exception('The token was already approved');
                     }
                     // check expire
                     $now = new DateTime('NOW', $this->registry['core.default_timezone']);
                     $date = new DateTime($row['date'], $this->registry['core.default_timezone']);
                     $date->add(new DateInterval($row['expire']));
                     if ($now > $date) {
                         $con = new Condition(array('token', '=', $oauthToken));
                         $this->hm->getTable('AmunService\\Oauth\\Request')->delete($con);
                         throw new Exception('The token is expired');
                     }
                     // load user rights
                     $con = new Condition(array('groupId', '=', $this->user->getGroupId()));
                     $this->userRights = $this->getHandler('AmunService\\User\\Group\\Right')->getAll(array('rightId', 'groupId', 'rightDescription'), 0, 1024, 'rightDescription', Sql::SORT_ASC, $con);
                     $this->template->assign('userRights', $this->userRights);
                     // assign token and callback for later use
                     $token = $row['token'];
                     $callback = $row['callback'];
                     // parse callback
                     if ($callback != 'oob') {
                         $host = parse_url($row['callback'], PHP_URL_HOST);
                         if (!empty($host)) {
                             $this->template->assign('consumerHost', $host);
                         } else {
                             throw new Exception('No valid callback was defined in the request');
                         }
                     }
                 } else {
                     throw new Exception('The consumer provide an invalid token');
                 }
                 // request consumer informations
                 $row = $this->getHandler('AmunService\\Oauth')->getOneById($this->apiId, array('url', 'title', 'description'));
                 if (!empty($row)) {
                     $this->template->assign('consumerTitle', $row['title']);
                     $this->template->assign('consumerDescription', $row['description']);
                 } else {
                     throw new Exception('Request is not assigned to an user');
                 }
                 // check whether access is already allowed
                 if ($this->getHandler('AmunService\\Oauth\\Access')->isAllowed($this->apiId, $this->user->getId())) {
                     $this->allowAccess($token, $callback, false);
                 }
             } else {
                 throw new Exception('The consumer has not provide an valid token');
             }
         } catch (\Exception $e) {
             $this->template->assign('error', $e->getMessage());
         }
         // template
         $this->htmlCss->add('login');
     } else {
         throw new Exception('Access not allowed');
     }
 }
Пример #5
0
 protected function getResponse(Provider\Consumer $consumer, Provider\Request $request)
 {
     // we check how often this ip has requested an token ... because
     // of security reasons each consumer can have max 5 request tokens
     $maxCount = 5;
     $ip = $_SERVER['REMOTE_ADDR'];
     $con = new Condition(array('ip', '=', $ip), array('status', '=', Oauth\Record::TEMPORARY));
     $count = $this->sql->count($this->registry['table.oauth_request'], $con);
     if ($count >= $maxCount) {
         $conDelete = new Condition();
         $result = $this->sql->select($this->registry['table.oauth_request'], array('id', 'expire', 'date'), $con, Sql::SELECT_ALL);
         foreach ($result as $row) {
             $now = new DateTime('NOW', $this->registry['core.default_timezone']);
             $date = new DateTime($row['date'], $this->registry['core.default_timezone']);
             $date->add(new DateInterval($row['expire']));
             if ($now > $date) {
                 $conDelete->add('id', '=', $row['id'], 'OR');
             }
         }
         if ($conDelete->hasCondition()) {
             $this->sql->delete($this->registry['table.oauth_request'], $conDelete);
         }
         throw new Exception('You can only have max. ' . $maxCount . ' active request tokens');
     }
     // get nonce
     $nonce = $request->getNonce();
     // assign callback
     $callback = $request->getCallback();
     // generate tokens
     $token = Security::generateToken();
     $tokenSecret = Security::generateToken();
     // we save the timestamp in the request but because it comes from
     // the user we doesnt use them to check the expire date
     $timestamp = $request->getTimestamp();
     // you have 30 minutes to authorize the request token and to exchange
     // them for an access token
     $expire = 'PT30M';
     $date = new DateTime('NOW', $this->registry['core.default_timezone']);
     $this->sql->insert($this->registry['table.oauth_request'], array('apiId' => $this->apiId, 'status' => Oauth\Record::TEMPORARY, 'ip' => $ip, 'nonce' => $nonce, 'callback' => $callback, 'token' => $token, 'tokenSecret' => $tokenSecret, 'timestamp' => $timestamp, 'expire' => $expire, 'date' => $date->format(DateTime::SQL)));
     $response = new Provider\Response();
     $response->setToken($token);
     $response->setTokenSecret($tokenSecret);
     return $response;
 }