feat(auth): implement role-based access control using spatie/laravel-permission

Integrate Spatie Laravel Permission to replace the legacy role system.
This includes:
- Adding `spatie/laravel-permission` dependency.
- Implementing `Role` and `User` model updates with `HasRoles` trait.
- Adding migrations for permission and role tables.
- Creating `RoleResource` and `UserResource` for Filament administration.
- Adding a `RoleAndPermissionSeeder` for initial setup.
- Updating `User` model helper methods to utilize role checks.
This commit is contained in:
Kazem Alghasi 2026-08-10 02:44:23 +03:30
parent 8ca92f3a05
commit a0bc871c8d
15 changed files with 1154 additions and 31 deletions

View File

@ -0,0 +1,162 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\RoleResource\Pages;
use App\Models\Role;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;
class RoleResource extends Resource
{
protected static ?string $model = Role::class;
protected static ?string $navigationIcon = 'heroicon-o-shield-check';
protected static ?string $navigationLabel = 'نقش‌ها';
protected static ?string $modelLabel = 'نقش';
protected static ?string $pluralModelLabel = 'نقش‌ها';
protected static ?string $navigationGroup = 'تنظیمات سیستم';
protected static ?int $navigationSort = 2;
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('اطلاعات نقش')
->schema([
Forms\Components\TextInput::make('name')
->label('نام نقش (انگلیسی)')
->required()
->unique(ignoreRecord: true)
->maxLength(255),
Forms\Components\Select::make('guard_name')
->label('نوع Guard')
->options([
'web' => 'Web',
'api' => 'API',
])
->default('web')
->required(),
])->columns(2),
Forms\Components\Section::make('دسترسی‌ها')
->schema([
Forms\Components\CheckboxList::make('permissions')
->label('دسترسی‌های این نقش')
->relationship('permissions', 'name')
->columns(3)
->bulkToggleable(),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id')
->label('شناسه')
->sortable(),
Tables\Columns\TextColumn::make('name')
->label('نام')
->searchable()
->sortable()
->badge()
->color(fn (string $state): string => match ($state) {
'super_admin' => 'danger',
'admin' => 'warning',
'staff' => 'info',
'customer' => 'success',
default => 'gray',
}),
Tables\Columns\TextColumn::make('guard_name')
->label('Guard')
->badge()
->color('gray'),
Tables\Columns\TextColumn::make('users_count')
->label('تعداد کاربران')
->counts('users')
->badge()
->color('info'),
Tables\Columns\TextColumn::make('permissions_count')
->label('تعداد دسترسی‌ها')
->counts('permissions')
->badge()
->color('success'),
Tables\Columns\TextColumn::make('created_at')
->label('تاریخ ایجاد')
->dateTime('Y/m/d')
->sortable(),
])
->filters([])
->actions([
Tables\Actions\EditAction::make()->label('ویرایش'),
Tables\Actions\DeleteAction::make()->label('حذف'),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
])
->defaultSort('created_at', 'desc');
}
public static function getRelations(): array
{
return [];
}
public static function getPages(): array
{
return [
'index' => Pages\ListRoles::route('/'),
'create' => Pages\CreateRole::route('/create'),
'edit' => Pages\EditRole::route('/{record}/edit'),
];
}
// ... بقیه کد فعلی (form, table, getPages) ...
// ─── Access Control (فقط super_admin) ───
protected static function getCurrentUser(): ?\App\Models\User
{
$user = Auth::user();
return $user instanceof \App\Models\User ? $user : null;
}
public static function canViewAny(): bool
{
$user = static::getCurrentUser();
return $user !== null && $user->hasRole('super_admin');
}
public static function canCreate(): bool
{
return static::canViewAny();
}
public static function canEdit($record): bool
{
return static::canViewAny();
}
public static function canDelete($record): bool
{
// جلوگیری از حذف نقش super_admin حتی توسط super_admin
if ($record->name === 'super_admin') {
return false;
}
return static::canViewAny();
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Resources\Pages\CreateRecord;
class CreateRole extends CreateRecord
{
protected static string $resource = RoleResource::class;
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditRole extends EditRecord
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListRoles extends ListRecords
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@ -0,0 +1,270 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static ?string $navigationIcon = 'heroicon-o-users';
protected static ?string $navigationLabel = 'کاربران';
protected static ?string $modelLabel = 'کاربر';
protected static ?string $pluralModelLabel = 'کاربران';
protected static ?string $navigationGroup = 'تنظیمات سیستم';
protected static ?int $navigationSort = 1;
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('اطلاعات اصلی')
->schema([
Forms\Components\TextInput::make('name')
->label('نام و نام خانوادگی')
->required()
->maxLength(255),
Forms\Components\TextInput::make('email')
->label('ایمیل')
->email()
->required()
->unique(ignoreRecord: true)
->maxLength(255),
Forms\Components\TextInput::make('phone')
->label('شماره موبایل')
->tel()
->maxLength(20),
Forms\Components\TextInput::make('password')
->label('رمز عبور')
->password()
->revealable()
->required(fn (string $operation): bool => $operation === 'create')
->dehydrated(fn ($state): bool => filled($state))
->dehydrateStateUsing(fn ($state): string => Hash::make($state))
->helperText('برای تغییر رمز عبور، رمز جدید را وارد کنید. در غیر این صورت خالی بگذارید.'),
])->columns(2),
Forms\Components\Section::make('نقش و دسترسی‌ها')
->schema([
Forms\Components\Select::make('roles')
->label('نقش‌های کاربر')
->relationship('roles', 'name')
->multiple()
->preload()
->searchable()
->required()
->minItems(1)
->helperText('حداقل یک نقش باید انتخاب شود'),
Forms\Components\Toggle::make('is_active')
->label('وضعیت فعال')
->default(true)
->helperText('کاربران غیرفعال نمی‌توانند وارد سیستم شوند'),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id')
->label('شناسه')
->sortable()
->searchable()
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('name')
->label('نام')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('email')
->label('ایمیل')
->searchable()
->sortable()
->copyable()
->copyMessage('ایمیل کپی شد')
->copyMessageDuration(1500),
Tables\Columns\TextColumn::make('phone')
->label('موبایل')
->searchable()
->toggleable(),
Tables\Columns\TextColumn::make('roles.name')
->label('نقش‌ها')
->badge()
->color(fn (string $state): string => match ($state) {
'super_admin' => 'danger',
'admin' => 'warning',
'staff' => 'info',
'customer' => 'success',
default => 'gray',
})
->separator('، '),
Tables\Columns\IconColumn::make('is_active')
->label('فعال')
->boolean()
->sortable()
->trueIcon('heroicon-o-check-circle')
->falseIcon('heroicon-o-x-circle')
->trueColor('success')
->falseColor('danger'),
Tables\Columns\TextColumn::make('created_at')
->label('تاریخ عضویت')
->dateTime('Y/m/d')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
Tables\Filters\SelectFilter::make('role')
->label('نقش')
->options([
'super_admin' => 'مدیر ارشد',
'admin' => 'مدیر',
'staff' => 'کارمند',
'customer' => 'مشتری',
])
->query(function ($query, array $data) {
return $query->when($data['value'], function ($query, $role) {
return $query->role($role);
});
}),
Tables\Filters\TernaryFilter::make('is_active')
->label('وضعیت فعال'),
])
->actions([
Tables\Actions\EditAction::make()
->label('ویرایش'),
Action::make('toggleActive')
->label(fn ($record) => $record->is_active ? 'غیرفعال کردن' : 'فعال کردن')
->icon(fn ($record) => $record->is_active ? 'heroicon-o-x-circle' : 'heroicon-o-check-circle')
->color(fn ($record) => $record->is_active ? 'danger' : 'success')
->requiresConfirmation()
->action(function (User $record) {
$record->update(['is_active' => !$record->is_active]);
Notification::make()
->title($record->is_active ? 'کاربر فعال شد' : 'کاربر غیرفعال شد')
->success()
->send();
}),
Action::make('resetPassword')
->label('بازنشانی رمز')
->icon('heroicon-o-key')
->color('warning')
->form([
Forms\Components\TextInput::make('password')
->label('رمز عبور جدید')
->password()
->revealable()
->required()
->minLength(8),
])
->requiresConfirmation()
->action(function (User $record, array $data) {
$record->update([
'password' => Hash::make($data['password']),
]);
Notification::make()
->title('رمز عبور با موفقیت بازنشانی شد')
->success()
->send();
}),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make()
->label('حذف انتخاب‌شده‌ها'),
]),
])
->defaultSort('created_at', 'desc');
}
public static function getRelations(): array
{
return [];
}
public static function getPages(): array
{
return [
'index' => Pages\ListUsers::route('/'),
'create' => Pages\CreateUser::route('/create'),
'edit' => Pages\EditUser::route('/{record}/edit'),
];
}
// ─── Access Control ───
protected static function getCurrentUser(): ?\App\Models\User
{
$user = Auth::user();
return $user instanceof \App\Models\User ? $user : null;
}
// فقط super_admin و admin می‌توانند کاربران را ببینند
public static function canViewAny(): bool
{
$user = static::getCurrentUser();
return $user !== null && $user->hasAnyRole(['super_admin', 'admin']);
}
// فقط super_admin می‌تواند کاربر جدید بسازد
public static function canCreate(): bool
{
$user = static::getCurrentUser();
return $user !== null && $user->hasRole('super_admin');
}
// super_admin و admin می‌توانند ویرایش کنند
public static function canEdit($record): bool
{
$user = static::getCurrentUser();
if ($user === null) return false;
// admin نمی‌تواند super_admin را ویرایش کند
if ($user->hasRole('admin') && $record->hasRole('super_admin')) {
return false;
}
return $user->hasAnyRole(['super_admin', 'admin']);
}
// فقط super_admin می‌تواند کاربر حذف کند
public static function canDelete($record): bool
{
$user = static::getCurrentUser();
if ($user === null) return false;
// super_admin نمی‌تواند خودش را حذف کند
if ($record->id === $user->id) {
return false;
}
return $user->hasRole('super_admin');
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditUser extends EditRecord
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListUsers extends ListRecords
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Spatie\Permission\Models\Role as SpatieRole;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Role extends SpatieRole
{
/**
* رابطه با کاربران دارای این نقش
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(
config('auth.providers.users.model', 'App\\Models\\User'),
config('permission.table_names.model_has_roles', 'model_has_roles'),
'role_id',
config('permission.column_names.model_morph_key', 'model_id')
);
}
}

View File

@ -5,20 +5,19 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; // ← اضافه کنید
use App\Models\Wallet;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable; // ← HasApiTokens اضافه شد
use HasApiTokens, HasFactory, Notifiable, HasRoles;
protected $fillable = [
'name',
'email',
'password',
'phone',
'role',
'is_active',
'role', // فیلد قدیمی - بعداً حذف می‌کنیم
];
protected $hidden = [
@ -31,34 +30,44 @@ class User extends Authenticatable
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'is_active' => 'boolean',
'role' => \App\Enums\UserRole::class,
];
}
public function isSuperAdmin(): bool
{
return $this->role === \App\Enums\UserRole::SuperAdmin;
}
// ─── Relationships ───────────────────────────────
public function isTrackingOperator(): bool
{
return $this->role === \App\Enums\UserRole::TrackingOperator;
}
public function isDataEntry(): bool
{
return $this->role === \App\Enums\UserRole::DataEntry;
}
public function isCustomer(): bool
{
return $this->role === \App\Enums\UserRole::Customer;
}
//کیف پول
public function wallet()
{
return $this->hasOne(Wallet::class);
}
// ─── Helper Methods (Role Checks) ────────────────
public function isSuperAdmin(): bool
{
return $this->hasRole('super_admin');
}
public function isAdmin(): bool
{
return $this->hasAnyRole(['super_admin', 'admin']);
}
public function isStaff(): bool
{
return $this->hasRole('staff');
}
public function isCustomer(): bool
{
return $this->hasRole('customer');
}
// ─── Filament Panel Access ───────────────────────
public function canAccessPanel(\Filament\Panel $panel): bool
{
// فقط super_admin, admin, staff می‌توانند به پنل ادمین دسترسی داشته باشند
// customer فقط از API استفاده می‌کند
return $this->hasAnyRole(['super_admin', 'admin', 'staff']);
}
}

View File

@ -13,7 +13,8 @@
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.10.1",
"maatwebsite/excel": "^3.1",
"morilog/jalali": "^3.0"
"morilog/jalali": "^3.0",
"spatie/laravel-permission": "^6.25"
},
"require-dev": {
"fakerphp/faker": "^1.23",

View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "86be2c9d3213013f1619d58ee77dc33c",
"content-hash": "b8dff8147ac7f29e9282deaf74979683",
"packages": [
{
"name": "anourvalar/eloquent-serialize",
@ -5989,6 +5989,90 @@
],
"time": "2026-05-19T14:06:37+00:00"
},
{
"name": "spatie/laravel-permission",
"version": "6.25.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-permission.git",
"reference": "d7d4cb0d58616722f1afc90e0484e4825155b9b3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-permission/zipball/d7d4cb0d58616722f1afc90e0484e4825155b9b3",
"reference": "d7d4cb0d58616722f1afc90e0484e4825155b9b3",
"shasum": ""
},
"require": {
"illuminate/auth": "^8.12|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/container": "^8.12|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/contracts": "^8.12|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/database": "^8.12|^9.0|^10.0|^11.0|^12.0|^13.0",
"php": "^8.0"
},
"require-dev": {
"laravel/passport": "^11.0|^12.0|^13.0",
"laravel/pint": "^1.0",
"orchestra/testbench": "^6.23|^7.0|^8.0|^9.0|^10.0|^11.0",
"pestphp/pest": "^2.0|^3.0|^4.0",
"pestphp/pest-plugin-laravel": "^2.0|^3.0|^4.0"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Spatie\\Permission\\PermissionServiceProvider"
]
},
"branch-alias": {
"dev-main": "6.x-dev",
"dev-master": "6.x-dev"
}
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Spatie\\Permission\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Permission handling for Laravel 8.0 and up",
"homepage": "https://github.com/spatie/laravel-permission",
"keywords": [
"acl",
"laravel",
"permission",
"permissions",
"rbac",
"roles",
"security",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-permission/issues",
"source": "https://github.com/spatie/laravel-permission/tree/6.25.0"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2026-03-17T22:46:46+00:00"
},
{
"name": "symfony/clock",
"version": "v7.4.8",

View File

@ -0,0 +1,206 @@
<?php
use Spatie\Permission\DefaultTeamResolver;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];

View File

@ -0,0 +1,134 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), Exception::class, 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // permission id
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
};

View File

@ -0,0 +1,136 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\User;
class RoleAndPermissionSeeder extends Seeder
{
public function run(): void
{
// پاک کردن cache
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
// ─── تعریف Permissions ───
$permissions = [
// مدیریت کاربران
'view_users',
'create_users',
'edit_users',
'delete_users',
// مدیریت مرسولات
'view_shipments',
'create_shipments',
'edit_shipments',
'delete_shipments',
'export_shipments',
// مدیریت کیف پول
'view_wallets',
'adjust_wallets',
'freeze_wallets',
'view_transactions',
// گزارش‌های مالی
'view_financial_reports',
'export_financial_reports',
// تنظیمات سیستم
'manage_settings',
'adjust_exchange_rates',
// کدهای تخفیف
'manage_discount_codes',
// سفارشات مشتریان
'view_customer_orders',
'update_order_status',
];
foreach ($permissions as $permission) {
Permission::firstOrCreate([
'name' => $permission,
'guard_name' => 'web'
]);
}
// ─── تعریف Roles ───
// Super Admin: دسترسی کامل (guard all permissions)
$superAdmin = Role::firstOrCreate([
'name' => 'super_admin',
'guard_name' => 'web'
]);
$superAdmin->syncPermissions(Permission::all());
$this->command->info('✅ Super Admin role created with all permissions');
// Admin: دسترسی بالا (بدون مدیریت کاربران حساس)
$admin = Role::firstOrCreate([
'name' => 'admin',
'guard_name' => 'web'
]);
$admin->syncPermissions([
'view_users',
'view_shipments', 'create_shipments', 'edit_shipments', 'delete_shipments', 'export_shipments',
'view_wallets', 'adjust_wallets', 'freeze_wallets', 'view_transactions',
'view_financial_reports', 'export_financial_reports',
'manage_discount_codes',
'adjust_exchange_rates',
'view_customer_orders', 'update_order_status',
]);
$this->command->info('✅ Admin role created');
// Staff: فقط مشاهده و عملیات روزمره
$staff = Role::firstOrCreate([
'name' => 'staff',
'guard_name' => 'web'
]);
$staff->syncPermissions([
'view_shipments', 'create_shipments', 'edit_shipments', 'export_shipments',
'view_wallets', 'view_transactions',
'view_customer_orders', 'update_order_status',
]);
$this->command->info('✅ Staff role created');
// Customer: بدون دسترسی به پنل ادمین (فقط API)
Role::firstOrCreate([
'name' => 'customer',
'guard_name' => 'web'
]);
$this->command->info('✅ Customer role created');
// ─── اختصاص role به کاربران موجود ───
$this->command->info('');
$this->command->info('📋 Assigning roles to existing users...');
// کاربر اصلی را super_admin کن
$mainAdmin = User::where('email', 'kazem@vernasoft.group')->first();
if ($mainAdmin) {
$mainAdmin->assignRole('super_admin');
$this->command->info("{$mainAdmin->name} ({$mainAdmin->email}) → super_admin");
} else {
// اگر کاربر اصلی نبود، اولین کاربر را super_admin کن
$firstUser = User::first();
if ($firstUser) {
$firstUser->assignRole('super_admin');
$this->command->info("{$firstUser->name} ({$firstUser->email}) → super_admin (first user)");
}
}
// سایر کاربران موجود را customer کن
User::where('email', '!=', 'kazem@vernasoft.group')
->whereDoesntHave('roles')
->get()
->each(function ($user) {
$user->assignRole('customer');
$this->command->info("{$user->name} ({$user->email}) → customer");
});
$this->command->info('');
$this->command->info('🎉 All roles and permissions seeded successfully!');
}
}