From 5589ebb99376234538d8b131e1065d8047829122 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Wed, 28 Oct 2020 14:05:03 -0700 Subject: [PATCH] dev/core#2141 - APIv4 - Add `OAuthClient.userPassword` authentication --- .../Api4/Action/OAuthClient/UserPassword.php | 61 +++++++++++++++++++ ext/oauth-client/Civi/Api4/OAuthClient.php | 11 ++++ 2 files changed, 72 insertions(+) create mode 100644 ext/oauth-client/Civi/Api4/Action/OAuthClient/UserPassword.php diff --git a/ext/oauth-client/Civi/Api4/Action/OAuthClient/UserPassword.php b/ext/oauth-client/Civi/Api4/Action/OAuthClient/UserPassword.php new file mode 100644 index 0000000000..4f0bfdd253 --- /dev/null +++ b/ext/oauth-client/Civi/Api4/Action/OAuthClient/UserPassword.php @@ -0,0 +1,61 @@ + [['id', '=', 123], + * 'username' => 'johndoe', + * 'password' => 'abcd1234', + * 'storage' => 'OAuthSysToken', + * ]); + * ``` + * + * If successful, the result will be a (redacted) token. + * + * @method $this setUsername(string $username) + * @method string getUsername() + * @method $this setPassword(string $password) + * @method string getPassword() + * + * @link https://tools.ietf.org/html/rfc6749#section-4.3 + */ +class UserPassword extends AbstractGrantAction { + + /** + * @var string + */ + protected $username; + + /** + * @var string + */ + protected $password; + + public function _run(Result $result) { + $this->validate(); + + $tokenRecord = \Civi::service('oauth2.token')->init([ + 'client' => $this->getClientDef(), + 'scope' => $this->getScopes(), + 'storage' => $this->getStorage(), + 'grant_type' => 'password', + 'cred' => [ + 'username' => $this->getUsername(), + 'password' => $this->getPassword(), + ], + ]); + + $result[] = \CRM_OAuth_BAO_OAuthSysToken::redact($tokenRecord); + } + +} diff --git a/ext/oauth-client/Civi/Api4/OAuthClient.php b/ext/oauth-client/Civi/Api4/OAuthClient.php index f3858bba68..bcfc51a5a8 100644 --- a/ext/oauth-client/Civi/Api4/OAuthClient.php +++ b/ext/oauth-client/Civi/Api4/OAuthClient.php @@ -34,6 +34,17 @@ class OAuthClient extends Generic\DAOEntity { return $action->setCheckPermissions($checkPermissions); } + /** + * Request access with a username and password. + * + * @param bool $checkPermissions + * @return \Civi\Api4\Action\OAuthClient\UserPassword + */ + public static function userPassword($checkPermissions = TRUE) { + $action = new \Civi\Api4\Action\OAuthClient\UserPassword(static::class, __FUNCTION__); + return $action->setCheckPermissions($checkPermissions); + } + public static function permissions() { return [ 'meta' => ['access CiviCRM'], -- 2.25.1