2014-09-27 5 views
0

У меня проблема с аутентификацией laravel 4.2. Auth :: попытка() всегда возвращает false. Hash :: check() возвращает false.
Я устал решать эту проблему. Я прочитал много учебников, и я не могу найти решение.

Вот некоторые из моих важных файлов:
мой auth.php
Laravel Auth :: попытка() return false

<?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

Проблема ваша $data, что вы передаете 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; 
} 

Это потому, что вам нужно передать password в массив в качестве пароля попытаться метод (вы можете узнать больше об этом на How to change/Custom password field name for Laravel 4 and Laravel 5 user authentication)

Смежные вопросы