Skip to content

Instantly share code, notes, and snippets.

@jeffreyvr
Last active December 2, 2020 20:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreyvr/444d34afd4bebdb49de1fcea438c7800 to your computer and use it in GitHub Desktop.
Save jeffreyvr/444d34afd4bebdb49de1fcea438c7800 to your computer and use it in GitHub Desktop.
Lumen Policies
<?php
namespace App\Providers;
use App\Post as Post;
use App\Policies\PostPolicy as PostPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
Gate::policy('App\Post', 'App\Policies\PostPolicy');
$this->app['auth']->viaRequest('api', function ($request) {
return app('auth')->setRequest($request)->user();
});
}
}
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Update the given blog post.
*
* @param Request $request
* @param int $id
* @return Response
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function update(Request $request, $id)
{
$post = Post::find($id);
$this->authorize('update', $post);
// The current user can update the blog post...
}
}
<?php
namespace App\Policies;
use App\User;
use App\Post;
class PostPolicy
{
/**
* Determine if a given user can delete
*
* @param User $user
* @param Post $post
* @return bool
*/
public function update(User $user, Post $post)
{
return $post->user_id === $user->id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment