This commit is contained in:
Beu 2023-02-16 11:00:25 +01:00
parent af11b6f690
commit d284712b8e
3 changed files with 203 additions and 0 deletions

40
README.md Normal file
View File

@ -0,0 +1,40 @@
# TrackMania (2020) OAuth2 authentication module
## How to install it
Add this in your composer.json file:
```json
"repositories": [
{
"url": "https://git.virtit.fr/beu/oauth2-trackmania.git",
"type": "git"
}
],
```
change the value of `minimum-stability` to dev in it.
then launch the command:
```bash
composer require beu/oauth2-trackmania
```
## How to configure it
Install the security bundle:
```bash
composer require symfony/security-bundle
```
Then create the User Entity
```bash
php bin/console make:user
```
Note that you have to answer **no** to the question `Does this app need to hash/check user passwords?`
Then, you could copy the files `TrackMania.php` in `src/Controller/OAuth2/` and `TrackManiaAuthenticator.php` in `src/Security/`

72
examples/TrackMania.php Normal file
View File

@ -0,0 +1,72 @@
<?php
namespace App\Controller\OAuth2;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\RequestStack;
class TrackMania extends AbstractController
{
/**
* Link to this controller to start the "connect" process
*/
#[Route(
'/connect/trackmania',
name: 'connect_trackmania_start'
)]
public function connectAction(ClientRegistry $clientRegistry)
{
// will redirect to Ubisoft Connect OAuth2
return $clientRegistry
->getClient('TrackMania') // key used in config/packages/knpu_oauth2_client.yaml
->redirect([],[]);
}
/**
* After going to Ubisoft Connect OAuth2, you're redirected back here
* because this is the "redirect_route" you configured
* in config/packages/knpu_oauth2_client.yaml
*/
#[Route(
'/connect/trackmania/check',
name: 'connect_trackmania_check'
)]
public function connectCheckAction(Request $request, ClientRegistry $clientRegistry)
{
// ** if you want to *authenticate* the user, then
// leave this method blank and create a Guard authenticator
}
#[Route(
'/login',
name: 'app_login',
methods: ['GET', 'HEAD']
)]
public function login(Request $request, RequestStack $requestStack): RedirectResponse
{
$referer = $request->headers->get('referer');
if ($referer !== null) {
$session = $requestStack->getSession();
$session->set("PostLoginRedirect", $referer);
}
return $this->redirectToRoute('connect_trackmania_start');
}
/**
* @Route("/logout", name="app_logout", methods={"GET"})
*/
#[Route(
'/logout',
name: 'app_logout',
methods: ['GET', 'HEAD']
)]
public function logout(): void
{
// controller can be blank: it will never be called!
throw new \Exception('Don\'t forget to activate logout in security.yaml');
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\HttpFoundation\RequestStack;
class TrackManiaAuthenticator extends OAuth2Authenticator
{
private $clientRegistry;
private $entityManager;
private $router;
private $requestStack;
public function __construct(ClientRegistry $clientRegistry, EntityManagerInterface $entityManager, RouterInterface $router, RequestStack $requestStack)
{
$this->clientRegistry = $clientRegistry;
$this->entityManager = $entityManager;
$this->router = $router;
$this->requestStack = $requestStack;
}
public function supports(Request $request): ?bool
{
// continue ONLY if the current ROUTE matches the check ROUTE
return $request->attributes->get('_route') === 'connect_trackmania_check';
}
public function authenticate(Request $request): Passport
{
$client = $this->clientRegistry->getClient('TrackMania');
$accessToken = $this->fetchAccessToken($client);
$selfvalidating = new SelfValidatingPassport(
new UserBadge($accessToken->getToken(), function() use ($accessToken, $client) {
/** @var Beu\TrackMania\OAuth2\Client\Provider\TrackManiaProviderOwner $user */
$user = $client->fetchUserFromToken($accessToken);
$existingUser = $this->entityManager->getRepository(User::class)->findOneBy(['AccountId' => $user->getId()]);
if ($existingUser) {
/** @var User $existingUser */
if ($existingUser->getDisplayName() !== $user->getDisplayName()) {
$existingUser->setDisplayName($user->getDisplayName());
$this->entityManager->flush();
}
return $existingUser;
}
$newuser = new User();
$newuser->setAccountId($user->getId());
$newuser->setDisplayName($user->getDisplayName());
$this->entityManager->persist($newuser);
$this->entityManager->flush();
return $newuser;
})
);
return $selfvalidating;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
$session = $this->requestStack->getSession();
if ($session->has("PostLoginRedirect")) {
$targetUrl = $session->get("PostLoginRedirect");
} else {
$targetUrl = $this->router->generate('homepage');
}
return new RedirectResponse($targetUrl);
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$message = strtr($exception->getMessageKey(), $exception->getMessageData());
return new Response($message, Response::HTTP_FORBIDDEN);
}
}