Skip to content

Commit

Permalink
授权访问
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Sep 19, 2019
1 parent 081e376 commit 4cf779f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
7 changes: 7 additions & 0 deletions app/Http/Controllers/UsersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,25 @@

class UsersController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => ['show']]);
}

public function show(User $user)
{
return view('users.show', compact('user'));
}

public function edit(User $user)
{
$this->authorize('update', $user);
return view('users.edit', compact('user'));
}

public function update(UserRequest $request, ImageUploadHandler $uploader, User $user)
{
$this->authorize('update', $user);
$data = $request->all();

if ($request->avatar) {
Expand Down
16 changes: 16 additions & 0 deletions app/Policies/UserPolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
use HandlesAuthorization;

public function update(User $currentUser, User $user)
{
return $currentUser->id === $user->id;
}
}
6 changes: 5 additions & 1 deletion app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ public function boot()
{
$this->registerPolicies();

//
// 修改策略自动发现的逻辑
Gate::guessPolicyNamesUsing(function ($modelClass) {
// 动态返回模型对应的策略名称,如:// 'App\Model\User' => 'App\Policies\UserPolicy',
return 'App\Policies\\'.class_basename($modelClass).'Policy';
});
}
}

0 comments on commit 4cf779f

Please sign in to comment.