From 79a08624af22cb92f7674ba0c851dfa035189f17 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 14 Dec 2024 09:08:55 +0000 Subject: [PATCH] feat: allow configuring role key --- src/Auth/Config.php | 1 + src/Auth/User.php | 6 +++--- src/Auth/UsesRoles.php | 20 ++++++++++++-------- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/Auth/Config.php b/src/Auth/Config.php index 990db3f..adec30e 100644 --- a/src/Auth/Config.php +++ b/src/Auth/Config.php @@ -19,6 +19,7 @@ class Config protected static array $config = [ 'id.key' => 'id', 'db.table' => 'users', + 'roles.key' => 'leaf_auth_user_roles', 'timestamps' => true, 'timestamps.format' => 'YYYY-MM-DD HH:mm:ss', diff --git a/src/Auth/User.php b/src/Auth/User.php index 3e95855..1fc5410 100644 --- a/src/Auth/User.php +++ b/src/Auth/User.php @@ -85,8 +85,8 @@ public function __construct($data, $session = true) $this->tokens['access'] = $this->generateToken($sessionLifetime); $this->tokens['refresh'] = $this->generateToken($sessionLifetime + 259200); - if ($data['roles'] ?? null) { - $this->setRolesAndPermissions(json_decode($data['roles'], true)); + if ($data[Config::get('roles.key')] ?? null) { + $this->setRolesAndPermissions(json_decode($data[Config::get('roles.key')], true)); } } @@ -160,7 +160,7 @@ public function get() $userData = $this->data; $idKey = Config::get('id.key'); - $hidden = array_merge(Config::get('hidden'), ['roles']); + $hidden = array_merge(Config::get('hidden'), [Config::get('roles.key')]); $passwordKey = Config::get('password.key'); if (count($hidden) > 0) { diff --git a/src/Auth/UsesRoles.php b/src/Auth/UsesRoles.php index ae5b943..0ff7c98 100644 --- a/src/Auth/UsesRoles.php +++ b/src/Auth/UsesRoles.php @@ -36,17 +36,21 @@ public function assign($role): bool $this->setRolesAndPermissions($role); - if (!($this->data['roles'] ?? null)) { + if (!($this->data[Config::get('roles.key')] ?? null)) { $this->db->query("ALTER TABLE users ADD COLUMN roles TEXT NOT NULL DEFAULT '[]'")->execute(); } - $this->db - ->update('users') - ->params([ - 'roles' => json_encode($this->roles) - ]) - ->where(Config::get('id.key'), $this->data['id']) - ->execute(); + try { + $this->db + ->update('users') + ->params([ + Config::get('roles.key') => json_encode($this->roles) + ]) + ->where(Config::get('id.key'), $this->data['id']) + ->execute(); + } catch (\Throwable $th) { + return false; + } return true; }