1
votes

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
@МаксимСтепанов Solves my problems with dashboard but not with login.Friency Fernandez

1 Answers

1
votes

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;
}