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

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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