login root path / on symfony instead /login - symfony

<!-- templates/bootstrap/login/form-login.html.twig-->
<div class="container">
<div class="row">
<div style="padding-right: 0px;" class="col-12">
<form method="post">
<label for="inputEmail">Email</label>
<input type="email" value="{{ last_username }}" name="email" id="inputEmail" class="form-control" autocomplete="email" required autofocus>
<label for="inputPassword">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" autocomplete="current-password" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div style="margin-top: 10px;" class="mb-3">
You are logged in as {{ app.user.username }}, Logout
</div>
{% endif %}
<button style="margin-top: 10px; width: 100%;" class="btn btn-primary" type="submit">
Sign in
</button>
</form>
<div style="border-top: 1px solid black; height: 1px;margin-top: 10px;"></div>
<a style="width: 100%;" href="/registration" class="btn btn-outline-primary">Create an account</a>
<div style="height: 1px;margin-bottom: 10px;"></div>
</div>
</div>
</div>
All work correctly on "http://webserver5.com:8001/login" path.
But It doesn't work on "http://webserver5.com:8001/" path.
If I enter email and password correctly or incorrectly I obtain only refresh page. Why?
I want "/" root path because to point a login method controller.
Can you help me please.

<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_welcome';
private $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
public function authenticate(Request $request): PassportInterface
{
$email = $request->request->get('email', '');
$request->getSession()->set(Security::LAST_USERNAME, $email);
return new Passport(
new UserBadge($email),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge('authenticate', $request->get('_csrf_token')),
]
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
// For example:
return new RedirectResponse($this->urlGenerator->generate('app_contact_index'));
//throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
public const LOGIN_ROUTE = 'app_welcome';
This route app_welcome is defined thus:
/
App\Controller\SecurityController::login
Now it works.

Related

Why isn't my member information transferring from the razor page to the Controller

My razor view is only sending the two textboxes fields. I need it to either send a field called "isDesigner" which is a bool or I need to be able to retrieve this information in from the database in the controller based on what the "Email" is.
Here is the cshtml
#model Member
#{ ViewData["Title"] = "Index"; }
<div class="row">
<div class="col-md-4">
<form method="post">
<div>
<h4>Login</h4>
<div class="form-group">
<label class="control-label">Email: </label>
<input asp-for="Email" class="form-control" /><span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Password: </label>
<input asp-for="Password" class="form-control" /><span asp-validation-for="Password" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<label> <a class="nav-link text-dark" asp-area="" asp-controller="Members" asp-action="Register">Register</a></label>
<label> <a class="nav-link text-dark" asp-area="admin" asp-controller="Home" asp-action="Index">Admin</a></label>
This is the controller side
public class MembersController : Controller
{
private readonly ThreeDeePrintingHubContext _context;
private readonly ILogger<MembersController> _logger;
public MembersController(ThreeDeePrintingHubContext threeDeeHubContext, ILogger<MembersController> logger)
{
_context = threeDeeHubContext;
_logger = logger;
}
[HttpPost]
public ActionResult Index(Member member)
{
var isValidMember = _context.Members.Where(x => x.Email == member.Email && x.Password == member.Password).Any();
if (isValidMember)
{
return Redirect("/Product");
}
else
{
TempData["Message"] = "Invalid user";
return View();
}
}
As far as I know, if you want to send the bool value from the view to the controller, you should firstly get it or set it in the view and then send it to the controller.
More details, you could refer to below codes:
<form method="post">
<div>
<h4>Login</h4>
<div class="form-group">
<label class="control-label">Email: </label>
<input asp-for="Email" class="form-control" /><span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Password: </label>
<input asp-for="Password" class="form-control" /><span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">isDesigner: </label>
<input asp-for="isDesigner" class="form-control" /><span asp-validation-for="isDesigner" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary" />
</div>
</form>
Member class:
public class Member
{
public string Email { get; set; }
public string Password { get; set; }
public bool isDesigner { get; set; }
}
Result:
[HttpPost]
public ActionResult Index(Member member)
{
This was the answer
var myMember = _context.Members.Where(x => x.Email == member.Email && x.Password == member.Password).FirstOrDefault();
var isValidMember = myMember != null;
if (isValidMember)
{
if (myMember.IsDesigner)
{
return Redirect("/Product/DesignerIndex");
}
else
{
return Redirect("/Product");
}
}
else
{
TempData["Message"] = "Invalid user";
return View();
}
}
// GET: MembersController/Details/5
public ActionResult Details(int id)
{
return View();
}

Symfony simple login

i to do login in my webpage about symfony documentation example and i have a little problem. It's work but work a second time, after i clear cache. In first time i catch error with your session time out or you disabled cookie.
it's base.html.twig
{% if is_granted('ROLE_USER') %}
<div class="content">
<div class="starter-template">
{% block body %}{% endblock %}
</div>
</div>
{% else %}
<div class="container">
<div class="row">
<div class="col-md-offset-5 col-md-3">
<div class="form-login">
<h4>Welcome back.</h4>
<form action="{{ path('login') }}" method="post">
<input type="text" name="_username" id="userName" class="form-control input-sm chat-input" placeholder="username" />
</br>
<input type="password" name="_password" id="userPassword" class="form-control input-sm chat-input" placeholder="password" />
</br>
<div class="wrapper">
<span class="group-btn">
<button type="submit" href="#" class="btn btn-primary btn-md">login <i class="fa fa-sign-in"></i></button>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
{% endif %}
and login action:
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
I try return redirect in this action but nothing helps me.
If login to do in /login page it's work okey. But I want use with which construction how in base.html
Try work on dev mode.
1) Go on web directory
2) Open app.php file
3) Change the code inside app.php to
$kernel = new AppKernel('dev', true);
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Remove from controller
/**
* #Route("/login", name="login")
*/
Finally try move route in routing file.
For example in routing.yml:
login:
path: /login
defaults: { _controller: YourNameBundle:NameYourController:login }

