[PLUGIN][OAuth2] Start adding OAuth2 support with client registration

This hardcodes the user, and has some other issues, so it is not yet
complete.

We follow mastodon's spec for automatic client registration, available
at both `/api/v1/apps` and a more reasonable `/oauth/client`. This
accepts a JSON POST with the client info and returns JSON with a
`client_id` and a `client_secret`, to be used with `/oauth/authorize`
and `/oauth/token`. It also, seemingly, requires returning an `id`
with unclear purpose.

The `/oauth/token` endpoint doesn't currently return a `me` field.
This commit is contained in:
Hugo Sales 2022-01-25 12:17:32 +00:00
parent 4736146b80
commit fa0d02a9ac
Firmato da: someonewithpc
ID Chiave GPG: 7D0C7EAFC9D835A0
20 ha cambiato i file con 1961 aggiunte e 0 eliminazioni

341
composer.lock generato
Vedi File

@ -221,6 +221,72 @@
],
"time": "2022-01-17T14:14:24+00:00"
},
{
"name": "defuse/php-encryption",
"version": "v2.3.1",
"source": {
"type": "git",
"url": "https://github.com/defuse/php-encryption.git",
"reference": "77880488b9954b7884c25555c2a0ea9e7053f9d2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/defuse/php-encryption/zipball/77880488b9954b7884c25555c2a0ea9e7053f9d2",
"reference": "77880488b9954b7884c25555c2a0ea9e7053f9d2",
"shasum": ""
},
"require": {
"ext-openssl": "*",
"paragonie/random_compat": ">= 2",
"php": ">=5.6.0"
},
"require-dev": {
"phpunit/phpunit": "^4|^5|^6|^7|^8|^9"
},
"bin": [
"bin/generate-defuse-key"
],
"type": "library",
"autoload": {
"psr-4": {
"Defuse\\Crypto\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Hornby",
"email": "taylor@defuse.ca",
"homepage": "https://defuse.ca/"
},
{
"name": "Scott Arciszewski",
"email": "info@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "Secure PHP Encryption Library",
"keywords": [
"aes",
"authenticated encryption",
"cipher",
"crypto",
"cryptography",
"encrypt",
"encryption",
"openssl",
"security",
"symmetric key cryptography"
],
"support": {
"issues": "https://github.com/defuse/php-encryption/issues",
"source": "https://github.com/defuse/php-encryption/tree/v2.3.1"
},
"time": "2021-04-09T23:57:26+00:00"
},
{
"name": "doctrine/annotations",
"version": "1.13.2",
@ -2599,6 +2665,281 @@
},
"time": "2021-04-11T16:10:46+00:00"
},
{
"name": "lcobucci/clock",
"version": "2.1.0",
"source": {
"type": "git",
"url": "https://github.com/lcobucci/clock.git",
"reference": "903513d28e85376a33385ebc601afd2ee69e5653"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/lcobucci/clock/zipball/903513d28e85376a33385ebc601afd2ee69e5653",
"reference": "903513d28e85376a33385ebc601afd2ee69e5653",
"shasum": ""
},
"require": {
"php": "^8.0"
},
"require-dev": {
"infection/infection": "^0.25",
"lcobucci/coding-standard": "^8.0",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan": "^0.12",
"phpstan/phpstan-deprecation-rules": "^0.12",
"phpstan/phpstan-phpunit": "^0.12",
"phpstan/phpstan-strict-rules": "^0.12",
"phpunit/phpunit": "^9.5"
},
"type": "library",
"autoload": {
"psr-4": {
"Lcobucci\\Clock\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Luís Cobucci",
"email": "lcobucci@gmail.com"
}
],
"description": "Yet another clock abstraction",
"support": {
"issues": "https://github.com/lcobucci/clock/issues",
"source": "https://github.com/lcobucci/clock/tree/2.1.0"
},
"funding": [
{
"url": "https://github.com/lcobucci",
"type": "github"
},
{
"url": "https://www.patreon.com/lcobucci",
"type": "patreon"
}
],
"time": "2021-10-31T21:32:07+00:00"
},
{
"name": "lcobucci/jwt",
"version": "4.1.5",
"source": {
"type": "git",
"url": "https://github.com/lcobucci/jwt.git",
"reference": "fe2d89f2eaa7087af4aa166c6f480ef04e000582"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/lcobucci/jwt/zipball/fe2d89f2eaa7087af4aa166c6f480ef04e000582",
"reference": "fe2d89f2eaa7087af4aa166c6f480ef04e000582",
"shasum": ""
},
"require": {
"ext-hash": "*",
"ext-json": "*",
"ext-mbstring": "*",
"ext-openssl": "*",
"ext-sodium": "*",
"lcobucci/clock": "^2.0",
"php": "^7.4 || ^8.0"
},
"require-dev": {
"infection/infection": "^0.21",
"lcobucci/coding-standard": "^6.0",
"mikey179/vfsstream": "^1.6.7",
"phpbench/phpbench": "^1.0",
"phpstan/extension-installer": "^1.0",
"phpstan/phpstan": "^0.12",
"phpstan/phpstan-deprecation-rules": "^0.12",
"phpstan/phpstan-phpunit": "^0.12",
"phpstan/phpstan-strict-rules": "^0.12",
"phpunit/php-invoker": "^3.1",
"phpunit/phpunit": "^9.5"
},
"type": "library",
"autoload": {
"psr-4": {
"Lcobucci\\JWT\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Luís Cobucci",
"email": "lcobucci@gmail.com",
"role": "Developer"
}
],
"description": "A simple library to work with JSON Web Token and JSON Web Signature",
"keywords": [
"JWS",
"jwt"
],
"support": {
"issues": "https://github.com/lcobucci/jwt/issues",
"source": "https://github.com/lcobucci/jwt/tree/4.1.5"
},
"funding": [
{
"url": "https://github.com/lcobucci",
"type": "github"
},
{
"url": "https://www.patreon.com/lcobucci",
"type": "patreon"
}
],
"time": "2021-09-28T19:34:56+00:00"
},
{
"name": "league/event",
"version": "2.2.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/event.git",
"reference": "d2cc124cf9a3fab2bb4ff963307f60361ce4d119"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/event/zipball/d2cc124cf9a3fab2bb4ff963307f60361ce4d119",
"reference": "d2cc124cf9a3fab2bb4ff963307f60361ce4d119",
"shasum": ""
},
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"henrikbjorn/phpspec-code-coverage": "~1.0.1",
"phpspec/phpspec": "^2.2"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
}
},
"autoload": {
"psr-4": {
"League\\Event\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frenky.net"
}
],
"description": "Event package",
"keywords": [
"emitter",
"event",
"listener"
],
"support": {
"issues": "https://github.com/thephpleague/event/issues",
"source": "https://github.com/thephpleague/event/tree/master"
},
"time": "2018-11-26T11:52:41+00:00"
},
{
"name": "league/oauth2-server",
"version": "8.3.3",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/oauth2-server.git",
"reference": "f5698a3893eda9a17bcd48636990281e7ca77b2a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/oauth2-server/zipball/f5698a3893eda9a17bcd48636990281e7ca77b2a",
"reference": "f5698a3893eda9a17bcd48636990281e7ca77b2a",
"shasum": ""
},
"require": {
"defuse/php-encryption": "^2.2.1",
"ext-json": "*",
"ext-openssl": "*",
"lcobucci/jwt": "^3.4.6 || ^4.0.4",
"league/event": "^2.2",
"php": "^7.2 || ^8.0",
"psr/http-message": "^1.0.1"
},
"replace": {
"league/oauth2server": "*",
"lncd/oauth2": "*"
},
"require-dev": {
"laminas/laminas-diactoros": "^2.4.1",
"phpstan/phpstan": "^0.12.57",
"phpstan/phpstan-phpunit": "^0.12.16",
"phpunit/phpunit": "^8.5.13",
"roave/security-advisories": "dev-master"
},
"type": "library",
"autoload": {
"psr-4": {
"League\\OAuth2\\Server\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Alex Bilbie",
"email": "hello@alexbilbie.com",
"homepage": "http://www.alexbilbie.com",
"role": "Developer"
},
{
"name": "Andy Millington",
"email": "andrew@noexceptions.io",
"homepage": "https://www.noexceptions.io",
"role": "Developer"
}
],
"description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.",
"homepage": "https://oauth2.thephpleague.com/",
"keywords": [
"Authentication",
"api",
"auth",
"authorisation",
"authorization",
"oauth",
"oauth 2",
"oauth 2.0",
"oauth2",
"protect",
"resource",
"secure",
"server"
],
"support": {
"issues": "https://github.com/thephpleague/oauth2-server/issues",
"source": "https://github.com/thephpleague/oauth2-server/tree/8.3.3"
},
"funding": [
{
"url": "https://github.com/sephster",
"type": "github"
}
],
"time": "2021-10-11T20:41:49+00:00"
},
{
"name": "league/uri-parser",
"version": "1.4.1",

Vedi File

@ -20,6 +20,9 @@ security:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
oauth:
pattern: ^/oauth
security: false
main:
entry_point: App\Security\Authenticator
guard:

Vedi File

@ -0,0 +1,100 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Controller;
use App\Core\Controller;
use App\Entity\LocalUser;
use App\Util\Exception\NotFoundException;
use League\OAuth2\Server\Entities\UserEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use Nyholm\Psr7\Factory\Psr17Factory;
use Plugin\OAuth2\OAuth2;
use Psr\Http\Message\ResponseFactoryInterface;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class Authorize extends Controller
{
public function __construct(
RequestStack $stack,
private ResponseFactoryInterface $response_factory,
) {
parent::__construct($stack);
}
public function __invoke(Request $request)
{
// @var \League\OAuth2\Server\AuthorizationServer $server
$server = OAuth2::$authorization_server;
$response = $this->response_factory->createResponse();
$httpFoundationFactory = new HttpFoundationFactory;
try {
// Validate the HTTP request and return an AuthorizationRequest object.
// The auth request object can be serialized into a user's session
$psr17Factory = new Psr17Factory();
$psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
$psrRequest = $psrHttpFactory->createRequest($request);
$authRequest = $server->validateAuthorizationRequest($psrRequest);
// TODO
// Once the user has logged in set the user on the AuthorizationRequest
$authRequest->setUser(
new class(LocalUser::getByNickname('foo')->getId()) implements UserEntityInterface {
public function __construct(private int $id)
{
}
public function getIdentifier()
{
return $this->id;
}
},
);
// Once the user has approved or denied the client update the status
// (true = approved, false = denied)
$authRequest->setAuthorizationApproved(true);
// Return the HTTP redirect response
return $httpFoundationFactory->createResponse($server->completeAuthorizationRequest($authRequest, $response));
} catch (OAuthServerException $exception) {
return $httpFoundationFactory->createResponse($exception->generateHttpResponse($response));
} catch (NotFoundException) {
return new JsonResponse(['error' => 'No such client', 'error_description' => 'This client is not registered']);
}
}
}

Vedi File

@ -0,0 +1,98 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Controller;
use App\Core\Controller;
use App\Core\DB\DB;
use function App\Core\I18n\_m;
use App\Core\Log;
use App\Util\Exception\ClientException;
use Plugin\OAuth2\Entity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Client Management Endpoint
*
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Client extends Controller
{
public function onPost(Request $request): JsonResponse
{
Log::debug('OAuth2 Apps: Received a POST request.');
Log::debug('OAuth2 Apps: Request content: ', [$body = $request->getContent()]);
$args = json_decode($body, true);
if (\is_null($args) || !\array_key_exists('redirect_uris', $args)) {
throw new ClientException(_m('Invalid request'), code: 400);
}
$identifier = hash('sha256', random_bytes(16)); // TODO maybe use password_hash and verify
$secret = hash('sha256', random_bytes(64));
// TODO more validation
$client = Entity\Client::create([
'id' => $identifier,
'secret' => $secret,
'active' => true,
'plain_pcke' => false,
'is_confidential' => true,
'redirect_uris' => $args['redirect_uris'],
'grants' => 'client_credentials',
'scopes' => $args['scopes'] ?? 'read',
'client_name' => $args['client_name'],
'website' => $args['website'] ?? null,
]);
DB::persist($client);
DB::flush();
Log::debug('OAuth2 Apps: Created App: ', [$client]);
$app_response = [
'id' => 42, // TODO ???
'name' => $client->getName(),
'website' => $client->getWebsite(),
'redirect_uri' => $client->getRedirectUri(),
'client_id' => $client->getIdentifier(),
'client_secret' => $client->getSecret(),
];
Log::debug('OAuth2 Apps: Create App response: ', [$app_response]);
// Success
return new JsonResponse($app_response, status: 200, headers: ['content_type' => 'application/json; charset=utf-8']);
}
}

Vedi File

@ -0,0 +1,72 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Controller;
use App\Core\Controller;
use League\OAuth2\Server\Exception\OAuthServerException;
use Nyholm\Psr7\Factory\Psr17Factory;
use Plugin\OAuth2\OAuth2;
use Psr\Http\Message\ResponseFactoryInterface;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class Token extends Controller
{
public function __construct(
RequestStack $stack,
private ResponseFactoryInterface $response_factory,
) {
parent::__construct($stack);
}
public function __invoke(Request $request)
{
// @var \League\OAuth2\Server\AuthorizationServer $server
$server = OAuth2::$authorization_server;
$psr17factory = new Psr17Factory();
$psr_http_factory = new PsrHttpFactory($psr17factory, $psr17factory, $psr17factory, $psr17factory);
$psr_request = $psr_http_factory->createRequest($request);
$http_foundation_factory = new HttpFoundationFactory;
$server_response = $this->response_factory->createResponse();
try {
return $http_foundation_factory->createResponse($server->respondToAccessTokenRequest($psr_request, $server_response));
} catch (OAuthServerException $e) {
return $http_foundation_factory->createResponse($e->generateHttpResponse($server_response));
}
}
}

Vedi File

@ -0,0 +1,145 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 Client
*
* @package GNUsocial
*
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Entity;
use DateTimeInterface;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
class AccessToken extends Token implements AccessTokenEntityInterface
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private string $id;
private DateTimeInterface $expiry;
private ?int $user_id = null;
private string $client_id;
private string $token_scopes;
private bool $revoked;
private DateTimeInterface $created;
public function setId(string $id): self
{
$this->id = mb_substr($id, 0, 64);
return $this;
}
public function getId(): string
{
return $this->id;
}
public function setExpiry(DateTimeInterface $expiry): self
{
$this->expiry = $expiry;
return $this;
}
public function getExpiry(): DateTimeInterface
{
return $this->expiry;
}
public function setUserId(?int $user_id): self
{
$this->user_id = $user_id;
return $this;
}
public function getUserId(): ?int
{
return $this->user_id;
}
public function setClientId(string $client_id): self
{
$this->client_id = mb_substr($client_id, 0, 64);
return $this;
}
public function getClientId(): string
{
return $this->client_id;
}
public function setTokenScopes(string $token_scopes): self
{
$this->token_scopes = $token_scopes;
return $this;
}
public function getTokenScopes(): string
{
return $this->token_scopes;
}
public function setRevoked(bool $revoked): self
{
$this->revoked = $revoked;
return $this;
}
public function getRevoked(): bool
{
return $this->revoked;
}
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface
{
return $this->created;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public CryptKey $private_key;
public function setPrivateKey(CryptKey $private_key)
{
$this->private_key = $private_key;
}
public function __toString()
{
return $this->getId();
}
public static function schemaDef(): array
{
return parent::tokenSchema('oauth2_access_token');
}
}

Vedi File

@ -0,0 +1,152 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 Client
*
* @package GNUsocial
*
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Entity;
use DateTimeInterface;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use Plugin\OAuth2\Repository;
class AuthCode extends Token implements AuthCodeEntityInterface
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private string $id;
private DateTimeInterface $expiry;
private ?int $user_id = null;
private string $client_id;
private string $token_scopes;
private bool $revoked;
private DateTimeInterface $created;
public function setId(string $id): self
{
$this->id = mb_substr($id, 0, 64);
return $this;
}
public function getId(): string
{
return $this->id;
}
public function setExpiry(DateTimeInterface $expiry): self
{
$this->expiry = $expiry;
return $this;
}
public function getExpiry(): DateTimeInterface
{
return $this->expiry;
}
public function setUserId(?int $user_id): self
{
$this->user_id = $user_id;
return $this;
}
public function getUserId(): ?int
{
return $this->user_id;
}
public function setClientId(string $client_id): self
{
$this->client_id = mb_substr($client_id, 0, 64);
return $this;
}
public function getClientId(): string
{
return $this->client_id;
}
public function setTokenScopes(string $token_scopes): self
{
$this->token_scopes = $token_scopes;
return $this;
}
public function getTokenScopes(): string
{
return $this->token_scopes;
}
public function setRevoked(bool $revoked): self
{
$this->revoked = $revoked;
return $this;
}
public function getRevoked(): bool
{
return $this->revoked;
}
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface
{
return $this->created;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
/**
* @return null|string
*/
public function getRedirectUri()
{
return (new Repository\Client)->getClientEntity($this->getClientId())->getRedirectUri();
}
/**
* @param string $uri
*/
public function setRedirectUri($uri)
{
/** @var Client $client */
$client = (new Repository\Client)->getClientEntity($this->getClientId());
$client->setRedirectUris($uri);
}
public static function schemaDef(): array
{
return parent::tokenSchema('oauth2_auth_code');
}
}

Vedi File

@ -0,0 +1,231 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 Client
*
* @package GNUsocial
*
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Entity;
use App\Core\Entity;
use DateTimeInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
class Client extends Entity implements ClientEntityInterface
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private string $id;
private string $secret;
private bool $active;
private bool $plain_pcke;
private bool $is_confidential;
private string $redirect_uris;
private string $grants;
private string $scopes;
private string $client_name;
private ?string $website = null;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setId(string $id): self
{
$this->id = mb_substr($id, 0, 64);
return $this;
}
public function getId(): string
{
return $this->id;
}
public function setSecret(string $secret): self
{
$this->secret = mb_substr($secret, 0, 64);
return $this;
}
public function getSecret(): string
{
return $this->secret;
}
public function setActive(bool $active): self
{
$this->active = $active;
return $this;
}
public function getActive(): bool
{
return $this->active;
}
public function setPlainPcke(bool $plain_pcke): self
{
$this->plain_pcke = $plain_pcke;
return $this;
}
public function getPlainPcke(): bool
{
return $this->plain_pcke;
}
public function setIsConfidential(bool $is_confidential): self
{
$this->is_confidential = $is_confidential;
return $this;
}
public function getIsConfidential(): bool
{
return $this->is_confidential;
}
public function setRedirectUris(string $redirect_uris): self
{
$this->redirect_uris = $redirect_uris;
return $this;
}
public function getRedirectUris(): string
{
return $this->redirect_uris;
}
public function setGrants(string $grants): self
{
$this->grants = $grants;
return $this;
}
public function getGrants(): string
{
return $this->grants;
}
public function setScopes(string $scopes): self
{
$this->scopes = $scopes;
return $this;
}
public function getScopes(): string
{
return $this->scopes;
}
public function setClientName(string $client_name): self
{
$this->client_name = mb_substr($client_name, 0, 191);
return $this;
}
public function getClientName(): string
{
return $this->client_name;
}
public function setWebsite(?string $website): self
{
$this->website = $website;
return $this;
}
public function getWebsite(): ?string
{
return $this->website;
}
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface
{
return $this->created;
}
public function setModified(DateTimeInterface $modified): self
{
$this->modified = $modified;
return $this;
}
public function getModified(): DateTimeInterface
{
return $this->modified;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public function getIdentifier()
{
return $this->getId();
}
public function getName(): string
{
return $this->getClientName();
}
public function getRedirectUri(): string
{
return mb_substr($this->getRedirectUris(), 0, mb_strpos($this->getRedirectUris(), ' ') ?: null);
}
public function isConfidential(): bool
{
return $this->getIsConfidential();
}
public static function schemaDef(): array
{
return [
'name' => 'oauth2_client',
'fields' => [
'id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'client identifier'],
'secret' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'client secret'],
'active' => ['type' => 'bool', 'not null' => true, 'description' => 'whether this client is active'],
'plain_pcke' => ['type' => 'bool', 'not null' => true, 'description' => 'whether to allow plaintext PKCE'],
'is_confidential' => ['type' => 'bool', 'not null' => true, 'description' => 'whether this client needs to provide the secret'],
'redirect_uris' => ['type' => 'text', 'not null' => true, 'description' => 'application redirect uris, space separated'],
'grants' => ['type' => 'text', 'not null' => true, 'description' => 'application grants, space separated'],
'scopes' => ['type' => 'text', 'not null' => true, 'description' => 'application scopes, space separated'],
'client_name' => ['type' => 'varchar', 'length' => 191, 'not null' => true, 'description' => 'name of the application'],
'website' => ['type' => 'text', 'not null' => false, 'description' => 'application homepage - used for source link'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
],
'primary key' => ['id'],
];
}
}

Vedi File

@ -0,0 +1,177 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 Client
*
* @package GNUsocial
*
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Entity;
use App\Core\Entity;
use DateTimeInterface;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
class RefreshToken extends Entity implements RefreshTokenEntityInterface
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private string $id;
private DateTimeInterface $expiry;
private ?string $access_token_id = null;
private bool $revoked;
private DateTimeInterface $created;
public function setId(string $id): self
{
$this->id = mb_substr($id, 0, 64);
return $this;
}
public function getId(): string
{
return $this->id;
}
public function setExpiry(DateTimeInterface $expiry): self
{
$this->expiry = $expiry;
return $this;
}
public function getExpiry(): DateTimeInterface
{
return $this->expiry;
}
public function setAccessTokenId(?string $access_token_id): self
{
$this->access_token_id = \is_null($access_token_id) ? null : mb_substr($access_token_id, 0, 64);
return $this;
}
public function getAccessTokenId(): ?string
{
return $this->access_token_id;
}
public function setRevoked(bool $revoked): self
{
$this->revoked = $revoked;
return $this;
}
public function getRevoked(): bool
{
return $this->revoked;
}
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface
{
return $this->created;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
/**
* Get the token's identifier.
*
* @return string
*/
public function getIdentifier()
{
return $this->getId();
}
/**
* Set the token's identifier.
*/
public function setIdentifier($identifier)
{
$this->setId($identifier);
}
/**
* Get the token's expiry date time.
*
* @return DateTimeImmutable
*/
public function getExpiryDateTime()
{
return $this->getExpiry();
}
/**
* Set the date time when the token expires.
*
* @param DateTimeImmutable $dateTime
*/
public function setExpiryDateTime(\DateTimeImmutable $dateTime)
{
$this->setExpiry($dateTime);
}
/**
* Set the access token that the refresh token was associated with.
*/
public function setAccessToken(AccessTokenEntityInterface $accessToken)
{
$this->setAccessTokenId($accessToken->getIdentifier());
}
/**
* Get the access token that the refresh token was originally associated with.
*
* @return AccessTokenEntityInterface
*/
public function getAccessToken()
{
return (new Repository\AccessToken)->getAccessTokenEntity($this->getAccessTokenId());
}
public static function schemaDef(): array
{
return [
'name' => 'oauth2_refresh_token',
'fields' => [
'id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'identifier for this token'],
'expiry' => ['type' => 'datetime', 'not null' => true, 'description' => 'when this token expires'],
'access_token_id' => ['type' => 'char', 'length' => 64, 'foreign key' => true, 'description' => 'Actor foreign key'],
'revoked' => ['type' => 'bool', 'not null' => true, 'foreign key' => true, 'description' => 'Whether this token is revoked'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
],
'primary key' => ['id'],
];
}
}

Vedi File

@ -0,0 +1,149 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 Client
*
* @package GNUsocial
*
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Entity;
use App\Core\Entity;
use Functional as F;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Entities\TokenInterface;
use Plugin\OAuth2\Repository;
abstract class Token extends Entity implements TokenInterface
{
public function getIdentifier()
{
return $this->getId();
}
public function setIdentifier($identifier)
{
$this->setId($identifier);
}
/**
* Get the token's expiry date time.
*
* @return DateTimeImmutable
*/
public function getExpiryDateTime()
{
return $this->getExpiry();
}
/**
* Set the date time when the token expires.
*
* @param DateTimeImmutable $dateTime
*/
public function setExpiryDateTime(\DateTimeImmutable $dateTime)
{
$this->setExpiry($dateTime);
}
/**
* Set the identifier of the user associated with the token.
*
* @param null|int|string $identifier The identifier of the user
*/
public function setUserIdentifier($identifier)
{
$this->setUserId($identifier);
}
/**
* Get the token user's identifier.
*
* @return null|int|string
*/
public function getUserIdentifier()
{
return $this->getUserId();
}
/**
* Get the client that the token was issued to.
*
* @return ClientEntityInterface
*/
public function getClient()
{
return (new Repository\Client)->getClientEntity($this->getClientId());
}
/**
* Set the client that the token was issued to.
*/
public function setClient(ClientEntityInterface $client)
{
$this->setClientId($client->getIdentifier());
}
/**
* Associate a scope with the token.
*/
public function addScope(ScopeEntityInterface $scope)
{
$scope = $this->hasTokenScopes() ? $this->getTokenScopes() . ' ' . $scope->getIdentifier() : $scope->getIdentifier();
$this->setTokenScopes($scope);
}
/**
* Return an array of scopes associated with the token.
*
* @return ScopeEntityInterface[]
*/
public function getScopes()
{
return F\map(
explode(' ', $this->getTokenScopes()),
fn (string $scope) => (new Repository\Scope)->getScopeEntityByIdentifier($scope),
);
}
public static function tokenSchema(string $table_name): array
{
return [
'name' => $table_name,
'fields' => [
'id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'identifier for this token'],
'expiry' => ['type' => 'datetime', 'not null' => true, 'description' => 'when this token expires'],
'user_id' => ['type' => 'int', 'foreign key' => true, 'description' => 'Actor foreign key'],
'client_id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'foreign key' => true, 'description' => 'OAuth client foreign key'],
'token_scopes' => ['type' => 'text', 'not null' => true, 'description' => 'Space separated scopes'],
'revoked' => ['type' => 'bool', 'not null' => true, 'foreign key' => true, 'description' => 'Whether this token is revoked'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
],
'primary key' => ['id'],
];
}
}

108
plugins/OAuth2/OAuth2.php Normal file
Vedi File

@ -0,0 +1,108 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2;
use App\Core\Event;
use App\Core\Modules\Plugin;
use App\Core\Router\RouteLoader;
use App\Core\Router\Router;
use App\Util\Common;
use DateInterval;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Grant\AuthCodeGrant;
use Plugin\OAuth2\Controller as C;
use XML_XRD_Element_Link;
/**
* Adds OAuth2 support to GNU social when enabled
*
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class OAuth2 extends Plugin
{
public const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token';
public const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token';
public const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize';
public function version(): string
{
return '3.0.0';
}
public static ?AuthorizationServer $authorization_server = null;
public function onInitializePlugin()
{
self::$authorization_server = new AuthorizationServer(
new Repository\Client,
new Repository\AccessToken,
new Repository\Scope,
privateKey: new CryptKey(keyPath: Common::config('oauth2', 'private_key'), passPhrase: Common::config('oauth2', 'private_key_password')),
encryptionKey: Common::config('oauth2', 'encryption_key'),
);
self::$authorization_server->enableGrantType(
new AuthCodeGrant(
new Repository\AuthCode,
new Repository\RefreshToken,
new DateInterval('PT10M'), // ???
),
new DateInterval('PT1H'),
);
}
/**
* This code executes when GNU social creates the page routing, and we hook
* on this event to add our Inbox and Outbox handler for ActivityPub.
*
* @param RouteLoader $r the router that was initialized
*/
public function onAddRoute(RouteLoader $r): bool
{
$r->connect('oauth2_mastodon_api_apps', '/api/v1/apps', C\Client::class, ['http-methods' => ['POST']]);
$r->connect('oauth2_client', '/oauth/client', C\Client::class, ['http-methods' => ['POST']]);
$r->connect('oauth2_authorize', '/oauth/authorize', C\Authorize::class);
$r->connect('oauth2_token', '/oauth/token', C\Token::class);
return Event::next;
}
public function onEndHostMetaLinks(array &$links): bool
{
$links[] = new XML_XRD_Element_link(self::OAUTH_REQUEST_TOKEN_REL, Router::url('oauth2_client', type: Router::ABSOLUTE_URL));
$links[] = new XML_XRD_Element_link(self::OAUTH_AUTHORIZE_REL, Router::url('oauth2_authorize', type: Router::ABSOLUTE_URL));
$links[] = new XML_XRD_Element_link(self::OAUTH_ACCESS_TOKEN_REL, Router::url('oauth2_token', type: Router::ABSOLUTE_URL));
return Event::next;
}
}

Vedi File

@ -0,0 +1,75 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Repository;
use App\Core\DB\DB;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use Plugin\OAuth2\Entity;
class AccessToken implements AccessTokenRepositoryInterface
{
public function getAccessTokenEntity(string $identifier): Entity\AccessToken
{
return DB::findOneBy(Entity\AccessToken::class, ['id' => $identifier]);
}
public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity)
{
DB::persist($accessTokenEntity);
}
public function revokeAccessToken($tokenId)
{
// Some logic here to revoke the access token
}
public function isAccessTokenRevoked($tokenId)
{
return false; // Access token hasn't been revoked
}
public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
{
$accessToken = new Entity\AccessToken();
$accessToken->setClient($clientEntity);
foreach ($scopes as $scope) {
$accessToken->addScope($scope);
}
$accessToken->setUserIdentifier($userIdentifier);
return $accessToken;
}
}

Vedi File

@ -0,0 +1,62 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Repository;
use App\Core\DB\DB;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
use Plugin\OAuth2\Entity;
class AuthCode implements AuthCodeRepositoryInterface
{
public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity)
{
DB::persist($authCodeEntity);
}
public function revokeAuthCode($codeId)
{
// Some logic to revoke the auth code in a database
}
public function isAuthCodeRevoked($codeId)
{
return false; // The auth code has not been revoked
}
public function getNewAuthCode()
{
return new Entity\AuthCode();
}
}

