Laravel Auth :: attempt()返回false

时间:2014-09-27 11:40:44

标签: php authentication laravel login laravel-4

我对laravel 4.2身份验证有疑问。 Auth :: attempt()总是返回false。 Hash :: check()返回false 我厌倦了解决这个问题。我阅读了很多教程,但我找不到解决方案。

以下是我的一些重要文件:
我的auth.php

<?php

 return array(
    'driver'   => 'eloquent', 
    'model'    => 'User',  
    'table'    => 'users',
    'reminder' => array(
        'email'  => 'emails.auth.reminder',
        'table'  => 'password_reminders',
        'expire' => 60,
     ),
);


我的UserModel.php

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

/**
 * The database table used by the model
 *
 * @var string
 */
protected $table = 'users';

/**
 * The primary key used by the model
 *
 * @var integer
 */
protected $primaryKey = 'UserId';

/**
 * The name of the "created at" column
 *
 * @var string
 */
const CREATED_AT = 'UserCreatedAt';

/**
 * The name of the "updated at" column
 *
 * @var string
 */
const UPDATED_AT = 'UserUpdatedAt';

/**
 * The attributes excluded from the model's JSON form
 *
 * @var array
 */
protected $hidden = array('UserPassword', 'UserRememberToken');

protected $fillable = array(
    'UserName',
    'UserSurname',
    'UserCity',
    'UserStreet',
    'UserPostalCode',
    'UserPostalCity',
    'UserDeskPhone',
    'UserMobilePhone',
    'UserEmail',
    'UserPassword',
    'UserType',
    'UserPermission',
    'UserActive'
);

protected $guarded = array('UserId', 'HotelId', 'UserRememberToken', 'UserCreatedAt', 'UserUpdatedAt');

public static $rules = array(
    'name'=>'required|alpha|min:2',
    'surname'=>'required|alpha|min:2',
    'email'=>'required|email|unique:users',
    'password'=>'required|alpha_num|between:8,100|confirmed',
    'password_confirmation'=>'required|alpha_num|between:8,100'
);

/**
 * Get the unique identifier for the user
 *
 * @return mixed
 */
public function getAuthIdentifier()
{
    return $this->getKey();
}

/**
 * Get the password for the user
 *
 * @return string
 */
public function getAuthPassword()
{
    return $this->UserPassword;
}

/**
 * Get the e-mail address where password reminders are sent
 *
 * @return string
 */
public function getReminderEmail()
{
    return $this->UserEmail;
}

/**
 * Get the remember token for the user
 *
 * @return string
 */
public function getRememberToken()
{
    return $this->UserRememberToken;
}

/**
 * Set the remember token for the user
 *
 * @var string
 */
public function setRememberToken($value)
{
    $this->UserRememberToken = $value;
}

/**
 * Get the remember token name used by the model
 *
 * @return string
 */
public function getRememberTokenName()
{
    return 'UserRememberToken';
}

/**
 * Get the user type
 *
 * @return integer
 */
public function getUserType()
{
    return 'UserType';
}
}


我的UserController.php

    <?php

class UserController extends BaseController {

    /*
    |--------------------------------------------------------------------------
    | User Controller
    |--------------------------------------------------------------------------
    */

    /**
     * UserController's constructor
     */
    public function __construct() {
        $this->beforeFilter('csrf', array('on'=>'post'));
        $this->beforeFilter('auth', array('only'=>array('getBackend')));
    }

    /**
     * Show register page for the user
     */
    public function getRegister()
    {
        return View::make('app.user.register');
    }

    /**
     * Action after pressing the register button
     */
    public function postCreate() {
        $validator = Validator::make(Input::all(), User::$rules);

        if ($validator->passes()) {
            // validation has passed, save user in DB
            $user = new User;
            $user->UserName = Input::get('name');
            $user->UserSurname = Input::get('surname');
            $user->UserEmail = Input::get('email');
            $user->UserPassword = Hash::make(Input::get('password'));
            $user->save();

            return Redirect::to('user/login')->with('message', 'Dodano użytkownika!');
        } else {
            // validation has failed, display error messages
            return Redirect::to('user/register')
                ->with('message', 'Pojawiły się następujące błędy:')
                ->withErrors($validator)
                ->withInput();
        }
    }

