//allow custom header
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
$errorCode = 200;
$response = null;
if ($config->getValue('enable_resource_owner_service', false)) {
    if ($_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
        //sort of ignore the damn ajax options pre-flight requests
        foreach (getallheaders() as $name => $value) {
            if ($name === 'Authorization' && strpos($value, 'Bearer ') === 0) {
                $tokenType = 'Bearer';
                $accessTokenId = base64_decode(trim(substr($value, 7)));
            }
        }
        if (isset($accessTokenId)) {
            if ('Bearer' === $tokenType) {
                $tokenStore = new sspmod_oauth2server_OAuth2_TokenStore($config);
                $userStore = new sspmod_oauth2server_OAuth2_UserStore($config);
                $accessToken = $tokenStore->getAccessToken($accessTokenId);
                if ($accessToken != null) {
                    $user = $userStore->getUser($accessToken['userId']);
                }
                if (isset($user) && $user != null) {
                    $configuredAttributeScopes = $config->getValue('resource_owner_service_attribute_scopes', array());
                    $attributeScopes = array_intersect($accessToken['scopes'], array_keys($configuredAttributeScopes));
                    if (count($attributeScopes) > 0) {
                        $response = array();
                        $attributeNames = array();
                        // null means grab all attributes
                        foreach ($attributeScopes as $scope) {
                            if (is_array($attributeNames) && is_array($configuredAttributeScopes[$scope])) {
                                $attributeNames = array_merge($attributeNames, $configuredAttributeScopes[$scope]);
*    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');
$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']) {
*    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();
if (isset($_POST['back'])) {
    SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php'));
}
$idAttribute = $config->getValue('user_id_attribute', 'eduPersonScopedAffiliation');
$tokenStore = new sspmod_oauth2server_OAuth2_TokenStore($config);
$userStore = new sspmod_oauth2server_OAuth2_UserStore($config);
$attributes = $as->getAttributes();
$user = $userStore->getUser($attributes[$idAttribute][0]);
if (!is_null($user) && isset($_REQUEST['tokenId'])) {
    if (array_search($_REQUEST['tokenId'], $user['authorizationCodes']) !== false) {
        $token = $tokenStore->getAuthorizationCode($_REQUEST['tokenId']);
        if (is_array($token) && isset($_POST['revoke'])) {
            $tokenStore->removeAuthorizationCode($_REQUEST['tokenId']);
            SimpleSAML\Utils\HTTP::redirectTrustedURL(SimpleSAML_Module::getModuleURL('oauth2server/manage/status.php'));
        }
    } else {
        if (array_search($_REQUEST['tokenId'], $user['refreshTokens']) !== false) {
            $token = $tokenStore->getRefreshToken($_REQUEST['tokenId']);
            if (is_array($token) && isset($_POST['revoke'])) {
                $tokenStore->removeRefreshToken($_REQUEST['tokenId']);
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);
                if (!is_null($client)) {
                    if (!isset($client['password']) && is_null($password) || isset($client['password']) && $password === $client['password'] || isset($client['alternative_password']) && $password === $client['alternative_password']) {
                        $tokenStore = new sspmod_oauth2server_OAuth2_TokenStore($config);
                        $userStore = new sspmod_oauth2server_OAuth2_UserStore($config);
                        $authorizationTokenId = null;
                        $authorizationToken = null;
                        $user = null;
                        if ($_POST['grant_type'] === 'authorization_code' && array_key_exists('code', $_POST)) {
                            $authorizationTokenId = $_POST['code'];
                            $authorizationToken = $tokenStore->getAuthorizationCode($authorizationTokenId);
                            $tokenStore->removeAuthorizationCode($_POST['code']);
                        } elseif ($_POST['grant_type'] === 'refresh_token' && array_key_exists('refresh_token', $_POST)) {
                            $authorizationTokenId = $_POST['refresh_token'];
                            $authorizationToken = $tokenStore->getRefreshToken($authorizationTokenId);
                        }
                        if (!is_null($authorizationToken)) {
                            $user = $userStore->getUser($authorizationToken['userId']);
                        }
*    Output:
*    json array containing a status attribute as well as access token properties, if
*   the token was valid
*
*/
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';
 $attributes = $as->getAttributes();
 if ($state['response_type'] === 'code') {
     $authorizationCodeFactory = new sspmod_oauth2server_OAuth2_TokenFactory($authorizationCodeTTL, $accessTokenTTL, $tokenTTL);
     $token = $authorizationCodeFactory->createAuthorizationCode($state['clientId'], $state['redirectUri'], array(), $attributes[$idAttribute][0]);
 } else {
     $authorizationCodeFactory = new sspmod_oauth2server_OAuth2_TokenFactory($authorizationCodeTTL, $tokenTTL, $tokenTTL);
     $token = $authorizationCodeFactory->createBearerAccessToken($state['clientId'], array(), $attributes[$idAttribute][0]);
 }
 if (isset($_REQUEST['grantedScopes'])) {
     $scopesTemp = $_REQUEST['grantedScopes'];
 } else {
     $scopesTemp = array();
 }
 \sspmod_oauth2server_Utility_Uri::augmentRequestedScopesWithRequiredScopes($client, $scopesTemp);
 $token['scopes'] = \sspmod_oauth2server_Utility_Uri::findValidScopes($client, $scopesTemp);
 $tokenStore = new sspmod_oauth2server_OAuth2_TokenStore($config);
 if ($state['response_type'] === 'code') {
     $tokenStore->addAuthorizationCode($token);
 } else {
     $tokenStore->addAccessToken($token);
 }
 $userStore = new sspmod_oauth2server_OAuth2_UserStore($config);
 $user = $userStore->getUser($token['userId']);
 if (is_array($user)) {
     $user['attributes'] = $as->getAttributes();
     $liveTokens = array($token['id']);
     if ($state['response_type'] === 'code') {
         foreach ($user['authorizationCodes'] as $tokenId) {
             if (!is_null($tokenStore->getAuthorizationCode($tokenId))) {
                 array_push($liveTokens, $tokenId);
             }
 /**
  * @group unit
  * @group oauth2
  */
 public function testAccessTokenIsolation()
 {
     $store = new \sspmod_oauth2server_OAuth2_TokenStore($this->getDefaultConfiguration());
     $token1 = array('id' => 'dummy', 'expire' => time() + 1000);
     $store->addAccessToken($token1);
     $this->assertNull($store->getAuthorizationCode($token1['id']));
     $this->assertNull($store->getRefreshToken($token1['id']));
 }