登录不起作用+ Symfony2

时间:2014-01-16 13:24:16

标签: php security symfony login

更新

我更新了我的用户实体,以便它实现AdvancedUserInterface和必要的功能。

<?php

namespace VolleyScout\VolleyScoutBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * Users
 *
 * @ORM\Table(name="users", indexes={@ORM\Index(name="fk_users_roles1_idx", columns={"role_id"})})
 * @ORM\Entity
 */
class Users implements AdvancedUserInterface
{
    /**
     * @var string
     *
     * @ORM\Column(name="user_username", type="string", length=45, nullable=false)
     */
    private $userUsername;

    /**
     * @var string
     *
     * @ORM\Column(name="user_firstname", type="string", length=45, nullable=false)
     */
    private $userFirstname;

    /**
     * @var string
     *
     * @ORM\Column(name="user_surname", type="string", length=255, nullable=false)
     */
    private $userSurname;

    /**
     * @var string
     *
     * @ORM\Column(name="user_email", type="string", length=255, nullable=false)
     */
    private $userEmail;

    /**
     * @var string
     *
     * @ORM\Column(name="user_type", type="string", nullable=false)
     */
    private $userType;

    /**
     * @var string
     *
     * @ORM\Column(name="user_password", type="string", length=60, nullable=false)
     */
    private $userPassword;

    /**
     * @var string
     *
     * @ORM\Column(name="user_salt", type="string", length=30, nullable=false)
     */
    private $userSalt;

