· 6 years ago · Oct 06, 2019, 08:06 PM
1<?php declare(strict_types=1);
2
3namespace Enis\Pim\Security;
4
5use Enis\Pim\Repository\UserRepository;
6use FOS\OAuthServerBundle\Model\TokenManager;
7use Symfony\Component\HttpFoundation\JsonResponse;
8use Symfony\Component\HttpFoundation\Request;
9use Symfony\Component\HttpFoundation\Response;
10use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
11use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
12use Symfony\Component\Security\Core\Exception\AuthenticationException;
13use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
14use Symfony\Component\Security\Core\User\UserInterface;
15use Symfony\Component\Security\Core\User\UserProviderInterface;
16use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
17
18class PublicApiJWTAuthenticator extends AbstractGuardAuthenticator
19{
20 private $userRepository;
21 private $passwordEncoder;
22
23 public function __construct(
24 UserRepository $userRepository,
25 UserPasswordEncoderInterface $passwordEncoder
26 )
27 {
28 $this->userRepository = $userRepository;
29 $this->passwordEncoder = $passwordEncoder;
30 }
31
32 /**
33 * Returns a response that directs the user to authenticate.
34 *
35 * This is called when an anonymous request accesses a resource that
36 * requires authentication. The job of this method is to return some
37 * response that "helps" the user start into the authentication process.
38 *
39 * Examples:
40 *
41 * - For a form login, you might redirect to the login page
42 *
43 * return new RedirectResponse('/login');
44 *
45 * - For an API token authentication system, you return a 401 response
46 *
47 * return new Response('Auth header required', 401);
48 *
49 * @param Request $request The request that resulted in an AuthenticationException
50 * @param AuthenticationException $authException The exception that started the authentication process
51 *
52 * @return Response
53 */
54 public function start(Request $request, AuthenticationException $authException = null): JsonResponse
55 {
56 return new JsonResponse('Auth header required', 401);
57 }
58
59 /**
60 * Does the authenticator support the given Request?
61 *
62 * If this returns false, the authenticator will be skipped.
63 *
64 * @param Request $request
65 *
66 * @return bool
67 */
68 public function supports(Request $request): bool
69 {
70 return 'public_api_login_check' === $request->attributes->get('_route') && $request->isMethod('POST');
71 }
72
73 /**
74 * Get the authentication credentials from the request and return them
75 * as any type (e.g. an associate array).
76 *
77 * Whatever value you return here will be passed to getUser() and checkCredentials()
78 *
79 * For example, for a form login, you might:
80 *
81 * return [
82 * 'username' => $request->request->get('_username'),
83 * 'password' => $request->request->get('_password'),
84 * ];
85 *
86 * Or for an API token that's on a header, you might use:
87 *
88 * return ['api_key' => $request->headers->get('X-API-TOKEN')];
89 *
90 * @param Request $request
91 *
92 * @return mixed Any non-null value
93 *
94 * @throws \UnexpectedValueException If null is returned
95 */
96 public function getCredentials(Request $request): array
97 {
98 return [
99 'username' => $request->request->get('username'),
100 'password' => $request->request->get('password'),
101 ];
102
103 }
104
105 /**
106 * Return a UserInterface object based on the credentials.
107 *
108 * The *credentials* are the return value from getCredentials()
109 *
110 * You may throw an AuthenticationException if you wish. If you return
111 * null, then a UsernameNotFoundException is thrown for you.
112 *
113 * @param mixed $credentials
114 * @param UserProviderInterface $userProvider
115 *
116 * @throws AuthenticationException
117 *
118 * @return UserInterface|null
119 */
120 public function getUser($credentials, UserProviderInterface $userProvider): ?UserInterface
121 {
122 if (empty($credentials['username']) || empty($credentials['password'])) {
123 throw new CustomUserMessageAuthenticationException('Invalid credentials');
124 }
125
126 $user = $this->userRepository->findByUsername($credentials['username']);
127
128 if ($user === null) {
129 throw new CustomUserMessageAuthenticationException('Invalid credentials');
130 }
131
132 return $user;
133
134 }
135
136 /**
137 * Returns true if the credentials are valid.
138 *
139 * If any value other than true is returned, authentication will
140 * fail. You may also throw an AuthenticationException if you wish
141 * to cause authentication to fail.
142 *
143 * The *credentials* are the return value from getCredentials()
144 *
145 * @param mixed $credentials
146 * @param UserInterface $user
147 *
148 * @return bool
149 *
150 * @throws AuthenticationException
151 */
152 public function checkCredentials($credentials, UserInterface $user): bool
153 {
154 if (!$this->passwordEncoder->isPasswordValid($user, $credentials['password'])) {
155 throw new CustomUserMessageAuthenticationException('Invalid credentials');
156 }
157
158 return true;
159 }
160
161 /**
162 * Called when authentication executed, but failed (e.g. wrong username password).
163 *
164 * This should return the Response sent back to the user, like a
165 * RedirectResponse to the login page or a 403 response.
166 *
167 * If you return null, the request will continue, but the user will
168 * not be authenticated. This is probably not what you want to do.
169 *
170 * @param Request $request
171 * @param AuthenticationException $exception
172 *
173 * @return Response|null
174 */
175 public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?JsonResponse
176 {
177 return new JsonResponse([
178 'message' => $exception->getMessageKey(),
179 ], Response::HTTP_UNAUTHORIZED);
180 }
181
182 /**
183 * Called when authentication executed and was successful!
184 *
185 * This should return the Response sent back to the user, like a
186 * RedirectResponse to the last page they visited.
187 *
188 * If you return null, the current request will continue, and the user
189 * will be authenticated. This makes sense, for example, with an API.
190 *
191 * @param Request $request
192 * @param TokenInterface $token
193 * @param string $providerKey The provider (i.e. firewall) key
194 *
195 * @return Response|null
196 */
197 public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): ?Response
198 {
199 return null;
200 }
201
202 /**
203 * Does this method support remember me cookies?
204 *
205 * Remember me cookie will be set if *all* of the following are met:
206 * A) This method returns true
207 * B) The remember_me key under your firewall is configured
208 * C) The "remember me" functionality is activated. This is usually
209 * done by having a _remember_me checkbox in your form, but
210 * can be configured by the "always_remember_me" and "remember_me_parameter"
211 * parameters under the "remember_me" firewall key
212 * D) The onAuthenticationSuccess method returns a Response object
213 *
214 * @return bool
215 */
216 public function supportsRememberMe(): bool
217 {
218 return false;
219 }
220}