    /**
     * Show login page for the user
     */
    public function getLogin()
    {
        // Check if we already logged in
        if (Auth::check())
        {
            // Redirect to backend homepage
            return Redirect::to('backend')->with('message', 'Jesteś zalogowany!');
        }
        return View::make('app.user.login');
    }

    /**
     * Action after pressing the login button
     */
    public function postLogin()
    {
        // Get all the inputs
        $data = array(
            'UserEmail' => Input::get('email'),
            'UserPassword' => Input::get('password')
        );

        // Declare the rules for the form validation
        $rules = array(
            'UserEmail'  => 'required|email|min:6',
            'UserPassword'  => 'required|between:8,100'
        );

        // Declare error message for the rules for the form validation
        $messages = array(
            'UserEmail.required' => 'Adres e-mail nie może być pusty!',
            'UserEmail.email' => 'Adres e-mail jest nieprawidłowy!',
            'UserEmail.min' => 'Adres e-mail musi mieć minimum 6 znaków!',
            'UserPassword.required' => 'Hasło nie może być puste!',
            'UserPassword.between' => 'Hasło musi mieć od 8 do 100 znaków!'
        );

        // Validate the inputs
        $validator = Validator::make($data, $rules, $messages);

        // Check if the form validates with success
        if ($validator->passes())
        {
            // Try to log the user in
            if (Auth::attempt($data))
            {
                // Redirect to backend homepage
                return Redirect::to('backend');
            }
            else
            {
                // Redirect to the login page
                return Redirect::to('user/login')
                    ->withErrors('Twój adres e-mail lub hasło jest nieprawidłowe!')
                    ->withInput(Input::except('password'));
            }
        }

        // Something went wrong
        return Redirect::to('user/login')
            ->withErrors($validator)
            ->withInput(Input::except('password'));
    }

    /**
     * Show the profile for the given user
     */
    public function getProfile($id)
    {
        $user = User::find($id);
        return View::make('app.user.profile', array('user' => $user));
    }

    /**
     * Show backend homepage
     */
    public function getBackend()
    {
        return View::make('app.backend.start');
    }
}


我的login.blade.php

@extends('app.user.master')

@section('title')
    {{ 'Logowanie' }}
@stop

@section('content')
<div class="container-fluid">
    <div id="page-login" class="row">
        <div class="col-xs-12 col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
            {{--
            <div class="text-right">
                <a href="page_register.html" class="txt-default">Need an account?</a>
            </div>
            --}}
            <div class="box">
                <div class="box-content">
                    {{ Form::open(array('url'=>'user/login', 'class'=>'form-signin')); }}
                    <div class="text-center">
                        <h3 class="page-header">{{ Config::get('app.name') }} - logowanie</h3>
                    </div>
                    @if($errors->has())
                        <div class="form-group">
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li class="alert">{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif
                    <div class="form-group">
                        <label class="control-label">E-mail</label>
                        {{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'E-mail')) }}
                    </div>
                    <div class="form-group">
                        <label class="control-label">Hasło</label>
                        {{ Form::password('password', array('class'=>'form-control', 'placeholder'=>'Hasło')) }}
                    </div>
                    <div class="text-center">
                        {{ Form::submit('Zaloguj', array('class'=>'btn btn-large btn-primary btn-block')) }}
                    </div>
                    {{ Form::close() }}
                </div>
            </div>
        </div>
    </div>
</div>
@stop

1 个答案:

答案 0 :(得分:1)

问题在于您传递给$data的{​​{1}}。你应该改变

Auth::attempt

if (Auth::attempt($data))

并在您的用户模型中添加以下功能:

$dataAttempt = array(
            'UserEmail' => Input::get('email'),
            'password' => Input::get('password')
        );

if (Auth::attempt($dataAttempt))

这是因为您需要将数组中的public function getAuthPassword() { return $this->UserEmail; } 作为密码传递给尝试方法(您可以在How to change / Custom password field name for Laravel 4 and Laravel 5 user authentication了解更多信息)