    /**
     * @var string
     *
     * @ORM\Column(name="user_token", type="string", length=45, nullable=true)
     */
    private $userToken;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_created", type="datetime", nullable=false)
     */
    private $userCreated;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_modified", type="datetime", nullable=true)
     */
    private $userModified = null;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_deleted", type="datetime", nullable=true)
     */
    private $userDeleted = null;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_lastlogin", type="datetime", nullable=true)
     */
    private $userLastlogin = null;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_confirmed", type="datetime", nullable=true)
     */
    private $userConfirmed = null;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="user_locked", type="datetime", nullable=true)
     */
    private $userLocked = null;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $userId;

    /**
     * @var \VolleyScout\VolleyScoutBundle\Entity\Roles
     *
     * @ORM\ManyToOne(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Roles")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="role_id", referencedColumnName="role_id")
     * })
     */
    private $role;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Teams", inversedBy="user")
     * @ORM\JoinTable(name="user_follows_teams",
     *   joinColumns={
     *     @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="team_id", referencedColumnName="team_id")
     *   }
     * )
     */
    private $team;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="VolleyScout\VolleyScoutBundle\Entity\Competitions", inversedBy="user")
     * @ORM\JoinTable(name="user_follows_competitions",
     *   joinColumns={
     *     @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="competition_id", referencedColumnName="competition_id")
     *   }
     * )
     */
    private $competition;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->team = new \Doctrine\Common\Collections\ArrayCollection();
        $this->competition = new \Doctrine\Common\Collections\ArrayCollection();
        $this->userSalt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
    }


    /**
     * Set userUsername
     *
     * @param string $userUsername
     * @return Users
     */
    public function setUserUsername($userUsername)
    {
        $this->userUsername = $userUsername;

        return $this;
    }

    /**
     * Get userUsername
     *
     * @return string
     */
    public function getUserUsername()
    {
        return $this->userUsername;
    }

    /**
     * Set userFirstname
     *
     * @param string $userFirstname
     * @return Users
     */
    public function setUserFirstname($userFirstname)
    {
        $this->userFirstname = $userFirstname;

        return $this;
    }

    /**
     * Get userFirstname
     *
     * @return string
     */
    public function getUserFirstname()
    {
        return $this->userFirstname;
    }

    /**
     * Set userSurname
     *
     * @param string $userSurname
     * @return Users
     */
    public function setUserSurname($userSurname)
    {
        $this->userSurname = $userSurname;

        return $this;
    }

    /**
     * Get userSurname
     *
     * @return string
     */
    public function getUserSurname()
    {
        return $this->userSurname;
    }

    /**
     * Set userEmail
     *
     * @param string $userEmail
     * @return Users
     */
    public function setUserEmail($userEmail)
    {
        $this->userEmail = $userEmail;

        return $this;
    }

    /**
     * Get userEmail
     *
     * @return string
     */
    public function getUserEmail()
    {
        return $this->userEmail;
    }

    /**
     * Set userType
     *
     * @param string $userType
     * @return Users
     */
    public function setUserType($userType)
    {
        $this->userType = $userType;

        return $this;
    }

    /**
     * Get userType
     *
     * @return string
     */
    public function getUserType()
    {
        return $this->userType;
    }

    /**
     * Set userPassword
     *
     * @param string $userPassword
     * @return Users
     */
    public function setUserPassword($userPassword)
    {
        $this->userPassword = $userPassword;

        return $this;
    }

    /**
     * Get userPassword
     *
     * @return string
     */
    public function getUserPassword()
    {
        return $this->userPassword;
    }

    /**
     * Set userSalt
     *
     * @param string $userSalt
     * @return Users
     */
    public function setUserSalt($userSalt)
    {
        $this->userSalt = $userSalt;

        return $this;
    }

    /**
     * Get userSalt
     *
     * @return string
     */
    public function getUserSalt()
    {
        return $this->userSalt;
    }

    /**
     * Set userToken
     *
     * @param string $userToken
     * @return Users
     */
    public function setUserToken($userToken)
    {
        $this->userToken = $userToken;

        return $this;
    }

    /**
     * Get userToken
     *
     * @return string
     */
    public function getUserToken()
    {
        return $this->userToken;
    }

    /**
     * Set userCreated
     *
     * @param \DateTime $userCreated
     * @return Users
     */
    public function setUserCreated($userCreated)
    {
        $this->userCreated = $userCreated;

        return $this;
    }

    /**
     * Get userCreated
     *
     * @return \DateTime
     */
    public function getUserCreated()
    {
        return $this->userCreated;
    }

    /**
     * Set userModified
     *
     * @param \DateTime $userModified
     * @return Users
     */
    public function setUserModified($userModified)
    {
        $this->userModified = $userModified;

        return $this;
    }

    /**
     * Get userModified
     *
     * @return \DateTime
     */
    public function getUserModified()
    {
        return $this->userModified;
    }

    /**
     * Set userDeleted
     *
     * @param \DateTime $userDeleted
     * @return Users
     */
    public function setUserDeleted($userDeleted)
    {
        $this->userDeleted = $userDeleted;

        return $this;
    }

    /**
     * Get userDeleted
     *
     * @return \DateTime
     */
    public function getUserDeleted()
    {
        return $this->userDeleted;
    }

    /**
     * Set userLastlogin
     *
     * @param \DateTime $userLastlogin
     * @return Users
     */
    public function setUserLastlogin($userLastlogin)
    {
        $this->userLastlogin = $userLastlogin;

        return $this;
    }

    /**
     * Get userLastlogin
     *
     * @return \DateTime
     */
    public function getUserLastlogin()
    {
        return $this->userLastlogin;
    }

    /**
     * Set userConfirmed
     *
     * @param \DateTime $userConfirmed
     * @return Users
     */
    public function setUserConfirmed($userConfirmed)
    {
        $this->userConfirmed = $userConfirmed;

        return $this;
    }

    /**
     * Get userConfirmed
     *
     * @return \DateTime
     */
    public function getUserConfirmed()
    {
        return $this->userConfirmed;
    }

    /**
     * Set userLocked
     *
     * @param \DateTime $userLocked
     * @return Users
     */
    public function setUserLocked($userLocked)
    {
        $this->userLocked = $userLocked;

        return $this;
    }

    /**
     * Get userLocked
     *
     * @return \DateTime
     */
    public function getUserLocked()
    {
        return $this->userLocked;
    }

    /**
     * Get userId
     *
     * @return integer
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * Set role
     *
     * @param \VolleyScout\VolleyScoutBundle\Entity\Roles $role
     * @return Users
     */
    public function setRole(\VolleyScout\VolleyScoutBundle\Entity\Roles $role = null)
    {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return \VolleyScout\VolleyScoutBundle\Entity\Roles
     */
    public function getRole()
    {
        return $this->role;
    }

    /**
     * Add team
     *
     * @param \VolleyScout\VolleyScoutBundle\Entity\Teams $team
     * @return Users
     */
    public function addTeam(\VolleyScout\VolleyScoutBundle\Entity\Teams $team)
    {
        $this->team[] = $team;

        return $this;
    }

    /**
     * Remove team
     *
     * @param \VolleyScout\VolleyScoutBundle\Entity\Teams $team
     */
    public function removeTeam(\VolleyScout\VolleyScoutBundle\Entity\Teams $team)
    {
        $this->team->removeElement($team);
    }

    /**
     * Get team
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTeam()
    {
        return $this->team;
    }

    /**
     * Add competition
     *
     * @param \VolleyScout\VolleyScoutBundle\Entity\Competitions $competition
     * @return Users
     */
    public function addCompetition(\VolleyScout\VolleyScoutBundle\Entity\Competitions $competition)
    {
        $this->competition[] = $competition;

        return $this;
    }

    /**
     * Remove competition
     *
     * @param \VolleyScout\VolleyScoutBundle\Entity\Competitions $competition
     */
    public function removeCompetition(\VolleyScout\VolleyScoutBundle\Entity\Competitions $competition)
    {
        $this->competition->removeElement($competition);
    }

    /**
     * Get competition
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCompetition()
    {
        return $this->competition;
    }

    private $player;

    /**
     * Get player
     *
     * @return \VolleyScout\VolleyScoutBundle\Entity\Players
     */

    public function getPlayer() {
        return $this->player;
    }
    /**
     * Set player
     *
     * @param \VolleyScout\VolleyScoutBundle\Entity\Players $player
     * @return Users
     */
    public function setPlayer(\VolleyScout\VolleyScoutBundle\Entity\Players $player = null){
        $this->player = $player;

        return $this;
    }


    public function getUsername()
    {
        return $this->userUsername;
    }

    public function getSalt()
    {
        return $this->userSalt;
    }

    public function getPassword()
    {
        return $this->userPassword;
    }


    public function eraseCredentials()
    {
        // Do nothing.
    }

    /**
     * Implementation of UserInterface method
     *
     * @return array Roles
     */
    public function getRoles()
    {
        return ['ROLE_USER'];
    }


    /**
     * Implementation of AdvancedUserInterface method
     *
     * @return boolean
     */
    public function isAccountNonExpired()
    {
        return true;
    }

    /**
     * Implementation of AdvancedUserInterface method
     *
     * @return boolean
     */
    public function isAccountNonLocked()
    {
        return true;
    }

    /**
     * Implementation of AdvancedUserInterface method
     *
     * @return boolean
     */
    public function isCredentialsNonExpired()
    {
        return true;
    }

    /**
     * Implementation of AdvancedUserInterface method
     *
     * @return boolean
     */
    public function isEnabled()
    {
        // CHECK IF $this->confirmed is not null
        return true;
    }
}

