forked from ecamp/ecamp3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoogleAuthenticator.php
111 lines (90 loc) · 4.63 KB
/
GoogleAuthenticator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
namespace App\Security\OAuth;
use App\Entity\Profile;
use App\Entity\User;
use App\OAuth\JWTStateOAuth2Client;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
use League\OAuth2\Client\Provider\GoogleUser;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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;
class GoogleAuthenticator extends OAuth2Authenticator {
public function __construct(
private AuthenticationSuccessHandler $authenticationSuccessHandler,
private string $cookiePrefix,
private ClientRegistry $clientRegistry,
private EntityManagerInterface $entityManager,
private Security $security,
private JWTEncoderInterface $jwtDecoder,
) {}
public function supports(Request $request): ?bool {
// continue ONLY if the current ROUTE matches the check ROUTE
return 'connect_google_check' === $request->attributes->get('_route');
}
public function authenticate(Request $request): Passport {
$client = $this->clientRegistry->getClient('google');
$accessToken = $this->fetchAccessToken($client);
return new SelfValidatingPassport(
new UserBadge($accessToken->getToken(), function () use ($accessToken, $client) {
/** @var GoogleUser $googleUser */
$googleUser = $client->fetchUserFromToken($accessToken);
$email = $googleUser->getEmail();
$profileRepository = $this->entityManager->getRepository(Profile::class);
// has the user logged in with Google before?
$existingProfile = $profileRepository->findOneBy(['googleId' => $googleUser->getId()]);
if ($existingProfile) {
$user = $existingProfile->user;
if (User::STATE_REGISTERED === $user->state
|| User::STATE_NONREGISTERED === $user->state
) {
$user->state = User::STATE_ACTIVATED;
$this->entityManager->persist($user);
$this->entityManager->flush();
}
return $user;
}
// do we have a matching user by email?
$profile = $profileRepository->findOneBy(['email' => $email]);
$user = $profile?->user;
if (is_null($profile)) {
$profile = new Profile();
$profile->email = $email;
$profile->firstname = $googleUser->getFirstName();
$profile->surname = $googleUser->getLastName();
$user = new User();
$user->profile = $profile;
$user->state = User::STATE_ACTIVATED;
}
// persist user object
$profile->googleId = $googleUser->getId();
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
})
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response {
$user = $this->security->getUser();
$authSuccess = $this->authenticationSuccessHandler->handleAuthenticationSuccess($user);
$redirectUrl = $this->jwtDecoder->decode($request->cookies->get(JWTStateOAuth2Client::getCookieName($this->cookiePrefix)))['callback'] ?? '/';
$response = new RedirectResponse($redirectUrl);
/** @var string[] $cookies */
$cookies = $authSuccess->headers->all('set-cookie');
$response->headers->set('set-cookie', $cookies);
return $response;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response {
$message = strtr($exception->getMessageKey(), $exception->getMessageData());
return new Response($message, Response::HTTP_FORBIDDEN);
}
}