Answer the question
In order to leave comments, you need to log in
Data validation in Symfony 3?
Hello! There is 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']
);
}
}
Answer the question
In order to leave comments, you need to log in
It is better to create an object in which to write the necessary validation using Assert
https://symfony.com/doc/current/validation.html
And another recommendation that does not apply to the question. Your controller is too fat :) It's worth thinking about taking it all out somewhere. It is also recommended not to receive services through container get, but to make them private and inject into a method or constructor
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question