主页/PHP笔记/PHP问答/框架Laravel/Laravel:如何在 Blade 模板中验证权限

Laravel:如何在 Blade 模板中验证权限

Bug编译狮

Bug编译狮

在 Laravel 中,你可以使用 Auth facade 来验证用户是否具有特定的权限。以下是一个示例,展示了如何在 Blade 模板中验证权限:

  1. 安装和配置 Laravel: 如果你还没有安装 Laravel,可以使用 Composer 进行安装:

    composer create-project --prefer-dist laravel/laravel my-laravel-app
    cd my-laravel-app
  2. 创建控制器: 创建一个新的控制器来处理权限验证逻辑:

    php artisan make:controller PermissionsController
  3. 定义路由: 在 routes/web.php 文件中添加路由:

    use AppHttpControllersPermissionsController;
    
    Route::get('/dashboard', [PermissionsController::class, 'index'])->middleware(['auth', 'permission:view-dashboard']);
  4. 创建控制器方法: 在 app/Http/Controllers/PermissionsController.php 文件中添加 index 方法,并使用 can 方法来验证权限:

    namespace AppHttpControllers;
    
    use IlluminateSupportFacadesAuth;
    use IlluminateHttpRequest;
    
    class PermissionsController extends Controller
    {
       public function index()
       {
           if (Auth::check() && Auth::user()->can('view-dashboard')) {
               return view('dashboard');
           } else {
               return redirect()->route('login');
           }
       }
    }
  5. 创建 Blade 模板: 创建一个名为 dashboard.blade.php 的视图文件并在其中显示一些内容:

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Dashboard</title>
    </head>
    <body>
       <h1>Welcome to the Dashboard!</h1>
       <!-- Your dashboard content here -->
    </body>
    </html>
  6. 确保权限存在: 确保你在 app/Providers/AuthServiceProvider.php 文件中的 boot 方法中注册了权限:

    protected function boot()
    {
       $this->registerPolicies();
    
       Gate::define('view-dashboard', function ($user) {
           // 自定义权限逻辑
           return $user->hasRole('admin') || $user->hasPermission('view-dashboard');
       });
    }

通过以上步骤,你可以在 Laravel 中使用 Auth facade 和 Gate 类来验证用户是否具有特定的权限。如果用户没有权限,他们将被重定向到登录页面。

黑板Bug讲师

黑板Bug讲师

介绍

在构建Web应用程序时,有效管理用户权限至关重要,以确保每个用户只能查看或操作与其权限相匹配的内容。Laravel,一个强大的PHP框架,提供了多种处理授权的方式。在Blade模板引擎中,Laravel的模板系统允许根据用户的权限条件显示元素。

本教程将指导您通过Blade模板中的权限验证过程,从基本示例到高级使用。我们将涵盖内置的指令、使用策略以及一些可以帮助您高效管理权限的最佳实践。让我们开始吧。

理解Laravel中的授权(Authorization)

Laravel 提供了两种主要的授权处理方式:门和策略。门是闭包,用于确定用户是否被授权执行特定的操作;而策略则是围绕特定模型或资源组织授权逻辑的类。

定义门和政策

// Example of defining a gate in AuthServiceProvider
Gate::define('edit-post', function ($user, $post) {
    return $user->id === $post->user_id;
});

// Example of a policy method
public function update(User $user, Post $post)
{
    return $user->id === $post->user_id;
}

基本权限验证示例

让我们从Blade模板中的授权基本操作开始。

使用@can指令。

<!-- Check if a user can edit a post within a Blade template -->
@can('edit-post', $post)
    <button>Edit Post</button>
@endcan

上述代码仅在签署的用户有权编辑指定帖子时显示“编辑帖子”按钮。@can方向指令接受两个参数:能力和相关模型。

使用@cannot指令

<!-- Opposite of @can. If a user cannot edit a post, show a message -->
@cannot('edit-post', $post)
    <p>You do not have permission to edit this post.</p>
@endcannot

对不起,我不能理解这句话。@cannot函数的作用与指令相反。@can当用户没有权限执行操作时,显示内容。

早期使用权限验证

在Blade中,inline policies(即inline策略)是指嵌入到对象中的策略定义。这些策略可以在创建对象时立即应用,而不是在对象实例化后通过setter方法来设置。这可以提高性能,因为不需要额外的调用以设置属性。 inline policies通常用于需要快速响应变化的应用程序或系统中。例如,在数据库操作中,一个简单的inline policy可能只是更新一条记录,而无需重新查询整个表。

