duanhai1455 2017-02-19 18:44
浏览 302
已采纳

Laravel 5 Auth:attempt()总是返回false

I am trying to make a custom login with multi auth. For the meantime, I am trying to do the login for admin. When an admin logs in, the login function handles it (it also just refreshes without the login function) Auth:attempt() seems to be always returning false, however (I have a different table name and fields). Aside from that, I can freely access the dashboard by just changing the url even if the user is not really logged in.

AuthController

/*
    |--------------------------------------------------------------------------
    | 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 = 'admin/dashboard';

    /**
     * Where to redirect users after logout.
     *
     * @var string
     */
    protected $redirectAfterLogout  = 'admin/login';

    /**
     * Guard for admin
     *
     * 
     */
    protected $guard = 'admin';

    /**
     * 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, [
            'OUsername' => 'required|max:255|unique:users',
            'OPassword' => 'required|min:6|confirmed',
        ]);
    }

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

    /**
     * Show login form.
     *
     * 
     * 
     */

    public function showLoginForm()
    {
        if (view()->exists('auth.authenticate')) {
            return view('auth.authenticate');
        }

        return view('pages.admin.login');
    }

    /**
     * Show registration form.
     *
     * 
     * 
     */

    public function showRegistrationForm()
    {
        return view('pages.admin.register');
    }  


    public function login(Request $request)
    {
        //Get inputs
        $username =  $request->input('username');
        $password =  $request->input('password');

        //Redirect accordingly     
        if (Auth::guard('admin')->attempt(array('OUsername' => $username, 'OPassword' => $password)))
        {
            return redirect()->intended('admin/dashboard');
        }

        else
        {
            //when echoing something here it is always displayed thus admin login is just refreshed.
            return redirect('admin/login')->withInput()->with('message', 'Login Failed');
        }
    }

Admin Provider Model

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


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'OUsername', 'OPassword',
    ];

    public $timestamps = false;

    /**
     * Set primary key
     *
     * @var int
     */
    protected $primaryKey = 'AccountOfficerID';

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'OPassword', 'remember_token',
    ];

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

Routes

    /*
    |--------------------------------------------------------------------------
    | Application Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register all of the routes for an application.
    | It's a breeze. Simply tell Laravel the URIs it should respond to
    | and give it the controller to call when that URI is requested.
    |
    */

    Route::group(['namespace' => 'Admin', 'middleware' => 'guest'], function(){
//This uses the guest middleware with the class name RedirectIfAuthenticated
        Route::auth();

        //Route for admin dashboard view
        Route::get('admin/dashboard', array('as' => 'dashboard', 'uses' => 'AdminController@showDashboard'));

    });

    Route::group(['middleware' => ['web']], function () {

        //Route for login
        Route::get('admin/login','AdminAuth\AuthController@showLoginForm');
        Route::post('admin/login','AdminAuth\AuthController@login');
        Route::get('admin/logout','AdminAuth\AuthController@logout');

        //Route for registration
        Route::get('admin/ims-register', 'AdminAuth\AuthController@showRegistrationForm');
        Route::post('admin/ims-register', 'AdminAuth\AuthController@register');

    }); 

RedirectIfAuthenticated (guest middleware)

/**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard('admin')->check()) {         
            return redirect('admin/dashboard');
        }

        if (Auth::guard($guard)->check()) {         
            return redirect('/');
        }

        return $next($request);
    }

I have just started learning the MVC framework and started using Laravel. Thank you for the help.

Notes

My passwords are stored using bcrypt() with column length of 255

I have tried checking if the hash from the table matches my input using Hash::check. It returns true. But when I do this:

dd( Auth::guard('admin')->attempt(array('OUsername' => $username, 'OPassword' => $password)));

It is false.

Tried checking the results based on the answer from this question especially # 7. Still the same.

  • 写回答

1条回答 默认 最新

  • dqbr37828 2017-02-20 04:33
    关注

    The problem seems to be with this line

    'OPassword' => $password
    

    I changed it to

    'password' => $password
    

    It has to be password not OPassword. And then in my Admin model I specified

    public function getAuthPassword()
    {
        return $this->OPassword;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