*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
*    response_type - 'code' corresponding to the authorization code grant flow and
*                    'token' corresponding to the implicit grant flow is supported.
*    client_id     - a configured id string agreed upon by any given client and authorization server
*    redirect_uri  - an optional configured uri to redirect the user agent to after authorization is granted or denied
*    scope         - optional configured scope strings agreed upon by any given client and authorization server
*    state         - optional string which clients can use to maintain state during authentication and authorization flows.
*/
session_cache_limiter('nocache');
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
$clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
if (isset($_REQUEST['client_id'])) {
    $client = $clientStore->getClient($_REQUEST['client_id']);
}
if (isset($client)) {
    $as = new SimpleSAML_Auth_Simple($config->getValue('authsource'));
    $params = sspmod_oauth2server_Utility_Uri::calculateScopingParameters($client);
    $as->requireAuth($params);
    if (array_key_exists('redirect_uri', $client) && is_array($client['redirect_uri']) && count($client['redirect_uri']) > 0) {
        $returnUri = isset($_REQUEST['redirect_uri']) ? $_REQUEST['redirect_uri'] : $client['redirect_uri'][0];
        $legalRedirectUri = sspmod_oauth2server_Utility_Uri::validateRedirectUri($returnUri, $client);
        if ($legalRedirectUri) {
            $requestedScopes = sspmod_oauth2server_Utility_Uri::augmentRequestedScopesWithRequiredScopes($client, isset($_REQUEST['scope']) ? explode(' ', $_REQUEST['scope']) : array());
            $invalidScopes = sspmod_oauth2server_Utility_Uri::findInvalidScopes($client, $requestedScopes);
            if (count($invalidScopes) == 0) {
                if (isset($_REQUEST['response_type']) && ($_REQUEST['response_type'] === 'code' || $_REQUEST['response_type'] === 'token')) {
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
*/
session_cache_limiter('nocache');
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
$as = new SimpleSAML_Auth_Simple($config->getValue('authsource'));
$as->requireAuth();
$idAttribute = $config->getValue('user_id_attribute', 'eduPersonScopedAffiliation');
$tokenStore = new sspmod_oauth2server_OAuth2_TokenStore($config);
$clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
$userStore = new sspmod_oauth2server_OAuth2_UserStore($config);
$attributes = $as->getAttributes();
$user = $userStore->getUser($attributes[$idAttribute][0]);
$globalConfig = SimpleSAML_Configuration::getInstance();
$authorizationCodes = array();
$refreshTokens = array();
$accessTokens = array();
$clients = array();
if (!is_null($user)) {
    $liveAuthorizationCodes = array();
    foreach ($user['authorizationCodes'] as $id) {
        $token = $tokenStore->getAuthorizationCode($id);
        if (!is_null($token)) {
            if (isset($_REQUEST['tokenId']) && $id === $_REQUEST['tokenId']) {
                $tokenStore->removeAuthorizationCode($id);
            $token = $tokenStore->getRefreshToken($_REQUEST['tokenId']);
            if (is_array($token) && isset($_POST['revoke'])) {
                $tokenStore->removeRefreshToken($_REQUEST['tokenId']);
                SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php'));
            }
        } else {
            if (array_search($_REQUEST['tokenId'], $user['accessTokens']) !== false) {
                $token = $tokenStore->getAccessToken($_REQUEST['tokenId']);
                if (is_array($token) && isset($_POST['revoke'])) {
                    $tokenStore->removeAccessToken($_REQUEST['tokenId']);
                    SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php'));
                }
            }
        }
    }
}
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'oauth2server:manage/token.php');
foreach ($config->getValue('scopes', array()) as $scope => $translations) {
    $t->includeInlineTranslation('{oauth2server:oauth2server:' . $scope . '}', $translations);
}
if (isset($token)) {
    $clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
    $client = $clientStore->getClient($token['clientId']);
    if (!is_null($client)) {
        $t->data['token'] = $token;
        $t->includeInlineTranslation('{oauth2server:oauth2server:client_description_text}', $client['description']);
    }
}
$t->data['form'] = SimpleSAML_Module::getModuleURL('oauth2server/manage/token.php');
$t->show();
*    refresh_token - refresh token previously issued by this token end point.
*
*    client_id     - a configured id string agreed upon by any given client and authorization server
*    redirect_uri  - same redirect_uri as used for the authorization code grant request
*
*    Clients may or may not have to provide Basic authentication header information based on their configuration.
*/
session_cache_limiter('nocache');
header('Content-Type: application/json; charset=utf-8');
//headers to support javascript ajax clients
header('Access-Control-Allow-Origin: *');
//allow cross domain
header('Access-Control-Allow-Headers: Authorization');
//allow custom header
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
$clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
$response = null;
$errorCode = 200;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (array_key_exists('grant_type', $_POST)) {
        if ($_POST['grant_type'] === 'authorization_code' || $_POST['grant_type'] === 'refresh_token') {
            $clientId = null;
            $password = null;
            if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
                $clientId = $_SERVER['PHP_AUTH_USER'];
                $password = $_SERVER['PHP_AUTH_PW'];
            } elseif (array_key_exists('client_id', $_POST)) {
                $clientId = $_POST['client_id'];
            }
            if (!is_null($clientId)) {
                $client = $clientStore->getClient($clientId);
*
*/
session_cache_limiter('nocache');
header('Content-Type: application/json; charset=utf-8');
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['access_token']) && isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $resourceServerId = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];
    $resourceServers = $config->getValue('resources', array());
    if (array_key_exists($resourceServerId, $resourceServers)) {
        $resourceServer = $resourceServers[$resourceServerId];
        if ($password === $resourceServer['password'] || array_key_exists('alternative_password', $resourceServer) && $password === $resourceServer['alternative_password']) {
            $tokenStore = new sspmod_oauth2server_OAuth2_TokenStore($config);
            $accessToken = $tokenStore->getAccessToken($_POST['access_token']);
            if (is_array($accessToken)) {
                $clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
                $userStore = new sspmod_oauth2server_OAuth2_UserStore($config);
                if (is_array($clientStore->getClient($accessToken['clientId'])) && is_array($userStore->getUser($accessToken['userId']))) {
                    echo json_encode(array('status' => 'valid_token', 'expires_in' => $accessToken['expire'] - time(), 'scopes' => array_values($accessToken['scopes']), 'userId' => $accessToken['userId']));
                    return;
                }
            }
            echo json_encode(array('status' => 'unknown_token'));
            return;
        }
    }
    $errorCode = 401;
    $status = 'invalid_resource';
} else {
    if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
        $errorCode = 401;
 /**
  * @group unit
  * @group oauth2
  */
 public function testRemoveClient()
 {
     $store = new \sspmod_oauth2server_OAuth2_ClientStore($this->getDefaultConfiguration());
     $client1 = array('id' => 'dummy', 'expire' => time() + 1000, 'scope' => array('scope1' => false));
     $store->addClient($client1);
     $client2 = $store->getClient($client1['id']);
     $this->assertNotNull($client2);
     $this->assertEquals($client1['id'], $client2['id']);
     $store->removeClient($client2['id']);
     $client3 = $store->getClient($client2['id']);
     $this->assertNull($client3);
 }
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
*/
session_cache_limiter('nocache');
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
$state = SimpleSAML_Auth_State::loadState($_REQUEST['stateId'], 'oauth2server:authorization/consent');
$globalConfig = SimpleSAML_Configuration::getInstance();
$clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
$client = $clientStore->getClient($state['clientId']);
$as = new SimpleSAML_Auth_Simple($config->getValue('authsource'));
$params = sspmod_oauth2server_Utility_Uri::calculateScopingParameters($client);
$as->requireAuth($params);
$authorizationCodeTTL = $config->getValue('authorization_code_time_to_live');
$accessTokenTTL = $config->getValue('access_token_time_to_live');
$tokenTTLs = $config->getValue('refresh_token_time_to_live');
if (empty($tokenTTLs)) {
    array_push($tokenTTLs, 3600);
}
if (array_key_exists('grant', $_REQUEST)) {
    if (array_key_exists('ttl', $_REQUEST) && array_key_exists($_REQUEST['ttl'], $tokenTTLs)) {
        $tokenTTL = $_REQUEST['ttl'];
    } else {
        $ttlNames = array_keys($tokenTTLs);