无法使用Guard在Laravel中运行登录应用程序

时间:2019-05-11 14:56:53

标签: php laravel laravel-5

我正在借助中间件创建登录应用程序。现在的问题是,当我运行应用程序时,出现错误消息:

  

类型错误:参数2传递给   Illuminate \ Auth \ SessionGuard :: __ construct()必须实现接口   Illuminate \ Contracts \ Auth \ UserProvider,给定null,在   C:\ wamp64 \ www \ Login \ vendor \ laravel \ framework \ src \ Illuminate \ Auth \ AuthManager.php   在第123行

实际上,我想实施基于角色的检查,并为此使用了警卫 一种是简单用户,另一种是管理员。请帮助解决我的问题。

这是我完整的代码:

  

LoginController.php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;

class LoginController extends Controller {
    //
    public function getLogin() {
        return view('login');
    }
    public function postLogin(Request $request) {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
        // Attempt to log the user in
        // Passwordnya pake bcrypt
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            // if successful, then redirect to their intended location
            return redirect()->intended('/admin');
        } else if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])) {
            return redirect()->intended('/user');
        }
    }
    public function logout() {
        if (Auth::guard('admin')->check()) {
            Auth::guard('admin')->logout();
        } elseif (Auth::guard('user')->check()) {
            Auth::guard('user')->logout();
        }
        return redirect('/');
    }
}
  

Controller.php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
  

型号:Admin.php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable {
    use Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];

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

User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

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

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

Config / auth.php

return [

    /*
            |--------------------------------------------------------------------------
            | Authentication Defaults
            |--------------------------------------------------------------------------
            |
            | This option controls the default authentication "guard" and password
            | reset options for your application. You may change these defaults
            | as required, but they're a perfect start for most applications.
            |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
            |--------------------------------------------------------------------------
            | Authentication Guards
            |--------------------------------------------------------------------------
            |
            | Next, you may define every authentication guard for your application.
            | Of course, a great default configuration has been defined for you
            | here which uses session storage and the Eloquent user provider.
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | Supported: "session", "token"
            |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
        'admin-api' => [
            'driver' => 'token',
            'provider' => 'admin',
        ],
        'user' => [
            'driver' => 'session',
            'provider' => 'user',
        ],
        'user-api' => [
            'driver' => 'token',
            'provider' => 'user',
        ],
    ],

    /*
            |--------------------------------------------------------------------------
            | User Providers
            |--------------------------------------------------------------------------
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | If you have multiple user tables or models you may configure multiple
            | sources which represent each model / table. These sources may then
            | be assigned to any extra authentication guards you have defined.
            |
            | Supported: "database", "eloquent"
            |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
            |--------------------------------------------------------------------------
            | Resetting Passwords
            |--------------------------------------------------------------------------
            |
            | You may specify multiple password reset configurations if you have more
            | than one user table or model in the application and you want to have
            | separate password reset settings based on the specific user types.
            |
            | The expire time is the number of minutes that the reset token should be
            | considered valid. This security feature keeps tokens short-lived so
            | they have less time to be guessed. You may change this as needed.
            |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];
  

routes.php

Route::get('/', function () {
    return view('welcome');
});

// hanya untuk tamu yg belum auth
Route::get('/login', 'LoginController@getLogin')->middleware('guest');
Route::post('/login', 'LoginController@postLogin');
Route::get('/logout', 'LoginController@logout');;

Route::get('/admin', function() {
  return view('admin');
})->middleware('auth:admin');

Route::get('/user', function() {
  return view('user');
})->middleware('auth:user');
  

admin.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h2>Admin Page {{ Auth::guard('admin')->user()->name }}</h2>
  <br>
  <a href="/logout">Logout {{ Auth::guard('admin')->user()->name }} ??</a>
</body>
</html>
  

user.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h2>User Page.. halo {{Auth::guard('user')->user()->name}}</h2>
  <br>
  <a href="/logout">Logout {{ Auth::guard('user')->user()->name }} ??</a>
</body>
</html>
  

login.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <fieldset style="width:300px; margin:100px auto">
    <legend>Form Login</legend>
    <form action="/login" method="post">
      {{ csrf_field() }}
      <table>
        <tr>
          <td>Email</td>
          <td>:</td>
          <td><input type="text" name="email" id="email"></td>
        </tr>
        <tr>
          <td>Password</td>
          <td>:</td>
          <td><input type="password" name="password" id="password"></td>
        </tr>
      </table>
      <button type="submit">Login</button>
    </form>
  </fieldset>
</body>

</html>
  

redirectIfAuthenticated.php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
  /**
   * 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');
    } else if (Auth::guard('user')->check()) {
      return redirect('/user');

    }
    return $next($request);
  }
}
  

Authenticate.php

    namespace App\Http\Middleware;
    use Illuminate\Auth\Middleware\Authenticate as Middleware;
    use Illuminate\Support\Facades\Auth;
    class Authenticate extends Middleware
    {
      /**
       * Get the path the user should be redirected to when they are not authenticated.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return string
       */
      protected function redirectTo($request)
      {
        if (Auth::guard('admin')->check()) {
          return redirect('/admin');
        } else if (Auth::guard('user')->check()) {
          return redirect('/user');

        }
      }
    }
  

App / Exceptions / Handler.php

namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];
    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];
    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
    protected function unauthenticated($request, \Illuminate\Auth\AuthenticationException $exception)
    {
      if($request->expectsJson()){
        return response()->json(['error' => 'Unauthenticated.'], 401);
      }
      return redirect('/login');
    }
}

0 个答案:

没有答案