Laravel 5.4~5.5 다중 사용자인증

  • 작업 조건
    • PHP >= 5.6.4
    • OpenSSL PHP Extension
    • PDO PHP Extension
    • Mbstring PHP Extension
    • Tokenizer PHP Extension
    • XML PHP Extension
  • 작업 내용
    • Laravel 5.4에서 다중 사용자 인증 만들기
  • 작업 과정
    • 1. Laravel 5.4 project를 설치합니다.
      • composer create-project –prefer-dist laravel/laravel blog “5.4.*”
    • 2. admins migration table과 Model을 만듭니다.
      • <?php
        use Illuminate\Support\Facades\Schema;
        use Illuminate\Database\Schema\Blueprint;
        use Illuminate\Database\Migrations\Migration;
        class CreateAdminsTable extends Migration
        {
         /**
         * Run the migrations.
         *
         * @return void
         */
         public function up()
         {
         Schema::create('admins', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');
         $table->string('email')->unique();
         $table->string('job_title');
         $table->string('password');
         $table->rememberToken();
         $table->timestamps();
         });
         }
         /**
         * Reverse the migrations.
         *
         * @return void
         */
         public function down()
         {
         Schema::dropIfExists('admins');
         }
        }
        
      • <?php
        
        namespace App;
        
        use Illuminate\Notifications\Notifiable;
        use Illuminate\Foundation\Auth\User as Authenticatable;
        
        class Admin extends Authenticatable
        {
         use Notifiable;
        
         protected $guard = 'admin';
        
         /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
         protected $fillable = [
         'name', 'email', 'password', 'job_title',
         ];
        
         /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
         protected $hidden = [
         'password', 'remember_token',
         ];
        }
        
      • 3. App/Exceiptions/Handler.php 에 다음 코드를 복사합니다.
        <?php
        namespace App\Exceptions;
        use Exception;
        use Illuminate\Auth\AuthenticationException;
        use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
        class Handler extends ExceptionHandler
        {
         /**
         * A list of the exception types that should not be reported.
         *
         * @var array
         */
         protected $dontReport = [
         \Illuminate\Auth\AuthenticationException::class,
         \Illuminate\Auth\Access\AuthorizationException::class,
         \Symfony\Component\HttpKernel\Exception\HttpException::class,
         \Illuminate\Database\Eloquent\ModelNotFoundException::class,
         \Illuminate\Session\TokenMismatchException::class,
         \Illuminate\Validation\ValidationException::class,
         ];
         /**
         * Report or log an exception.
         *
         * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
         *
         * @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);
         }
         /**
         * Convert an authentication exception into an unauthenticated response.
         *
         * @param \Illuminate\Http\Request $request
         * @param \Illuminate\Auth\AuthenticationException $exception
         * @return \Illuminate\Http\Response
         */
         protected function unauthenticated($request, AuthenticationException $exception)
         {
         if ($request->expectsJson()) {
         return response()->json(['error' => 'Unauthenticated.'], 401);
         }
         $guard = array_get($exception->guards(), 0);
         switch ($guard) {
         case 'admin':
         $login = 'admin.login';
         break;
         default:
         $login = 'login';
         break;
         }
         return redirect()->guest(route($login));
         }
        }
        
      • 4. app/Http/Middleware/RedirectIfAuthenticated.php 으로 이동한 후 이 코드를 붙여넣습니다.
        <?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)
         {
         switch ($guard) {
         case 'admin':
         if (Auth::guard($guard)->check()) {
         return redirect()->route('admin.dashboard');
         }
         break;
         default:
         if (Auth::guard($guard)->check()) {
         return redirect('/home');
         }
         break;
         }
         return $next($request);
         }
        }
        
      • 5. Admin Controller를 만듭니다.
        <?php
        namespace App\Http\Controllers;
        use Illuminate\Http\Request;
        class AdminController extends Controller
        {
         /**
         * Create a new controller instance.
         *
         * @return void
         */
         public function __construct()
         {
         $this->middleware('auth:admin');
         }
         /**
         * Show the application dashboard.
         *
         * @return \Illuminate\Http\Response
         */
         public function index()
         {
         return view('admin');
         }
        }
        
      • 6. 다음 명령어를 실행합니다. php artisan make:controller auth/AdminLoginController
      • 또는 AdminLoginController/Http/ Controllers/Auth/AdminLoginController.php를 생성하고 이 코드를 붙여넣습니다.
        <?php
        namespace App\Http\Controllers\Auth;
        use Illuminate\Http\Request;
        use App\Http\Controllers\Controller;
        use Auth;
        class AdminLoginController extends Controller
        {
         public function __construct()
         {
         $this->middleware('guest:admin');
         }
         public function showLoginForm()
         {
         return view('auth.admin-login');
         }
         public function login(Request $request)
         {
         // Validate the form data
         $this->validate($request, [
         'email' => 'required|email',
         'password' => 'required|min:6'
         ]);
         // Attempt to log the user in
         if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
         // if successful, then redirect to their intended location
         return redirect()->intended(route('admin.dashboard'));
         }
         // if unsuccessful, then redirect back to the login with the form data
         return redirect()->back()->withInput($request->only('email', 'remember'));
         }
        }
        
      • 7. config/auth.php 파일에 이 코드를 붙여넣습니다.
        <?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' => 'admins',
         ],
         'admin-api' => [
         'driver' => 'token',
         'provider' => 'admins',
         ],
         ],
         /*
         |--------------------------------------------------------------------------
         | 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,
         ],
         'admins' => [
         '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,
         ],
         'admins' => [
         'provider' => 'admins',
         'table' => 'password_resets',
         'expire' => 15,
         ],
         ],
        ];
        
      • 8. Route file
        <?php
        /*
        |--------------------------------------------------------------------------
        | Web Routes
        |--------------------------------------------------------------------------
        |
        | Here is where you can register web routes for your application. These
        | routes are loaded by the RouteServiceProvider within a group which
        | contains the "web" middleware group. Now create something great!
        |
        */
        Route::get('/', function () {
         return view('welcome');
        });
        Auth::routes();
        Route::get('/home', 'HomeController@index');
         Route::prefix('admin')->group(function() {
         Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
         Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
         Route::get('/', 'AdminController@index')->name('admin.dashboard');
         });
        
      • 9. admin.blade.php를 home.blade.php와 동일하게 만듭니다.
        @extends('layouts.app')
        
        @section('content')
        <div class="container">
         <div class="row">
         <div class="col-md-8 col-md-offset-2">
         <div class="panel panel-default">
         <div class="panel-heading">ADMIN Dashboard</div>
        
         <div class="panel-body">
         You are logged in as <strong>ADMIN</strong>
         </div>
         </div>
         </div>
         </div>
        </div>
        @endsection
        

        10.views/auth/admin-login.blade.php를 만듭니다.

        @extends('layouts.app')
        
        @section('content')
        <div class="container">
        <div class="row">
        <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
        <div class="panel-heading">ADMIN Login</div>
        <div class="panel-body">
        
        {{ csrf_field() }}
        <div>has('email') ? ' has-error' : '' }}"&gt;
        E-Mail Address
        <div class="col-md-6">
        
        
        @if ($errors-&gt;has('email'))
        <span class="help-block">
        <strong>{{ $errors-&gt;first('email') }}</strong>
        </span>
        @endif
        </div>
        </div>
        <div>has('password') ? ' has-error' : '' }}"&gt;
        Password
        <div class="col-md-6">
        
        
        @if ($errors-&gt;has('password'))
        <span class="help-block">
        <strong>{{ $errors-&gt;first('password') }}</strong>
        </span>
        @endif
        </div>
        </div>
        <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
        <div class="checkbox">
        
         Remember Me
        
        </div>
        </div>
        </div>
        <div class="form-group">
        <div class="col-md-8 col-md-offset-4">
        
        Login
        
        
        <a class="btn btn-link" href="{{ route('password.request') }}">
        Forgot Your Password?
        </a>
        </div>
        </div>
        
        </div>
        </div>
        </div>
        </div>
        </div>
        @endsection
        
  • 작업 중 참고사항
  • 작업 중 발생한 문제 해결
  • 작업과 관련된 주제
  • 참고 문헌
Advertisements

글쓴이: Hong Jin-Seob

Developer

답글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Google+ photo

Google+의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Twitter 사진

Twitter의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

%s에 연결하는 중