Laravel 7:如何限制用户的URL?

发布于 2025-02-11 11:50:53 字数 310 浏览 2 评论 0原文

我是一个正在学习Laravel 7的新手。我已经开发了一个使用Laravel 7的小型Web应用程序。但是今天我注意到了一个问题。所有URL都是全局的,这意味着所有用户都可以访问我网站的所有URL。假设用户一个创建的数据,并在每个行中存在编辑和删除按钮的表中显示。编辑URL就像:localhost/Records/Records/Edit/5。问题是,其他登录的用户也可以访问此编辑页面。这样,所有登录的用户都可以访问所有URL,这非常糟糕。 我希望你明白我在说什么。我有将近250个以上的网络路线。有什么简单的限制路线的方法吗? 用户只能访问自己的数据。我该怎么做? 谢谢

I'm a newbie who is learning Laravel 7. I have developed a small web application with Laravel 7. But today I noticed one problem. That all the URLs are global, means all users can access all the URLs of my website. Suppose User A created data and it shows in a table where the edit and delete buttons exist with every row. The edit URL is like: localhost/records/edit/5. The problem is, that other logged-in users can access this edit page also. Like this, all the URLs are accessible by any logged-in users which is very bad.
I hope you understand what I'm saying. I have almost 250+ web routes. Is there any easy way to restrict the routes?
User can access their own data only. How can I do that?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

⒈起吃苦の倖褔 2025-02-18 11:50:54

您必须注册策略,并确保未经正确的授权,用户无法访问网站的一部分。

请参阅 docs 关于如何制定政策和实施它们。

示例代码:

策略:

class RecordPolicy 
{
    public function delete(User $user, Record $record)
    {
        return $user->id === $record->user_id;
    }
}

控制器

class RecordController
{
    public function destroy(Record $record)
    {
        // Authorize the delete action before actually deleting the record
        $this->authorize('delete', $record);

        $record->delete();
    }
}

记录索引

@foreach($records as $record)
    <div> 
        {{ $record->name }}

        {{-- Only show delete button if the authorized user can actually delete the record --}}
        @can('delete', $record)
            <form action="{{ route('records.destroy', compact('record') }}" method="POST">
                @csrf
                @method('DELETE')
                <button type="submit">Delete record</button>
            </form>
        @endcan
    </div>
@endforeach

You'll have to register policies and ensure users cannot access parts of the website without the correct authorization.

See the docs on how to write policies and implement them.

Sample code:

Policy:

class RecordPolicy 
{
    public function delete(User $user, Record $record)
    {
        return $user->id === $record->user_id;
    }
}

Controller

class RecordController
{
    public function destroy(Record $record)
    {
        // Authorize the delete action before actually deleting the record
        $this->authorize('delete', $record);

        $record->delete();
    }
}

Records index

@foreach($records as $record)
    <div> 
        {{ $record->name }}

        {{-- Only show delete button if the authorized user can actually delete the record --}}
        @can('delete', $record)
            <form action="{{ route('records.destroy', compact('record') }}" method="POST">
                @csrf
                @method('DELETE')
                <button type="submit">Delete record</button>
            </form>
        @endcan
    </div>
@endforeach
二智少女猫性小仙女 2025-02-18 11:50:54
  1. 添加新记录&gt;添加create_by
  2. 在用户运行URL&gt; gt; gt; gt; gt; gt;从会话中获取登录的用户user_id,然后在数据库中检查其记录&gt;如果找不到记录,则将消息重定向到主页,否则会继续。
  1. store user_id when new record added > Add created_by field in user_table DB
  2. when user run URL > get logged-in user user_id from session and check in DB for their record > if record not found then redirect to home page with message otherwise continue.
楠木可依 2025-02-18 11:50:54

如果我正确理解您,您想将路由限制为特定用户。

  1. 创建角色表
Columns (id, name) 

(1 = Super Admin, 2 = Admin, 3 = User)
  1. 在创建新用户时为用户分配角色
    IE将角色_ID添加到用户表中。
$user = User::create([
  'name' => 'First Admin',
  'email' => '[email protected]',
  'password' => Hash::make('Admin@1234'),
  'role_id'  => 2 // For admin role
]);
  1. 然后为每个角色创建中间Wares,并为特定用户限制路线。

管理中间件:adminmiddleware.php

public function handle(Request $request, Closure $next)
    {
        $allowedRoles = [2];
        if (!in_array(Auth::user()->role_id, $allowedRoles))
            {
                return redirect()->back()->with('error',__('Sorry, you are not authorized to access that location.'));
            }
        return $next($request);
    }

in kernel.php

'admin' => \App\Http\Middleware\AdminMiddleware::class,
Route::group(['middleware' => 'admin'], function(){
   // All admin Routes
});

您也可以使用spatie软件包

。 /middleware“ rel =” nofollow noreferrer“> https://spatie.be/docs/laravel-permission/v5/basic-usage/middleware

只需检查角色是否允许使用该路线:

Route::group(['middleware' => ['auth', 'role:admin']], function () {
    // All routes available for admin
});

If i understand you correctly you want to restrict routes to specific user.

  1. Create a roles table
Columns (id, name) 

(1 = Super Admin, 2 = Admin, 3 = User)
  1. Assign Roles To User While Creating new User
    i.e add role_id to users table.
$user = User::create([
  'name' => 'First Admin',
  'email' => '[email protected]',
  'password' => Hash::make('Admin@1234'),
  'role_id'  => 2 // For admin role
]);
  1. Then Create Middlewares for each role and restrict routes for specific users.

Admin Middleware: AdminMiddleware.php

public function handle(Request $request, Closure $next)
    {
        $allowedRoles = [2];
        if (!in_array(Auth::user()->role_id, $allowedRoles))
            {
                return redirect()->back()->with('error',__('Sorry, you are not authorized to access that location.'));
            }
        return $next($request);
    }

In Kernel.php

'admin' => \App\Http\Middleware\AdminMiddleware::class,
Route::group(['middleware' => 'admin'], function(){
   // All admin Routes
});

You Can also Use Spatie package for this.

https://spatie.be/docs/laravel-permission/v5/basic-usage/middleware

Just Check If Role is allowed to use that route:

Route::group(['middleware' => ['auth', 'role:admin']], function () {
    // All routes available for admin
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文