dongshungai4857 2016-05-29 20:18
浏览 160
已采纳

Laravel 5.2 Auth登录工作,Auth :: check失败

I know this is a common problem with laravel 5.2 but I have been searching for hours and unable to figure this out.

Currently, I want to do a simple authenticate call through a login form. I am using a custom database that attaches to the laravel AuthController. I have a form that posts to auth/login and validates correctly as it redirects back to the desired route, the home page. However when I try to call Auth::check() on that route it always returns false as if it is undefined. Now I am fully aware of having to use the 'web' middle-ware for my routes to keep session data. I have tried that as indicated here Laravel 5.2 Auth not Working, which sadly did not fix it for me. I then realized I am using version 5.2.32 of laravel which means I don't even need to define 'web' middle ware as it is used by default passed version 5.2.27 as indicated by the ability to receive error messages once the web middleware is removed.

This problem has been knicking at me for the entire day, the authentication goes through perfectly and redirects. However once I redirect, Auth just doesn't work. If I could at least get a fresh pair of eyes on this code it would be greatly appreciated.

******routes.php********************************

// Route::group not necessary after version 5.2.27 of laravel on by default, simply here for display purposes.
Route::group(['middleware' => 'web'], function () {

    Route::get('/', function(){

        if(Auth::check()){
            echo "logged in";
        }

    return view('pages.home');
    }); 


    Route::get('channels/{channel}', function($channel) 
    {     
        return view('pages.channels', ['channel' => $channel] );
    });
    Route::get('events', function() 
    {    
        return view('pages.events');
    });
    Route::get('news', function() 
    {    
        return view('pages.news');
    });
    Route::get('contact', function() 
    {    
        return view('pages.contact');
    });

    // Login Form routes
    Route::get('login', function(){

        return view('pages.login');

    });

    // Just Get login working, instead of using Route::auth()
    Route::post('auth/login', 'Auth\AuthController@login');
});

*****login.blade.php****************************** My Form

@extends('layouts.master')

@section('content')
<div class="text-center col-md-4 col-md-offset-4">
    <h1>Login</h1>

    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>

    {!! Form::open(array('url' => '/auth/login', 'class' => 'form')) !!}

    <div class="form-group">
        {!! Form::label('Username') !!}
        {!! Form::text('username', null, 
            array('required', 
                  'class'=>'form-control', 
                  'placeholder'=>'Your username')) !!}
    </div>

    <div class="form-group">
        {!! Form::label('Password') !!}
        {!! Form::text('password', null, 
            array('required', 
                  'class'=>'form-control', 
                  'placeholder'=>'Your password')) !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Login', 
          array('class'=>'btn btn-primary')) !!}
    </div>
    {!! Form::close() !!}
    <div>
        Don't have an account? <a href="">Sign up.</a>
    </div>
</div>

@endsection

*******New_Client.php **********************Custom database model

namespace App;

// http://laravel-recipes.com/recipes/11/changing-your-authentication-model
// model change to https://laravel.com/docs/5.0/upgrade

use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class New_Client extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'new_client';

    /*Turn off timestamps, as we do not have them*/
    public $timestamps = false;

    use Authenticatable, Authorizable, CanResetPassword;
}

*Note I have attached this model in config/auth.php under provider->users->model

Finally AuthController.php itself, its basically the default controller taht comes packaged with laravel. However the loginPath, redirectPath and username variables are only changed.

<?php

namespace App\Http\Controllers\Auth;

use App\New_Client;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

// temp

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
    * Redirect user after failed login
    */
    protected $loginPath = '/login';

    // Override email required field with this 
    //https://stackoverflow.com/questions/28584531/modify-existing-authorization-module-email-to-username
    protected $username = 'username';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|max:255',
            'password' => 'required|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'username' => $data['name'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

*This is completely irrelevant but I also removed the line return $this->hasher->check($plain, $user->getAuthPassword()); and replaced it with, return ($plain == $user->getAuthPassword()); in EloquentUserProvider.php as my passwords are not hashed at the moment and will be put back once testing is complete. I know this won't affect the problem at hand but I have know idea why I can't refer to Auth in route

Edit: This is the database we are authenticating against. We have the username, the password, even the remember_token indicated in the documentation https://laravel.com/docs/5.2/authentication#introduction-database-considerations

CREATE TABLE `new_client` (
  `client_idx_NW` int(11) NOT NULL,
  `ID` int(11) NOT NULL DEFAULT '450',
  `username` varchar(60) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `first_name` varchar(20) NOT NULL DEFAULT 'John',
  `surname_name` varchar(20) NOT NULL DEFAULT 'Smith',
  `organization_name` varchar(20) NOT NULL DEFAULT 'Sony',
  `phone_number` varchar(20) NOT NULL DEFAULT '6476231234',
  `address_street` varchar(256) NOT NULL DEFAULT '230-140 Cresent Road',
  `city` varchar(20) NOT NULL DEFAULT 'Burlington',
  `province` varchar(20) NOT NULL DEFAULT 'Ontario',
  `country` varchar(20) NOT NULL DEFAULT 'Canada',
  `postal_code` varchar(20) NOT NULL DEFAULT 'l7l4C3',
  `email_address` varchar(20) NOT NULL DEFAULT 'JohnSmith@sony.ca',
  `credit_card_number` varchar(20) NOT NULL,
  `expiry_date` date NOT NULL,
  `security_code` varchar(20) NOT NULL,
  `accepted` tinyint(1) NOT NULL,
  `remember_token` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Regards

  • 写回答

1条回答 默认 最新

  • dsfdgdsfd23212 2016-05-29 21:55
    关注

    So I ended up figuring out the solution, I just wish this wasn't down-voted. But oh well, on my model I never indicated a primary key and as such when retrieving the user it was not possible.

    To fix for me it simply required this line

     protected $primaryKey = 'client_idx_NW';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器