Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions module/VuFind/config/module.config.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@
'VuFind\Controller\LibGuidesAZController' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\LibraryCardsController' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\MyResearchController' => 'VuFind\Controller\MyResearchControllerFactory',
'VuFind\Controller\OAuth2Controller' => 'VuFind\Controller\OAuth2ControllerFactory',
'VuFind\Controller\OverdriveController' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\Pazpar2Controller' => 'VuFind\Controller\AbstractBaseFactory',
'VuFind\Controller\PrimoController' => 'VuFind\Controller\AbstractBaseFactory',
Expand Down Expand Up @@ -227,8 +226,6 @@
'librarycards' => 'VuFind\Controller\LibraryCardsController',
'MyResearch' => 'VuFind\Controller\MyResearchController',
'myresearch' => 'VuFind\Controller\MyResearchController',
'OAuth2' => 'VuFind\Controller\OAuth2Controller',
'oauth2' => 'VuFind\Controller\OAuth2Controller',
'Overdrive' => 'VuFind\Controller\OverdriveController',
'overdrive' => 'VuFind\Controller\OverdriveController',
'Pazpar2' => 'VuFind\Controller\Pazpar2Controller',
Expand Down
23 changes: 23 additions & 0 deletions module/VuFind/src/VuFind/Action/AbstractAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,10 @@ public function __invoke(
return $accessDeniedResponse;
}

if ($preprocessResponse = $this->preprocessRequest($request, $response)) {
return $preprocessResponse;
}

return $this->action($request, $response);
} catch (Throwable $exception) {
return $this->handleException($exception);
Expand Down Expand Up @@ -263,6 +267,25 @@ protected function validateActionConfig(
return null;
}

/**
* 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 {
return null;
}

/**
* Perform the action.
*
Expand Down
143 changes: 143 additions & 0 deletions module/VuFind/src/VuFind/Action/OAuth2/AbstractOAuth2Action.php
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

convertOAuthServerExceptionToResponse assumes that $e will 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?

Copy link
Copy Markdown
Contributor Author

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.

): 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 module/VuFind/src/VuFind/Action/OAuth2/AuthorizeAction.php
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(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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')
);
}
}
Loading