这次我有这样的Url http://Blog/user/profile/51 我登录了一个用户,其id = 51,但如果我将这个id更改为50,它显示了用户id为50的数据的形式,我想阻止这种情况,我如何保护帮助。如何在执行othere
之前检查此条件?public function profile($id, Request $request)
{
***if($id == Auth::user()->id){
Now Check get or post method
}else{
return ('Out');
}***
$method = $request->method();
if ($request->isMethod('get')) {
$user = User::findOrFail($id);
$users = DB::table('users')->select('id', 'name')->get();
$user_fields = DB::table('users')->where('id', $user->id)->get();
$page_data = [
'title' => 'Edit User Account',
'action' => 'edit'
];
return view('user.profile')->with(compact('user', 'page_data', 'users'));
}else{
$this->validate($request, [
'name' => 'required|max:255',
]);
$user = User::findOrFail($id);
$input = $request->all();
$user->fill([
'name' => $request->input('name'),
'password' => $request->password ? bcrypt($request->input('password')) : $user->password,
'time_zone' => $request->input('time_zone'),
'address_line_1' => $request->input('address_line_1'),
'address_line_2' => $request->input('address_line_2'),
])->save();
session()->flash('msg',trans('successfully Updated.'));
}
我有想法,我可以检查auth用户id等于这个id,但不知道如何实现,我在这里把url作为
<form action="/user/profile/{{$user->id}}" method="POST">
,这里我用auth user id作为
<a href="{{ route('user.profile', ['id' => Auth::user()->id ]) }}">
路由如下
Route::any('/user/profile/{id}', ['as' => 'user.profile', 'uses' => 'UserController@profile']);
现在我如何在向用户显示表单之前检查它是否相关由于
如果您想使用户配置文件私有,您不应该将其绑定到GET
参数(仅对公共配置文件页面这样做)。你应该做的是将配置文件路由放入auth
中间件组:
Route::group(['middleware' => 'auth'], function () {
Route::get('profile', 'UserController@showProfile');
}
并使用auth()->user()
对象获取数据显示:
{{ auth()->user()->name }}
{{ auth()->user()->email }}
Laravel中间件
(文档)中间件将帮助您,它将允许您检查请求url的用户是否与存储在其会话中的id相同。如果他们匹配,他是配置文件的"所有者",如果不是,你可以重定向他并提供一个错误消息。
创建中间件 (App'Http'Middleware'IsOwnerOfProfile.php)
<?php
namespace App'Http'Middleware;
use Closure;
class IsOwnerOfProfile {
/**
* Check if the user accessing the profile is the owner of the profile
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next){
if ($request->id != auth()->user()->id) {
return redirect('home')->with('error','You are not the owner of this profile');
}
return $next($request);
}
}
注册中间件 (App'Http'Kernel.php)
protected $routeMiddleware = [
// other defined middlewares
'profileOwner' => 'App'Http'Middleware'IsOwnerOfProfile::class,
]
更新路由
Route::any('/user/profile/{id}', [
'middleware' => 'profileOwner'
'as' => 'user.profile',
'uses' => 'UserController@profile'
]);
注意,更新:正如@Alexey Mezenin所提到的,auth
中间件需要在此之前执行。否则,您将无法访问auth()->user()
,并且中间件将抛出异常。