그냥 사는 이야기

Laravel 5.3 Sentinel - Visitors & Manager 본문

Development/Web

Laravel 5.3 Sentinel - Visitors & Manager

없다캐라 2020. 1. 21. 11:10
반응형

Visitor 권한

우선 VisitorMiddleware를 만든다.

php artisan make:middleware VisitorsMiddleware
routes/web.php
Route::group(['middleware' => 'visitors'], function() {
    Route::get('/register', 'RegistrationController@register');
    Route::post('/register', 'RegistrationController@postRegister');

    Route::get('/login', 'LoginController@login');
    Route::post('/login', 'LoginController@postLogin');
});

visitor가 접근 할 수 있는 register, login 경로는 visitor middleware group로 묶는다.

App/Http/Kernel.php
...
'visitors' => \App\Http\Middleware\VisitorsMiddleware::class,
App/Http/Middleware/VisitorsMiddleware
use Sentinel;
...
public function handle($request, Closure $next)
{
    if(!Sentinel::check())
        return $next($request);

    return redirect('/');
}

earnings view

resources/views/admins/earnings.blade.php
Total earnings 9999

<form action="/logout" method="POST" id="logout-form">
    {{ csrf_field() }}
    <a href="#" onclick="document.getElementById('logout-form').submit()">Logout</a>
</form>
App/Http/Controllers/AdminController
public function earnings()
{
    return view('admins.earnings');
}

Manager 권한

php artisan make:middleware ManagerMiddleware
App/Http/Kernel.php
...
'manager' => \App\Http\Middleware\ManagerMiddleware::class,
App/Http/Middleware/ManagerMiddleware
use Sentinel;
...
public function handle($request, Closure $next)
{
    if (Sentinel::check() && Sentinel::getUser()->roles()->first()->slug == 'manager') {
        // \Log::info('role', ['role' => Sentinel::getUser()->roles()->first()]);
        return $next($request);
    }
    else
        return redirect('/');
}
routes/web.php
...
Route::get('tasks', 'ManagerController@tasks')->middleware('manager');
App/Http/Controllers/ManagerController
public function earnings()
{
    return view('managers.tasks');
}

로그인 시 권한에 맞는 페이지 redirect

LoginController
public function postLogin(Request $request)
{
    Sentinel::authenticate($request->all());

    $slug = Sentinel::getUser()->roles()->first()->slug;

    if ($slug =='admin')
        return redirect('/earnings');
    elseif ($slug =='manager')
        return redirect('/tasks');

    return Sentinel::check();
}
Comments