Skip to content

Commit

Permalink
feat: allow configuring role key
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Dec 14, 2024
1 parent 8712722 commit 79a0862
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
1 change: 1 addition & 0 deletions src/Auth/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
6 changes: 3 additions & 3 deletions src/Auth/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

Expand Down Expand Up @@ -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) {
Expand Down
20 changes: 12 additions & 8 deletions src/Auth/UsesRoles.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 79a0862

Please sign in to comment.