虽然您可以在政策类中为每个操作定义单独的方法,但也可以在 Blade 文件中直接编写内联策略,使用相同的语法。@canand 是中文里表示“并且”的意思,没有特殊含义。@cannot指令。

根据权限显示不同的内容。

<!-- Using @can and @else to show different content -->
@can('edit-post', $post)
    <button>Edit Post</button>
@else
    <p>Only the author can edit this post.</p>
@endcan

在这种场景下,用户如果可以编辑帖子,则会看到一个“编辑帖子”按钮;否则,会显示一条消息。

正在检查多个权限。

在某些情况下,你需要同时检查多个权限。Laravel在这方面做得非常简单。

使用 @can 直接标

@canany(['publish-post', 'unpublish-post'], $post)
    <button>Publish/Unpublish Post</button>
@elsecan('edit-post', $post)
    <button>Edit Post</button>
@else
    <p>You cannot manage this post.</p>
@endcanany

对不起,您的问题不明确。请提供更多的信息或澄清一下。@canany该指令将在用户具备指定能力之一时渲染按钮。

结论。

授权在 Laravel 的 Blade 模板中非常强大且灵活。使用诸如@can好的,请提供需要翻译的内容。@cannot和我有什么事吗?@canany您可以通过调整用户在应用程序模板中的可见性和可操作性来微调您的应用。按照本指南中的实践,您将能够构建一个安全且用户友好的应用程序。

长工码奴1523

长工码奴1523

Laravel 是一个非常流行的 PHP 开发框架,它提供了强大的功能来管理数据库和与之交互。其中,验证权限是 Laravel 提供的一个重要特性,可以帮助您确保只有授权的用户才能访问特定的资源。

要使用 Laravel 的权限系统进行验证,您可以按照以下步骤操作:

1. 配置权限

首先,需要创建一个新的权限模型。这将用于存储用户的权限信息。例如,假设我们有一个名为 User 的模型,我们需要为该模型添加一些权限字段:

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];

    public function permissions()
    {
        return $this->belongsToMany('AppPermission');
    }
}

2. 在 Blade 模板中验证权限

要在 Blade 模板中验证权限,只需在相应的视图文件(如 users/show.blade.php)中加入权限验证逻辑即可。这里展示一个简单的例子:

@if(Auth::user()->can('view-users'))
    <h2>{{ Auth::user()->name }}'s Profile</h2>
@endif

在这个例子中,如果当前用户具有“查看用户”权限,则显示用户名;否则,跳转到登录页面。

3. 使用 Laravel 命令行工具验证权限

除了在模板中验证权限外,还可以通过 Laravel 命令行工具(如 laravel newlaravel new --force) 来验证权限。具体来说,可以使用 make:auth 命令创建新的权限验证控制器。

$ make:auth
Creating the auth controller in /path/to/your/app/controllers/AuthController.php

You can now use this class to create and manage your users, roles, and permissions.

然后,根据实际情况在 AuthController.php 中添加相应的验证方法:

namespace AppHttpControllersAuth;

use IlluminateSupportFacadesRoute;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateHttpRequest;

class AuthController extends Controller
{
    /*
     * Show the application login page.
     */
    public function showLoginForm(Request $request)
    {
        return view('auth.login');
    }

    /*
     * Handle a login attempt.
     *
     * @param IlluminateHttpRequest $request
     * @return mixed
     */
    public function authenticate(Request $request)
    {
        if ($request->input('remember') === null) {
            // If remember is not set, clear the session
            $request->session()->forget('_token');
        }

        return Authenticator::authenticate($request);
    }
}

// Authenticator.php
use IlluminateContractsAuthGuard;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;

class Authenticator implements MustVerifyEmail
{
    /**
     * Get the user model responsible for performing password resets.
     *
     * @return string
     */
    public static function model()
    {
        return Authenticatable::model();
    }

    /**
     * Validate and authenticate a given credentials.
     *
     * @param IlluminateHttpRequest $request
     * @return bool|IlluminateContractsAuthAccessGate|mixed
     */
    public static function authenticate(Guard $guard, Request $request)
    {
        try {
            $credentials = $request->only($guard->getUsername() . '.email', $guard->getUsername() . '.password');

            $user = $guard->attempt($credentials);

            if (is_null($user)) {
                throw new Exception("Sorry, that account doesn't exist.");
            }

            if (!$user instanceof Authenticatable) {
                throw new Exception("That was an unexpected error.");
            }

            return $user;
        } catch (Exception $e) {
            return false;
        }
    }
}

这样,您就可以在 Laravel 的各个组件中轻松地使用权限验证了。希望这个指南对您有所帮助!