<?php
$server = \FileRun\OAuth2::getServer();

try {
	$authParams = $server->getGrantType('authorization_code')->checkAuthorizeParams();
} catch (\Exception $e) {
	if ($e->httpStatusCode) {
		http_response_code($e->httpStatusCode);
	}
	jsonOutput(array(
		'error' => $e->errorType,
		'message' => $e->getMessage()
	));
}

$clientInternalId = $authParams['client']->getId();
$clientManager = new FileRun\OAuth2\ClientManager;
$clientInfo = $clientManager->getInfo($clientInternalId);

$auth = new FileRunAuth;
$auth->initPHPSession();
$authenticated = false;
$rs = $auth->hasValidCookie();
if ($rs) {
	$username = $rs;
	$authenticated = $auth->validateAccount($username);
}
if (!$authenticated) {
	if ($auth->hasValidPHPSession()) {
		$authenticated = $auth->validateAccount();
	}
}

$consentURL = Guzzle\Http\Url::factory($config['url']['root'].'/oauth2/authorize/');
$query = array(
	'client_id' => $clientInfo['cid'],
	'redirect_uri' =>  $authParams['redirect_uri'],
	'response_type' => $authParams['response_type'],
	'scope' => $str->fromHTML($_REQUEST['scope']),
	'state' => $str->fromHTML($_REQUEST['state'])
);
if ($_REQUEST['FileRunOauthDebug']) {
	$query['FileRunOauthDebug'] = 1;
}
$consentURL->setQuery($query);


if (!$authenticated) {
	$consentURL->setQuery($consentURLQueryString);
	if ($_REQUEST['noCookies']) {
		header('Location: '.$config['url']['root'].'/?redirectAfterLogin='.$str->forURL(base64_encode($consentURL)));
	} else {
		setCookie('FileRun[LoginRedirect]', base64_encode($consentURL), time()+180, '/', false, isSSL(), true);
		header('Location: '.$config['url']['root']);
	}
	exit();
} else {
	if ($_SESSION['confirm'] && $str->fromHTML($_GET['confirm']) == $_SESSION['confirm']) {
		unset($_SESSION['confirm']);
		$redirectUri = $server->getGrantType('authorization_code')->newAuthorizeRequest('user', $auth->currentUserInfo['id'], $authParams);
		if (!$_REQUEST['FileRunOauthDebug']) {
			header('Location: ' . $redirectUri);
			exit();
		} else {
			?>
			You got the code. The app should request the access token.
			<br><br>
			Auth code grant:
			<form method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $config['url']['root'] ?>/oauth2/token/">
				Client id: <input type="text" name="client_id" value="<?php echo $server->getRequest()->query->get('client_id') ?>" />
				<br>
				Client secret: <input type="text" name="client_secret" value="xvuI9CqgaDvbgibtdszhoYqstJAFm0Wt88PaQCP7" />
				<br>
				Grant type: <input type="text" name="grant_type" value="authorization_code" />
				<br>
				Code: <input type="text" name="code" value="<?php echo $str->safeHTML($redirectUri) ?>" size="100" />
				<br>
				State: <input type="text" name="state" value="" />
				<br>
				Redirect URI: <input type="text" name="redirect_uri" value="<?php echo $server->getRequest()->query->get('redirect_uri') ?>" />
				<br>
				<input type="submit" name="submit" value="send" />
			</form>


			Password grant:
			<form method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $config['url']['root'] ?>/oauth2/token/">
				Client id: <input type="text" name="client_id" value="<?php echo $server->getRequest()->query->get('client_id') ?>"/>
				<br>
				Client secret: <input type="text" name="client_secret" value="xvuI9CqgaDvbgibtdszhoYqstJAFm0Wt88PaQCP7"/>
				<br>
				Grant type: <input type="text" name="grant_type" value="password"/>
				<br>
				Scope: <input type="text" name="scope" value="list weblink profile email"/>
				<br>
				Username: <input type="text" name="username" value="admin"/>
				<br>
				Password: <input type="text" name="password" value="admin"/>
				<br>
				<input type="submit" name="submit" value="send"/>
			</form>

			Refresh token grant:
			<form method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $config['url']['root'] ?>/oauth2/token/">
				Client id: <input type="text" name="client_id" value="<?php echo $server->getRequest()->query->get('client_id') ?>"/>
				<br>
				Client secret: <input type="text" name="client_secret" value="xvuI9CqgaDvbgibtdszhoYqstJAFm0Wt88PaQCP7"/>
				<br>
				Grant type: <input type="text" name="grant_type" value="refresh_token"/>
				<br>
				Refresh token: <input type="text" name="refresh_token" value=""/>
				<br>
				<input type="submit" name="submit" value="send"/>
			</form>

		<?php
		}
	} else {
		$app['logoutURL'] = '../../?module=fileman&page=logout&redirectAfterLogin='.$str->forURL(base64_encode($consentURL));

		$confirm = md5(rand());
		$_SESSION['confirm'] = $confirm;
		$consentURL->getQuery()->set('confirm', $confirm);
		$app['confirmURL'] = $consentURL;

		$scopesInfo = array();
		foreach ($authParams['scopes'] as $scope) {
			$scopesInfo[] = $scope->getScope();
		}

		$app['scopes'] = $scopesInfo;
		$app['userInfo'] = $auth->currentUserInfo;
		$app['clientInfo'] = $clientInfo;

		$app['cancelURL'] = $config['url']['root'];
		FileRun::displaySmartyPage(false, 'consent');
	}
}