Last active
November 28, 2017 06:37
-
-
Save cyberfly/257e29e7d08ead819446df1581fcc026 to your computer and use it in GitHub Desktop.
Laravel middleware check Object Ownership
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| protected $routeMiddleware = [ | |
| 'check_user_role' => \App\Http\Middleware\CheckUserRole::class, | |
| 'check_product_ownership' => \App\Http\Middleware\CheckProductOwnership::class, | |
| ]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Middleware; | |
| use Closure; | |
| use App\Product; | |
| class CheckProductOwnership | |
| { | |
| /** | |
| * Handle an incoming request. | |
| * | |
| * @param \Illuminate\Http\Request $request | |
| * @param \Closure $next | |
| * @return mixed | |
| */ | |
| public function handle($request, Closure $next) | |
| { | |
| //dapatkan product id dari url | |
| $product_id = $request->product; | |
| //dapatkan product info based on product_id | |
| $product = Product::find($product_id); | |
| if ($product) { | |
| //dapatkan user_id untuk product tersebut | |
| $product_owner = $product->user_id; | |
| //dapatkan current logged in user id | |
| $current_user_id = auth()->id(); | |
| //check jika current user yang cuba akses, tak sama dengan product owner | |
| if ($current_user_id!=$product_owner) { | |
| dd("You are not allowed"); | |
| } | |
| } | |
| return $next($request); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Controllers; | |
| use Illuminate\Http\Request; | |
| class ProductsController extends Controller | |
| { | |
| public function __construct(){ | |
| //check product ownership | |
| $this->middleware('check_product_ownership')->only('edit','destroy','update'); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment