Laravel Auth :: attempt()返回false [英] Laravel Auth::attempt() return false

查看:397
本文介绍了Laravel Auth :: attempt()返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对laravel 4.2身份验证有疑问. Auth :: attempt()始终返回false. Hash :: check()返回false.
我很累要解决这个问题.我看了很多教程,却找不到解决方法.

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

I have a problem with laravel 4.2 authentication. Auth::attempt() always return false. Hash::check() return false.
I am tired to solve this problem. I read many tutorial and I can't find the solution.

Here are some of my important files:
my 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

推荐答案

问题是您传递给Auth::attempt$data.你应该改变

The problem is your $data that you pass to Auth::attempt. You should change

if (Auth::attempt($data))

进入

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

if (Auth::attempt($dataAttempt))

并将以下功能添加到您的用户模型:

and add to your User model the following function:

public function getAuthPassword() {
    return $this->UserEmail;
}

这是因为您需要在数组中传递password作为尝试方法的密码(您可以在

This is because you need to pass password in array as your password to attempt method (You can read more about it at How to change / Custom password field name for Laravel 4 and Laravel 5 user authentication)

这篇关于Laravel Auth :: attempt()返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