但是我还是无法登录。我还缺少什么吗?
我的登录视图:

    {% extends "::securitybase.html.twig" %}

{% block title %}Login | {{ parent() }}{% endblock %}

{% block body %}
    {% set class_error = ' has-error alert alert-warning' %}
    <h1 class="col-sm-offset-3 col-sm-9">Please sign on</h1>
    {% if loginError %}
        <div class="alert alert-warning">{{ loginError.message }}</div>
    {% endif %}
    {{ form_errors(loginForm) }}
    {{ form_start(loginForm, {"attr": {"class": "form-horizontal"} }) }}
    <div class="form-group{{ loginForm.userUsername.vars.valid ? '' : class_error }}">
        {{ form_label(loginForm.userUsername, label|default(),
        { "label_attr": { "class": "col-sm-3 control-label"}}) }}
        <div class="col-sm-9">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                {{ form_widget(loginForm.userUsername,
                {"attr": {"class": "form-control" } }) }}
            </div>
        </div>
        {% if not loginForm.userUsername.vars.valid %}
            <div class="col-sm-offset-3 col-sm-9">
                <h5><i class="glyphicon glyphicon-warning-sign"></i> <strong>Please fix:</strong></h5>
                {{ form_errors(loginForm.userUsername) }}
            </div>
        {% endif %}
    </div>
    <div class="form-group{{ loginForm.userPassword.vars.valid ? '' : class_error }}">
        {{ form_label(loginForm.userPassword, label|default(),
        { "label_attr": { "class": "col-sm-3 control-label"}}) }}
        <div class="col-sm-9">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                {{ form_widget(loginForm.userPassword,
                {"attr": {"class": "form-control" } }) }}
            </div>
        </div>
        {% if not loginForm.userPassword.vars.valid %}
            <div class="col-sm-offset-3 col-sm-9">
                <h5><i class="glyphicon glyphicon-warning-sign"></i> <strong>Please fix:</strong></h5>
                {{ form_errors(userPassword.userUsername) }}
            </div>
        {% endif %}
    </div>
    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-9">
            <div class="checkbox">
                <input type="checkbox" id="remember" name="remember" checked>
                <label for="remember">Remember me</label>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-9">
            {{ form_widget(loginForm.btn_login,
            {"attr": {"class": "btn btn-primary"} }) }}
            <a href="{{ path('volley_scout_registerpage') }}" class="btn btn-link">Register</a>
        </div>
    </div>
    {{ form_end(loginForm) }}
{% endblock %}

