让我们解释一下我的问题......我已经在很多帖子和官方文档中阅读了如何使用syfmfony构建会话系统一段时间。
创建用户需要创建表单我没有问题,我可以在数据库中检查它们,密码也是加密的......但实际上,我正在尝试构建“典型登录”< / em>所以,用户名和密码,我有一些问题
PD:我正在尝试执行ADMIN_ROLE和USER_ROLE
信息:我正在使用security.yml文件,因此我将编写我认为您需要的所有文件,如果我没有,请提出要求。
提前非常感谢你!
security.yml
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
encoders:
AppBundle\Entity\Users: bcrypt
AppBundle\Entity\Admin: bcrypt
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
chain_provider:
chain:
providers: [admin, users]
users:
entity:
class: AppBundle:Users
property: username
admin:
entity:
class: AppBundle:Admin
property: username
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
user_secured_area:
pattern: ^/
anonymous: ~
provider: chain_provider
form_login:
login_path: login_user
check_path: login_user
csrf_token_generator: security.csrf.token_manager
default_target_path: /
logout:
path: /logout
target: /
access_control:
# require ROLE_ADMIN for /admin*
- { path: ^/admin, roles: ROLE_ADMIN }
services.yml
# Learn more about services, parameters and containers at
# http://symfony.com/doc/current/book/service_container.html
parameters:
# parameter_name: value
services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
app.user_locale_listener:
class: AppBundle\EventListener\UserLocaleListener
arguments: ['@session']
tags:
- { name: kernel.event_listener, event: security.interactive_login, method: onInteractiveLogin }
实体:用户
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="UsersRepository")
* @UniqueEntity("username")
* @UniqueEntity("email")
*/
class Users implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $name;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $lastname;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $username;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
*
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
*
* @ORM\Column(type="string", length=64)
*/
private $password;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $language;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/*****************
* Users constructor.
*/
public function __construct() {
$this->language = 'es';
$this->isActive = true;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getLastname()
{
return $this->lastname;
}
/**
* @param mixed $lastname
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @param mixed $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return mixed
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* @param mixed $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
}
/**
* @return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* @param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* @return mixed
*/
public function getLanguage()
{
return $this->language;
}
/**
* @param mixed $language
*/
public function setLanguage($language)
{
$this->language = $language;
}
/**
* @return mixed
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
//implementaciones de la interface
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->isActive,
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->isActive,
) = unserialize($serialized);
}
}
SecurityController
namespace AppBundle\Controller;
use AppBundle\Entity\Admin;
use AppBundle\Entity\Users;
use AppBundle\Form\AdminFormType;
use AppBundle\Form\UserFormType;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
class SecurityController extends BaseController
{
/**
* @Route("/signup", name="signup")
* @param Request $request
* @return response
*/
public function guardarUser(Request $request)
{
$user = new Users();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$form = $this->createForm(UserFormType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('signup');
}
$this->addData('formUser', $form->createView());
return $this->render('AppBundle:signup:signup.html.twig', $this->getData());
}
/**
* @Route("/login", name="login_user")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showLogin(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();
$this->addData('last_username', $lastUsername);
$this->addData('error', $error);
return $this->render('AppBundle:login:login.html.twig', $this->getData());
}
}
登录视图
<div id="signupForm" class="row">
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if last_username %}
{{ last_username }}
{% endif %}
<!-- Formulario para iniciar sesión -->
<form action="{{ path('login_user') }}" method="post">
<div class="row">
<div class="input-field col s12">
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="username">Nombre usuario</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="password" id="password" name="_password" />
<label for="password">Constraseña</label>
</div>
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
<input type="submit" value="Accede">
</form>
<!-- ¿Has olvidado el password? -->
<p id="forgotPassword"><a href="/login">¿Se te ha olvidado el nombre de usuario o la contraseña?</a></p>
<!-- Redirige a /signup -->
<p id="tienesCuenta">¿No tienes cuenta? <a href="/signup">Registrate</a></p>
<!-- Linia gris que divide -->
<div class="divider"></div>
<!-- Aceptas los terminos y politicas de privacidad -->
<p id="terminos">Si haces click en iniciar sesión con Facebook/Gmail y no eres usuario de My appLibrary, pasarás a estar registrado y aceptas los <a href="/terminos">Términos y condiciones</a>
y la <a href="politicas">Política de privacidad</a>de My appLibrary.</p>
</div>