fix: 顯示使用者角色以除錯 & 強化權限指派邏輯
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
* 使用更寬鬆的條件確保 admin 使用者被設為 super-admin
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
// 取得 super-admin 角色
|
||||
$role = DB::table('roles')->where('name', 'super-admin')->first();
|
||||
if (!$role) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 嘗試用多種條件抓取 admin 使用者
|
||||
$user = DB::table('users')
|
||||
->where('username', 'admin')
|
||||
->orWhere('email', 'admin@example.com')
|
||||
->orWhere('username', 'admin01') // 之前對話提到的可能 username
|
||||
->first();
|
||||
|
||||
if (!$user) {
|
||||
// 如果都找不到,嘗試抓 ID = 1 或 2 (通常是建立的第一個使用者)
|
||||
$user = DB::table('users')->orderBy('id')->first();
|
||||
}
|
||||
|
||||
if (!$user) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 檢查是否已有此角色
|
||||
$exists = DB::table('model_has_roles')
|
||||
->where('role_id', $role->id)
|
||||
->where('model_type', 'App\\Models\\User')
|
||||
->where('model_id', $user->id)
|
||||
->exists();
|
||||
|
||||
if (!$exists) {
|
||||
// 移除舊角色並指派新角色
|
||||
DB::table('model_has_roles')
|
||||
->where('model_type', 'App\\Models\\User')
|
||||
->where('model_id', $user->id)
|
||||
->delete();
|
||||
|
||||
DB::table('model_has_roles')->insert([
|
||||
'role_id' => $role->id,
|
||||
'model_type' => 'App\\Models\\User',
|
||||
'model_id' => $user->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user