티스토리 뷰

Laravel 5.1.11 release에 이르러 새 인증 기능들을 제공하게 되었다. 바로 뛰어들어보자.
우린 이미 라라벨에서 Authentication 기능들에 대해 알고 있다. 종니좋군, 하지만 in many applications just a start in handling your users. 우린 항상 몇가지 다른 권한을 필요로 한다. 누가 이 의견을 업데이트 해도 되는가? 또는 누구에게 모든 권한을 부여해도 되는가? 이런 질문들의 답이 여기에 있다.
기능들 설정
Laravel의 새로운 Illuminate\Auth\Access\Gate 클래스는 설정을 다루고 검사하고, 그렇게 불리는, 능력들이 있다. Laravel의 AuthServiceProvider 는 그런 능력들을 정의하는곳에 권장된다. 우리 사례에서는 우리의 의견들을 보호하는데 쓴다.

// Inside AuthServiceProvider
// ...

public function boot(GateContract $gate)
{
    parent::registerPolicies($gate);

    $gate->define('update-comment', function ($user, $comment) {
        return $user->id === $comment->user_id;
    });
}
우린 boot 메쏘드 내에서 update-comment 기능을 정의한다. 우린 사용자가 그들이 속한 의견만 업데이트 하기를 바란다. 이것이 우리가 검사해야할 것이다.
주: 또한 다음과 같이 클래스와 함수를 'Class@method’ 클로저 대신 인자로 설정이 가능하다.
Gate 퍼사드(facade)를 통해 기능 검사
이제 권한 설정을 해보자, 우린 의견 업데이트 전에 검사하길 원한다.

// inside the CommentController
// ...

public function update($id)
{
    $comment = comment::findOrFail($id);
   
    if (Gate::denies('update-comment', $comment)) {
        abort(403);
    }

    // Update Comment...
}
주: user object를 denies 메쏘드에 전달할 필요는 없다. Gate 퍼사드가 인증된 user를 자동적으로 취득할 것이다.
반대의 Gate 메쏘드인 allows 도 가능하다.
if (Gate::allows('update-comment', $comment)) {
    // Update Comment...
}


모델 instance를 통해 기능 검사
물론 update-comment 권한 검사에 다른 방법이 존재한다. 이번엔 user instance와 새로운 can 또는 cannot 메쏘드들을 사용할 것이다.

// Inside the CommentController
// ...

if ($request->user()->cannot('update-comment', $comment)) {
    abort(403);
}
둘은 동일한 처리를 달성하므로 어떤 방법을 제공할지는 당신에게 달렸다.
항상 최고관리자는 존재한다

I guess in every application there is a super admin with super powers. Of course he or she shouldn't be hindered by our Gate. For this case Laravel provides an additional before method. Just place it inside the AuthServiceProvider again. Now we just need to provide the information if this user should have all rights. In this case it is a method, but it also could be a database field or something else. This is totally up to you.


$gate->before(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});
Blade에서의 사용법
아직 부족한가? 옛다 더 있다. 이 기능들도 Blade에서 역시 가능하다. 이것은 우리가 사용자의 권한에 기반한 무언가를 보여줄때 유용하다. 우리 사례에서 내게 속한 의견에 대한 수정링크를 보여주기 원한다. 보자!
// Inside a blade template file
// ...

@can('update-comment', $comment)
    <a href="/comment/{{ $comment->id }}/edit">Edit Comment</a> 
@endcan


결론
Laravel 5.1.11 는 작은 공개지만 여전히 프레임웍에 새 접근제어목록(ACL: Access Control List) 기능들과 같은 강력한것들을 제공한다. 여기서 더 알아보고 만지고 다뤄보자.


댓글