我的loginAction:

    public function loginAction(Request $request)
{
    // New user
    $user = new Users();

    $form = $this->createForm(new LoginType(), $user);

    if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
        $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
        $session = $request->getSession();
        $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        $session->remove(SecurityContext::AUTHENTICATION_ERROR);
    }

    return $this->render('VolleyScoutBundle:User:login.html.twig', array(
        'loginForm'  => $form->createView(),
        'loginError' => $error,
    ));
}

我的security.yml:

security:
    encoders:
        VolleyScout\VolleyScoutBundle\Entity\Users:
            algorithm: bcrypt
            cost: 15

    role_hierarchy:
        ROLE_ADMIN:       [ROLE_USER]

    providers:
        members:
            entity:
                class: VolleyScoutBundle:Users
                property: userUsername

    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/
            anonymous: true
        secured_area:
            pattern: ^/
            anonymous: ~
            form_login:
                login_path: volley_scout_loginpage
                check_path: volley_scout_logincheck
                username_parameter: login[username]
                password_parameter: login[password]
                always_use_default_target_path: true
                default_target_path: volley_scout_homepage
            logout:
                path:   volley_scout_logout
                target: volley_scout_loginpage
            remember_me:
                 key:      "%secret%"
                 lifetime: 31536000 # 365 days in seconds
                 path:     /
                 domain:   ~ # Defaults to the current domain from $_SERVER
                 remember_me_parameter: remember

    access_control:
         - { path: /_wdt/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: /_profiler/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: /login, role: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: /register, role: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: /admin, roles: ROLE_ADMIN }
         - { path: /.*, role: IS_AUTHENTICATED_FULLY }

更新2:
当我检查我的dev.log文件时,我收到以下错误:

[2014-01-17 18:20:46] event.DEBUG: Notified event "kernel.terminate" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate". [] []

每次我尝试登录..

3 个答案:

答案 0 :(得分:1)

请尝试使用https://github.com/FriendsOfSymfony/FOSUserBundle - 它可以帮助您节省几个小时或更长时间。这是用于注册,登录和管理用户的可靠捆绑包。还可以让您更改安全性,发送电子邮件或更改密码。

它在我们的许多项目中帮助了我。

答案 1 :(得分:1)

问题正是@Cerad提到的,你没有实现UserInterfaceAdvancedUserInterface。看一下文档How To load users from the database,它会给你一些如何做到这一点的例子。通过实施AdvancedUserInterface,您还可以使用其他很酷的功能,例如管理数据库中的roles,锁定不“活跃”的用户或其他很酷的功能。看一下这篇文章,我相信它会给你答案。

use Symfony\Component\Security\Core\User\AdvancedUserInterface;

class Users implements AdvancedUserInterface
{
    //.....
}

请确保将所需的getters添加到您的用户类。

对于UserInterface,您需要以下这些功能:

getRoles()
getPassword()
getSalt()
getUsername()
eraseCredentials()

对于AdvancedUserInterface,您需要以上所有内容以及

isAccountNonExpired()
isAccountNonLocked()
isCredentialsNonExpired()
isEnabled()

答案 2 :(得分:0)

csrf保护令牌在登录视图中是否显示良好?

您可以尝试添加

{{ form_rest(loginForm) }}

如果情况并非如此,请在表格内的某处。