Vedi File

@ -0,0 +1,61 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Repository;
use App\Core\DB\DB;
use App\Util\Exception\NotFoundException;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use Plugin\OAuth2\Entity;
class Client implements ClientRepositoryInterface
{
public function getClientEntity($clientIdentifier)
{
return DB::findOneBy(Entity\Client::class, ['id' => $clientIdentifier]);
}
public function validateClient($clientIdentifier, $clientSecret, $grantType)
{
try {
/** @var Entity\Client $client */
$client = $this->getClientEntity($clientIdentifier);
if ($client->getIsConfidential() && $clientSecret !== $client->getSecret()) {
return false;
}
} catch (NotFoundException) {
return false;
}
return true;
}
}

Vedi File

@ -0,0 +1,62 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Repository;
use App\Core\DB\DB;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use Plugin\OAuth2\Entity;
class RefreshToken implements RefreshTokenRepositoryInterface
{
public function persistNewRefreshToken(RefreshtokenEntityInterface $refreshtokenEntity)
{
DB::persist($refreshtokenEntity);
}
public function revokeRefreshToken($tokenId)
{
// Some logic to revoke the auth token in a database
}
public function isRefreshtokenRevoked($tokenId)
{
return false; // The auth token has not been revoked
}
public function getNewRefreshToken()
{
return new Entity\RefreshToken();
}
}

