-
Notifications
You must be signed in to change notification settings - Fork 401
Refactor OAuth2Controller to actions. #5605
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EreMaijala
wants to merge
7
commits into
vufind-org:dev
Choose a base branch
from
EreMaijala:dev-refactor-oauth2controller
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
dd582d8
Refactor OAuth2Controller to actions.
EreMaijala d650826
Remove unnecessary config.
EreMaijala 6e4e965
Update module/VuFind/src/VuFind/ActionHelper/ResponseHelper.php
EreMaijala d1ae453
Fix OPTIONS request and exception handling.
EreMaijala 0d18b20
Get HTTP_HOST from request.
EreMaijala 8f7364b
Fix whitespace.
EreMaijala e32ca98
Update module/VuFind/src/VuFind/Action/OAuth2/AuthorizeAction.php
EreMaijala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
143 changes: 143 additions & 0 deletions
143
module/VuFind/src/VuFind/Action/OAuth2/AbstractOAuth2Action.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| <?php | ||
|
|
||
| /** | ||
| * Abstract base class for OAuth2 actions. | ||
| * | ||
| * PHP version 8 | ||
| * | ||
| * Copyright (C) The National Library of Finland 2022-2026. | ||
| * | ||
| * This program is free software; you can redistribute it and/or modify | ||
| * it under the terms of the GNU General Public License version 2, | ||
| * as published by the Free Software Foundation. | ||
| * | ||
| * This program 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 General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU General Public License | ||
| * along with this program; if not, see | ||
| * <https://www.gnu.org/licenses/>. | ||
| * | ||
| * @category VuFind | ||
| * @package Action | ||
| * @author Ere Maijala <ere.maijala@helsinki.fi> | ||
| * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License | ||
| * @link https://vufind.org Main Site | ||
| */ | ||
|
|
||
| namespace VuFind\Action\OAuth2; | ||
|
|
||
| use League\OAuth2\Server\Exception\OAuthServerException; | ||
| use Psr\Http\Message\ResponseInterface; | ||
| use Psr\Http\Message\ServerRequestInterface; | ||
| use VuFind\Action\AbstractTemplateRenderingAction; | ||
| use VuFind\ActionHelper\ResponseHelper; | ||
| use VuFind\OAuth2\OAuth2ServerService; | ||
| use VuFind\ServiceManager\Factory\Autowire; | ||
|
|
||
| /** | ||
| * Abstract base class for OAuth2 actions. | ||
| * | ||
| * @category VuFind | ||
| * @package Action | ||
| * @author Ere Maijala <ere.maijala@helsinki.fi> | ||
| * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License | ||
| * @link https://vufind.org Main Site | ||
| */ | ||
| abstract class AbstractOAuth2Action extends AbstractTemplateRenderingAction | ||
| { | ||
| /** | ||
| * Constructor. | ||
| * | ||
| * @param OAuth2ServerService $oauth2Service OAuth2 server service | ||
| */ | ||
| #[Autowire] | ||
| public function __construct( | ||
| protected OAuth2ServerService $oauth2Service, | ||
| ) { | ||
| parent::__construct(); | ||
| } | ||
|
|
||
| /** | ||
| * Preprocess a request before the actual action is executed. | ||
| * | ||
| * This method is executed just before the actual action (i.e. after permission checks etc.). | ||
| * It is meant for preprocessing of requests in a shared base class of multiple actions. | ||
| * It may return a suitable response or throw an exception if there are issues. | ||
| * | ||
| * @param ServerRequestInterface $request Request | ||
| * @param ResponseInterface $response Response | ||
| * | ||
| * @return ?ResponseInterface | ||
| */ | ||
| protected function preprocessRequest( | ||
| ServerRequestInterface $request, | ||
| ResponseInterface $response | ||
| ): ?ResponseInterface { | ||
| if ($request->getMethod() === 'OPTIONS') { | ||
| // Disable session writes | ||
| $this->disableSessionWrites(); | ||
| return $this->getHelper(ResponseHelper::class)->addCorsHeaders($response->withStatus(204)); | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * Create a server error response from a returnable OAuth2 exception. | ||
| * | ||
| * @param ResponseInterface $response Response | ||
| * @param string $function Function description | ||
| * @param OAuthServerException $e Exception | ||
| * | ||
| * @return ResponseInterface | ||
| */ | ||
| protected function handleOAuth2ServerException( | ||
| ResponseInterface $response, | ||
| string $function, | ||
| OAuthServerException $e | ||
| ): ResponseInterface { | ||
| $this->logError("$function failed: " . (string)$e); | ||
|
|
||
| return $this->convertOAuthServerExceptionToResponse($response, $e); | ||
| } | ||
|
|
||
| /** | ||
| * Create a server error response from a non-OAuth2 exception. | ||
| * | ||
| * @param ResponseInterface $response Response | ||
| * @param string $function Function description | ||
| * @param \Exception $e Exception | ||
| * | ||
| * @return ResponseInterface | ||
| */ | ||
| protected function handleOAuth2GenericException( | ||
| ResponseInterface $response, | ||
| string $function, | ||
| \Exception $e | ||
| ): ResponseInterface { | ||
| $this->logError("$function exception: " . (string)$e); | ||
|
|
||
| return $this->convertOAuthServerExceptionToResponse( | ||
| $response, | ||
| OAuthServerException::serverError('Server side issue') | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Convert an instance of OAuthServerException to a response. | ||
| * | ||
| * @param ResponseInterface $response Response | ||
| * @param OAuthServerException $exception Exception | ||
| * | ||
| * @return ResponseInterface | ||
| */ | ||
| protected function convertOAuthServerExceptionToResponse( | ||
| ResponseInterface $response, | ||
| OAuthServerException $exception | ||
| ): ResponseInterface { | ||
| $response = $exception->generateHttpResponse($response); | ||
| return $this->getHelper(ResponseHelper::class)->addCorsHeaders($response); | ||
| } | ||
| } | ||
168 changes: 168 additions & 0 deletions
168
module/VuFind/src/VuFind/Action/OAuth2/AuthorizeAction.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| <?php | ||
|
|
||
| /** | ||
| * OAuth2 authorization action. | ||
| * | ||
| * PHP version 8 | ||
| * | ||
| * Copyright (C) The National Library of Finland 2022-2026. | ||
| * | ||
| * This program is free software; you can redistribute it and/or modify | ||
| * it under the terms of the GNU General Public License version 2, | ||
| * as published by the Free Software Foundation. | ||
| * | ||
| * This program 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 General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU General Public License | ||
| * along with this program; if not, see | ||
| * <https://www.gnu.org/licenses/>. | ||
| * | ||
| * @category VuFind | ||
| * @package Action | ||
| * @author Ere Maijala <ere.maijala@helsinki.fi> | ||
| * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License | ||
| * @link https://vufind.org Main Site | ||
| */ | ||
|
|
||
| namespace VuFind\Action\OAuth2; | ||
|
|
||
| use Exception; | ||
| use League\OAuth2\Server\Exception\OAuthServerException; | ||
| use Psr\Http\Message\ResponseInterface; | ||
| use Psr\Http\Message\ServerRequestInterface; | ||
| use VuFind\ActionHelper\FormHelper; | ||
| use VuFind\ActionHelper\LoginHelper; | ||
| use VuFind\Auth\Manager as AuthManager; | ||
| use VuFind\Db\Service\AccessTokenServiceInterface; | ||
| use VuFind\Db\Service\PluginManager as DbServicePluginManager; | ||
| use VuFind\Exception\BadRequest as BadRequestException; | ||
| use VuFind\ILS\Connection; | ||
| use VuFind\OAuth2\Entity\ScopeEntity; | ||
| use VuFind\OAuth2\OAuth2ServerService; | ||
| use VuFind\ServiceManager\Factory\Autowire; | ||
| use VuFind\Validator\CsrfInterface; | ||
|
|
||
| use function in_array; | ||
|
|
||
| /** | ||
| * OAuth2 authorization action. | ||
| * | ||
| * @category VuFind | ||
| * @package Action | ||
| * @author Ere Maijala <ere.maijala@helsinki.fi> | ||
| * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License | ||
| * @link https://vufind.org Main Site | ||
| */ | ||
| class AuthorizeAction extends AbstractOAuth2Action | ||
| { | ||
| /** | ||
| * Constructor. | ||
| * | ||
| * @param OAuth2ServerService $oauth2Service OAuth2 server service | ||
| * @param AuthManager $authManager Authentication manager | ||
| * @param CsrfInterface $csrf CSRF validator | ||
| * @param AccessTokenServiceInterface $accessTokenService Access token database service | ||
| * @param Connection $ilsConnection ILS connection | ||
| */ | ||
| public function __construct( | ||
| OAuth2ServerService $oauth2Service, | ||
| protected AuthManager $authManager, | ||
| protected CsrfInterface $csrf, | ||
| #[Autowire(container: DbServicePluginManager::class)] | ||
| protected AccessTokenServiceInterface $accessTokenService, | ||
| protected Connection $ilsConnection | ||
| ) { | ||
| parent::__construct($oauth2Service); | ||
| } | ||
|
|
||
| /** | ||
| * Handle an authorization request. | ||
| * | ||
| * @param ServerRequestInterface $request Server request | ||
| * @param ResponseInterface $response Response | ||
| * | ||
| * @return ResponseInterface | ||
| */ | ||
| public function action( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be nice to move more of the logic in this method to OAuth2ServerService, but it's not easy because it's a multi-step operation with different outcomes depending e.g. on the user login status. |
||
| ServerRequestInterface $request, | ||
| ResponseInterface $response, | ||
| ): ResponseInterface { | ||
| // Validate the authorization request: | ||
| $clientId = $this->getQueryParam('client_id', ''); | ||
| if ( | ||
| '' === $clientId | ||
| || !($clientConfig = $this->oauth2Service->getClientConfig($clientId)) | ||
| ) { | ||
| throw new BadRequestException("Invalid OAuth2 client $clientId"); | ||
| } | ||
|
|
||
| if (!($user = $this->authManager->getUserObject())) { | ||
| return $this->getHelper(LoginHelper::class) | ||
| ->forceLogin($request, $response, 'external_auth_access_login_message'); | ||
| } | ||
|
|
||
| $authServer = $this->oauth2Service->getAuthorizationServer($clientId); | ||
| try { | ||
| $authRequest = $authServer->validateAuthorizationRequest($request); | ||
| } catch (OAuthServerException $e) { | ||
| return $this->handleOAuth2ServerException($response, 'Authorization request', $e); | ||
| } catch (\Exception $e) { | ||
| return $this->handleOAuth2GenericException($response, 'Authorization request', $e); | ||
| } | ||
|
|
||
| // Hide any scopes not allowed by a client-specific filter (see also ScopeRepository for the actual filtering): | ||
| if ($allowedScopes = $clientConfig['allowedScopes'] ?? null) { | ||
| $scopes = $authRequest->getScopes(); | ||
| array_map( | ||
| function ($scope) use ($allowedScopes): void { | ||
| if (!in_array($scope->getIdentifier(), $allowedScopes)) { | ||
| if (!($scope instanceof ScopeEntity)) { | ||
| throw new Exception('Scope must be an instance of ScopeEntity'); | ||
| } | ||
| $scope->setHidden(true); | ||
| } | ||
| }, | ||
| $scopes | ||
| ); | ||
| $authRequest->setScopes($scopes); | ||
| } | ||
|
|
||
| $formHelper = $this->getHelper(FormHelper::class); | ||
| if ($formHelper->formWasSubmitted($request, ['allow', 'deny'])) { | ||
| // Check CSRF and session: | ||
| if (!$this->csrf->isValid($this->getPostParam('csrf'))) { | ||
| throw new \VuFind\Exception\BadRequest('error_inconsistent_parameters'); | ||
| } | ||
|
|
||
| // Store OpenID nonce (or null if not present to clear any existing one) in the access | ||
| // token table so that it can be retrieved for token or user info action: | ||
| $this->accessTokenService->storeNonce($user->getId(), $this->getQueryParam('nonce')); | ||
|
|
||
| $authRequest->setUser($this->oauth2Service->getOAuth2UserEntity($user)); | ||
| $authRequest->setAuthorizationApproved($formHelper->formWasSubmitted($request, 'allow')); | ||
|
|
||
| try { | ||
| return $authServer->completeAuthorizationRequest($authRequest, $response); | ||
| } catch (OAuthServerException $e) { | ||
| return $this->handleOAuth2ServerException($response, 'Authorization request', $e); | ||
| } catch (\Exception $e) { | ||
| return $this->handleOAuth2GenericException($response, 'Authorization request', $e); | ||
| } | ||
| } | ||
|
|
||
| $userIdentifierField = $this->oauth2Service->getUserIdentifierField(); | ||
| $patron = $this->getHelper(LoginHelper::class)->catalogLogin($request, $response, false); | ||
| if ($patron instanceof ResponseInterface) { | ||
| return $patron; | ||
| } | ||
| $showCatalogLoginForm = !$patron; | ||
| return $this->renderTemplate( | ||
| $request, | ||
| $response, | ||
| compact('authRequest', 'user', 'patron', 'showCatalogLoginForm', 'userIdentifierField') | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
convertOAuthServerExceptionToResponse assumes that
$ewill have a generateHttpResponse method, which I assume is not part of the base exception class. Do we need a more specific type here, or some kind of type checking later?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The exception handling methods were kind of confusing already in the controller. I renamed the methods and fixed the parameter typing.