Add telephone field to FOSUserBundle in symfony 2.7

Hi I'm trying to add new field (Telephone) to my FOS User bundle registration form. But Instead of getting this field I'm having this issue.
Method "telephone" for object "Symfony\Component\Form\FormView" does
not exist in FOSUserBundle:Registration:register_content.html.twig at
line 32
I'm trying to override custom templates and add new telephone field(Needed to customise to add few styles....).
\app\Resources\FOSUserBundle\views\Registration\register_content.html.twig
This is my 'register_content.html.twig' template,
{% trans_default_domain 'FOSUserBundle' %}
<div class="container">
<h1 style="text-align: center;">Register a User</h1>
<br>
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register form-horizontal'}}) }}
{# {{ form_widget(form) }}#}
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-4">
{{ form_widget(form.username, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(form.username) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
{{ form_widget(form.email, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(form.email) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Telephone</label>
<div class="col-sm-4">
{{ form_widget(form.telephone, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(form.telephone) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
{{ form_widget (form.plainPassword.first, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors (form.plainPassword.first) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Repeat password</label>
<div class="col-sm-4">
{{ form_widget (form.plainPassword.second, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors (form.plainPassword.second) }}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-default" value="{{ 'registration.submit'|trans }}" />
</div>
</div>
{{ form_end(form) }}
</div>
And this is my User Entity,
<?php
// src/AppBundle/Entity/User.php
namespace AdminBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="telephone", type="text", length=30, nullable=false)
*/
private $telephone;
/**
* Set nonotification
*
* #param text $telephone
* #return User
*/
public function settelephone($telephone) {
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return text
*/
public function gettelephone() {
return $this->telephone;
}
public function __construct() {
parent::__construct();
// your own logic
}
}
The form provided by FosUserBundle isn't aware of your new field.
You should add a formtype with the extra fields you created.
Example:
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('Telephone');
// Other fields
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
// Or for Symfony < 2.8
// return 'fos_user_registration';
}
// other methods needed setDefaultOptions() and getName()
You can find more information at the official documentation: http://symfony.com/doc/current/bundles/FOSUserBundle/overriding_forms.html

Symfony2 getLastUsername() function not working

I'm creating my first Symfony2 login form and want to use the getLastUsername() function to set the value of the username textbox but when calling the function it simply returns an empty string.
This is my SecurityController.php file:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class SecurityController extends Controller
{
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'security/login.html.twig',
array(
// last username entered by the user
'last_username' => $lastUsername,
'error' => $error,
)
);
}
/**
* #Route("/login_check", name="login_check")
*/
public function loginCheckAction()
{
}
}
?>
and my Twig template for the form:
{# app/Resources/views/security/login.html.twig #}
{% extends 'base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('css/login.css') }}" rel="stylesheet" />
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('js/login.js') }}"></script>
{% endblock %}
{% block body %}
<div id="container">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<div id="loginbox">
<form id="loginform" action="{{ path('login_check') }}" method="post">
<p>Enter username and password to continue.</p>
<div class="input-group input-sm">
<span class="input-group-addon"><i class="fa fa-user"></i></span><input class="form-control" type="text" name="_username" id="username" placeholder="Username" value="{{ last_username }}" />
</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock"></i></span><input class="form-control" type="password" name="_password" id="password" placeholder="Password" />
</div>
<div class="form-actions clearfix">
<div class="pull-left">
Create new account
</div>
<div class="pull-right">
Lost password?
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
<input type="submit" class="btn btn-block btn-primary btn-default" value="Login" />
</div>
</form>
</div>
</div>
{% endblock %}
Everything works fine. Logged in and out many times but the las username isn't showing. Thought Symfony might be using cookies to save the last used username but it isn't creating any cookies, only the PHP session is saved in a cookie. Is it a problem in the cookie configurations or may be something else?
Thanks,

Symfony2 - Wrong controller action called

I am doing a lot on the page and I think I am getting a conflict somewhere. Basically, my page initially shows an input and a blank div. When an input is provided and submitted, the page refreshed with the div full of data. The user can then select some of this data and finally submit again.
This is my view
{% block main %}
<div class="col-md-4">
<section class="panel panel-default">
<header class="panel-heading">
<h3 class="panel-title">Terminal</h3>
</header>
<div class="panel-body">
<form action="{{ path('NickAlertBundle_terminalSearch') }}" method="post" enctype="multipart/form-data" class="terminalForm" id="terminalForm">
<div class="row">
<div class="col-md-12">
<input type="text" class="addMargin" id="terminal_command" name="terminal_command" placeholder=">">
</div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-default" id="terminal_submit" value="Submit">
</div>
</div>
</form>
</div>
</section>
</div>
<div class="col-md-8" id="terminal-window">
<table class="terminalAvailability">
{% if data is defined %}
<form action="{{ path('NickAlertBundle_terminalCreate') }}" method="post" enctype="multipart/form-data" class="terminalForm">
{% for info in data %}
<tr>
<td class="flightNumber">{{ info.flightNumber }}</td>
<td class="details">{{ info.from ~ info.to }}</td>
{% for seat, availability in info.seats %}
<td class="seatClass">
<label for="{{ seat }}">
<span>{{ seat ~ availability }}</span>
</label>
<input type="checkbox" id="{{ seat }}" name="seats[{{ info.flightNumber }}][]" style="display: none;" value="{{ seat }}" />
</td>
{% endfor %}
<td class="otherInfo">{{ info.other }}</td>
</tr>
{% endfor %}
<div class="row">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-default" value="Submit">
</div>
</div>
</form>
{% endif %}
</table>
</div>
<div class="modal"></div>
{% endblock %}
The first div is the input and the second div is the div the data will be displayed, selected, and resubmitted.
I then have my controller actions
public function terminalAction()
{
return $this->render('NickAlertBundle:Page:terminal.html.twig');
}
public function terminalSearchAction(Request $request)
{
try {
$terminal_command = strtoupper($request->get('terminal_command'));
$error = array();
if (!$terminal_command) {
$error[] = "Please enter the Command";
}
if (count($error)) {
echo "There were errors adding the alert.\n\n";
foreach ($error as $item) {
echo $item . "\n";
}
die();
}
$uapiService = $this->container->get('alert_bundle.api_service');
$commandData = $apiService->terminalService($terminal_command);
return $this->render('NickAlertBundle:Page:terminal.html.twig', array(
'data' => $commandData,
));
}catch (Exception $e) {
}
}
public function terminalCreateAction(Request $request)
{
try {
foreach ($request->request->get('seats') as $row) {
foreach ($row as $seat) {
var_dump($seat);
}
}
return $this->render('NickAlertBundle:Page:terminal.html.twig');
}catch (Exception $e) {
}
}
And finally my routes
NickAlertBundle_terminal:
pattern: /terminal
defaults: { _controller: NickAlertBundle:Alert:terminal }
methods: [GET]
NickAlertBundle_terminalSearch:
pattern: /terminal
defaults: { _controller: NickAlertBundle:Alert:terminalSearch }
methods: [POST]
NickAlertBundle_terminalCreate:
pattern: /terminal
defaults: { _controller: NickAlertBundle:Alert:terminalCreate }
methods: [POST]
So the page is initially displayed fine. The user then enters some input, submits it, and the response data is then displayed in the div. So this means the first two routes work perfectly. With the data in the div, the user can select some data, and then submit it. However, when this data is submitted, they are displayed with
There were errors adding the alert. Please enter the Command
This error is for the second action, and should not have anything to do with the third action. The second form has its path set to NickAlertBundle_terminalCreate so why would it cross wires with the other action?
Thanks
NickAlertBundle_terminalCreate will always solve to NickAlertBundle_terminalSearch, because the RouteMatcher will always match the pattern /terminal + method POST to the first route with these rules.
Why not give NickAlertBundle_terminalSearch a pattern like /terminal/search?

Resources