Здравствуйте! Есть Symfony 3.4.
class LoginController extends Controller
{
/**
* Matches /login exactly
*
* @Route("/login", name="login")
*
* @param Request $request
*
* @return Response
*/
public function loginAction(Request $request)
{
$email = $request->query->get('email');
$password = $request->query->get('password');
if (empty($email) || empty($password)) {
return new Response(
'Email or password can not be blank',
Response::HTTP_UNAUTHORIZED,
['Content-type' => 'application/json',]
);
}
/** @var EncoderFactory $factory */
$factory = $this->get('security.encoder_factory');
/** @var UserManager $user_manager */
$user_manager = $this->get('fos_user.user_manager');
/** @var User $user */
$user = $user_manager->findUserByEmail($email);
if (!$user) {
return new Response(
'Email doesnt exists',
Response::HTTP_UNAUTHORIZED,
['Content-type' => 'application/json',]
);
}
$encoder = $factory->getEncoder($user);
$salt = $user->getSalt();
if (!$encoder->isPasswordValid($user->getPassword(), $password, $salt)) {
return new Response(
'Email or Password not valid.',
Response::HTTP_UNAUTHORIZED,
['Content-type' => 'application/json',]
);
}
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
$this->get('session')->set('_security_main', serialize($token));
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
return new Response(
'Welcome '. $user->getUsername(),
Response::HTTP_OK,
['Content-type' => 'application/json']
);
}
}
С помощью POSTman отправляю POST запрс паролем и email. Всё работает, но подскажите, пожалуйста, как сделать валидацию приходящих email и пароля?