rvr-nextgen/src/Controller/OAuthAuthController.php

71 lines
2.2 KiB
PHP
Raw Normal View History

2023-04-11 17:45:08 +02:00
<?php namespace RVR\Controller;
use DateTime;
use RVR\PersistentData\Model\OAuthToken;
use RVR\PersistentData\Model\User;
use SokoWeb\Interfaces\Authorization\ISecured;
use SokoWeb\Interfaces\Request\IRequest;
use SokoWeb\Interfaces\Response\IRedirect;
use SokoWeb\Response\Redirect;
use SokoWeb\PersistentData\PersistentDataManager;
use SokoWeb\Response\HtmlContent;
class OAuthAuthController implements ISecured
{
private IRequest $request;
private PersistentDataManager $pdm;
public function __construct(IRequest $request)
{
$this->request = $request;
$this->pdm = new PersistentDataManager();
}
public function authorize(): bool
{
return $this->request->user() !== null;
}
public function auth()
{
$redirectUri = $this->request->query('redirect_uri');
$scope = $this->request->query('scope') ? $this->request->query('scope'): '';
$state = $this->request->query('state');
$nonce = $this->request->query('nonce') ? $this->request->query('nonce'): '';
if (!$redirectUri || !$state) {
return new HtmlContent('oauth/oauth_error', ['error' => 'An invalid request was made. Please start authentication again.']);
}
$this->request->session()->delete('oauth_payload');
/**
* @var ?User $user
*/
$user = $this->request->user();
$code = bin2hex(random_bytes(16));
$accessToken = bin2hex(random_bytes(16));
$token = new OAuthToken();
$token->setNonce($nonce);
$token->setScope($scope);
$token->setUser($user);
$token->setCode($code);
$token->setAccessToken($accessToken);
$token->setCreatedDate(new DateTime());
$token->setExpiresDate(new DateTime('+5 minutes'));
$this->pdm->saveToDb($token);
$redirectUri = $redirectUri;
$additionalUriParams = [
'state' => $state,
'code' => $code
];
$and = (strpos($redirectUri, '?') !== false) ? '&' : '?';
$finalRedirectUri = $redirectUri . $and . http_build_query($additionalUriParams);
return new Redirect($finalRedirectUri, IRedirect::TEMPORARY);
}
}