Vedi File

@ -0,0 +1,92 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* OAuth2 implementation for GNU social
*
* @package OAuth2
* @category API
*
* @author Diogo Peralta Cordeiro <mail@diogo.site>
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\OAuth2\Repository;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
class Scope implements ScopeRepositoryInterface
{
/**
* @return ?ScopeEntityInterface
*/
public function getScopeEntityByIdentifier($scopeIdentifier)
{
$scopes = [
'basic' => [
'description' => 'Basic details about you',
],
'email' => [
'description' => 'Your email address',
],
'read' => [
'description' => 'Read',
],
'write' => [
'description' => 'Read',
],
'follow' => [
'description' => 'Read',
],
];
if (\array_key_exists($scopeIdentifier, $scopes) === false) {
return;
}
return new class($scopeIdentifier) implements ScopeEntityInterface {
public function __construct(private string $identifier)
{
}
public function getIdentifier()
{
return $this->identifier;
}
public function jsonSerialize(): mixed
{
return $this->getIdentifier();
}
};
}
public function finalizeScopes(
array $scopes,
$grantType,
ClientEntityInterface $clientEntity,
$userIdentifier = null,
) {
return $scopes;
}
}

Vedi File

@ -0,0 +1,6 @@
{
"require": {
"league/oauth2-server": "*",
"nyholm/psr7": "*"
}
}

Vedi File

@ -0,0 +1,6 @@
parameters:
oauth2:
private_key: '%kernel.project_dir%/file/oauth/private.key'
private_key_password: null
public_key: '%kernel.project_dir%/file/oauth/public.key'
encryption_key: 'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'

Vedi File

@ -278,3 +278,9 @@ parameters:
feeds:
entries_per_page: 32
oauth2:
private_key: '%kernel.project_dir%/file/oauth/private.key'
private_key_password: null
public_key: '%kernel.project_dir%/file/oauth/public.key'
encryption_key: 'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'

Vedi File

@ -65,6 +65,9 @@
"composer/xdebug-handler": {
"version": "1.4.6"
},
"defuse/php-encryption": {
"version": "v2.3.1"
},
"doctrine/annotations": {
"version": "1.0",
"recipe": {
@ -223,6 +226,18 @@
"landrok/activitypub": {
"version": "0.5.6"
},
"lcobucci/clock": {
"version": "2.1.0"
},
"lcobucci/jwt": {
"version": "4.1.5"
},
"league/event": {
"version": "2.2.0"
},
"league/oauth2-server": {
"version": "8.3.3"
},
"league/uri-parser": {
"version": "1.4.1"
},