diff --git a/README.md b/README.md index dc2a6c5..cb651c9 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ quite large. I decided to build CI4-Auth based on Myth-Auth, changing and adding ## Requirements - PHP 8.1+ -- CodeIgniter 4.4+ +- CodeIgniter 4.5+ - [RobThree TwoFactorAuth](http://github.com/RobThree/TwoFactorAuth) ## Features diff --git a/src/Authentication/Activators/BaseActivator.php b/src/Authentication/Activators/BaseActivator.php index e2b3172..d85c673 100644 --- a/src/Authentication/Activators/BaseActivator.php +++ b/src/Authentication/Activators/BaseActivator.php @@ -53,7 +53,7 @@ public function setConfig(AuthConfig $config) { * @return object */ public function getActivatorSettings() { - return (object)$this->config->userActivators[ static::class ]; + return (object)$this->config->userActivators[static::class]; } /** diff --git a/src/Authentication/Activators/EmailActivator.php b/src/Authentication/Activators/EmailActivator.php index d39f721..bf6bc5e 100644 --- a/src/Authentication/Activators/EmailActivator.php +++ b/src/Authentication/Activators/EmailActivator.php @@ -29,7 +29,7 @@ public function send(User $user = null): bool { $sent = $email->setFrom($settings->fromEmail ?? $config->fromEmail, $settings->fromName ?? $config->fromName) ->setTo($user->email) ->setSubject(lang('Auth.activation.subject')) - ->setMessage(view($this->config->views[ 'emailActivation' ], [ 'hash' => $user->activate_hash ])) + ->setMessage(view($this->config->views['emailActivation'], [ 'hash' => $user->activate_hash ])) ->setMailType('html') ->send(); diff --git a/src/Authentication/AuthenticationBase.php b/src/Authentication/AuthenticationBase.php index d43a4e5..910c066 100644 --- a/src/Authentication/AuthenticationBase.php +++ b/src/Authentication/AuthenticationBase.php @@ -37,39 +37,46 @@ class AuthenticationBase { */ protected $config; - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Constructor. + * -------------------------------------------------------------------------- */ public function __construct($config) { $this->config = $config; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Error. + * -------------------------------------------------------------------------- + * * Returns the current error, if any. * * @return string */ - public function error() { + public function error(): string { return $this->error; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Silent. + * -------------------------------------------------------------------------- + * * Whether to continue instead of throwing exceptions, as defined in config. * * @return bool */ - public function silent() { + public function silent(): bool { return (bool)$this->config->silent; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Login. + * -------------------------------------------------------------------------- + * * Logs a user into the system. * NOTE: does not perform validation. All validation should be done prior to * using the login method, incl. 2FA. @@ -132,9 +139,11 @@ public function login(User $user = null, bool $remember = false): bool { return true; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Is Logged In. + * -------------------------------------------------------------------------- + * * Checks to see if the user is logged in. * * @return bool @@ -146,7 +155,6 @@ public function isLoggedIn(): bool { if ($this->user instanceof User) { return true; } - if ($userID = session('logged_in')) { // // Store our current user object @@ -154,35 +162,39 @@ public function isLoggedIn(): bool { $this->user = $this->userModel->find($userID); return $this->user instanceof User; } - return false; } - - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Login By ID. + * -------------------------------------------------------------------------- + * * Logs a user into the system by their ID. * - * @param int $id + * @param int $id * @param bool $remember + * + * @return bool */ - public function loginByID(int $id, bool $remember = false) { + public function loginByID(int $id, bool $remember = false): bool { $user = $this->retrieveUser([ 'id' => $id ]); - if (empty($user)) { throw UserNotFoundException::forUserID($id); } - return $this->login($user, $remember); } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Logout. + * -------------------------------------------------------------------------- + * * Logs a user out of the system. + * + * @return void */ - public function logout() { + public function logout(): void { helper('cookie'); // @@ -191,8 +203,8 @@ public function logout() { // if (isset($_SESSION)) { foreach ($_SESSION as $key => $value) { - $_SESSION[ $key ] = NULL; - unset($_SESSION[ $key ]); + $_SESSION[$key] = NULL; + unset($_SESSION[$key]); } } @@ -224,20 +236,22 @@ public function logout() { } } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Record Login Attempt. + * -------------------------------------------------------------------------- + * * Record a login attempt * - * @param string $email + * @param string $email * @param string|null $ipAddress - * @param int|null $userID - * @param bool $success - * @param string $info + * @param int|null $userID + * @param bool $success + * @param string $info * * @return bool|int|string */ - public function recordLoginAttempt(string $email, string $ipAddress = null, int $userID = null, bool $success, string $info) { + public function recordLoginAttempt(string $email, string $ipAddress = null, int $userID = null, bool $success, string $info): bool|int|string { return $this->loginModel->insert([ 'ip_address' => $ipAddress, 'email' => $email, @@ -248,9 +262,11 @@ public function recordLoginAttempt(string $email, string $ipAddress = null, int ]); } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Remember User. + * -------------------------------------------------------------------------- + * * Generates a timing-attack safe remember me token and stores the necessary * info in the db and a cookie. * @@ -258,9 +274,11 @@ public function recordLoginAttempt(string $email, string $ipAddress = null, int * * @param int $userID * + * @return void + * * @throws \Exception */ - public function rememberUser(int $userID) { + public function rememberUser(int $userID): void { $selector = bin2hex(random_bytes(12)); $validator = bin2hex(random_bytes(20)); $expires = date('Y-m-d H:i:s', time() + $this->config->rememberLength); @@ -293,24 +311,28 @@ public function rememberUser(int $userID) { ); } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Refresh Remember. + * -------------------------------------------------------------------------- + * * Sets a new validator for this user/selector. This allows a one-time use * of remember-me tokens, but still allows a user to be remembered on * multiple browsers/devices. * - * @param int $userID + * @param int $userID * @param string $selector + * + * @return void */ - public function refreshRemember(int $userID, string $selector) { + public function refreshRemember(int $userID, string $selector): void { $existing = $this->loginModel->getRememberToken($selector); // // No matching record? Shouldn't happen, but remember the user now. // if (empty($existing)) { - return $this->rememberUser($userID); + $this->rememberUser($userID); } // @@ -342,46 +364,48 @@ public function refreshRemember(int $userID, string $selector) { ); } - //------------------------------------------------------------------------ - /** + * -------------------------------------------------------------------------- + * Id. + * -------------------------------------------------------------------------- + * * Returns the User ID for the current logged in user. * * @return int|null */ - public function id() { + public function id(): ?int { return $this->user->id ?? null; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * User. + * -------------------------------------------------------------------------- + * * Returns the User instance for the current logged in user. * * @return User|null */ - public function user() { + public function user(): ?User { return $this->user; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Retrieve User. + * -------------------------------------------------------------------------- + * * Grabs the current user from the database. * * @param array $wheres * * @return array|null|object */ - public function retrieveUser(array $wheres) { + public function retrieveUser(array $wheres): array|null|object { if (!$this->userModel instanceof Model) { throw AuthException::forInvalidModel('User'); } - - $user = $this->userModel - ->where($wheres) - ->first(); - + $user = $this->userModel->where($wheres)->first(); return $user; } @@ -389,22 +413,27 @@ public function retrieveUser(array $wheres) { // Model Setters //========================================================================= - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Set User Model. + * -------------------------------------------------------------------------- + * * Sets the model that should be used to work with user accounts. * * @param Model $model * * @return $this */ - public function setUserModel(Model $model) { + public function setUserModel(Model $model): AuthenticationBase { $this->userModel = $model; return $this; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Check. + * -------------------------------------------------------------------------- + * * Sets the model that should be used to record login attempts (but failed * and successful). * @@ -412,7 +441,7 @@ public function setUserModel(Model $model) { * * @return $this */ - public function setLoginModel(Model $model) { + public function setLoginModel(Model $model): AuthenticationBase { $this->loginModel = $model; return $this; } diff --git a/src/Authentication/AuthenticatorInterface.php b/src/Authentication/AuthenticatorInterface.php index dc3e604..45b3c55 100644 --- a/src/Authentication/AuthenticatorInterface.php +++ b/src/Authentication/AuthenticatorInterface.php @@ -9,7 +9,7 @@ interface AuthenticatorInterface { * Attempts to validate the credentials and log a user in. * * @param array $credentials - * @param bool $remember Should we remember the user (if enabled) + * @param bool $remember Should we remember the user (if enabled) * * @return bool */ @@ -27,7 +27,7 @@ public function check(): bool; * Unlike `attempt()`, will not log the user into the system. * * @param array $credentials - * @param bool $returnUser + * @param bool $returnUser * * @return bool|User */ diff --git a/src/Authentication/LocalAuthenticator.php b/src/Authentication/LocalAuthenticator.php index 085c6bb..f62d2f7 100644 --- a/src/Authentication/LocalAuthenticator.php +++ b/src/Authentication/LocalAuthenticator.php @@ -8,13 +8,15 @@ use CI4\Auth\Password; class LocalAuthenticator extends AuthenticationBase implements AuthenticatorInterface { - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Attempt. + * -------------------------------------------------------------------------- + * * Attempts to validate the credentials and log a user in. * * @param array $credentials - * @param bool $remember Should we remember the user (if enabled) + * @param bool $remember Should we remember the user (if enabled) * * @return bool */ @@ -26,7 +28,7 @@ public function attempt(array $credentials, bool $remember = null): bool { // User empty or unknown // $ipAddress = service('request')->getIPAddress(); - $this->recordLoginAttempt($credentials[ 'email' ] ?? $credentials[ 'username' ], $ipAddress, $this->user->id ?? null, false, 'User unknown'); + $this->recordLoginAttempt($credentials['email'] ?? $credentials['username'], $ipAddress, $this->user->id ?? null, false, 'User unknown'); $this->user = null; return false; } @@ -36,7 +38,7 @@ public function attempt(array $credentials, bool $remember = null): bool { // User banned // $ipAddress = service('request')->getIPAddress(); - $this->recordLoginAttempt($credentials[ 'email' ] ?? $credentials[ 'username' ], $ipAddress, $this->user->id ?? null, false, 'User banned'); + $this->recordLoginAttempt($credentials['email'] ?? $credentials['username'], $ipAddress, $this->user->id ?? null, false, 'User banned'); $this->error = lang('Auth.user.is_banned'); $this->user = null; return false; @@ -47,8 +49,8 @@ public function attempt(array $credentials, bool $remember = null): bool { // User inactive // $ipAddress = service('request')->getIPAddress(); - $this->recordLoginAttempt($credentials[ 'email' ] ?? $credentials[ 'username' ], $ipAddress, $this->user->id ?? null, false, 'User inactive'); - $param = http_build_query([ 'login' => urlencode($credentials[ 'email' ] ?? $credentials[ 'username' ]) ]); + $this->recordLoginAttempt($credentials['email'] ?? $credentials['username'], $ipAddress, $this->user->id ?? null, false, 'User inactive'); + $param = http_build_query([ 'login' => urlencode($credentials['email'] ?? $credentials['username']) ]); $this->error = lang('Auth.activation.not_activated') . '
' . anchor(route_to('resend-activate-account') . '?' . $param, lang('Auth.activation.resend')); $this->user = null; return false; @@ -59,13 +61,15 @@ public function attempt(array $credentials, bool $remember = null): bool { // Do not login the user yet. Return true only because a 2FA might still // be needed. // -// return $this->login($this->user, $remember); +// return $this->login($this->user, $remember); return true; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Check. + * -------------------------------------------------------------------------- + * * Checks to see if the user is logged in or not. * * @return bool @@ -115,14 +119,16 @@ public function check(): bool { return true; } - //------------------------------------------------------------------------- - /** + * -------------------------------------------------------------------------- + * Validate. + * -------------------------------------------------------------------------- + * * Checks the user's credentials to see if they could authenticate. * Unlike `attempt()`, will not log the user into the system. * * @param array $credentials - * @param bool $returnUser + * @param bool $returnUser * * @return bool|User */ @@ -130,15 +136,15 @@ public function validate(array $credentials, bool $returnUser = false) { // // Can't validate without a password. // - if (empty($credentials[ 'password' ]) || count($credentials) < 2) { + if (empty($credentials['password']) || count($credentials) < 2) { return false; } // // Only allowed 1 additional credential other than password // - $password = $credentials[ 'password' ]; - unset($credentials[ 'password' ]); + $password = $credentials['password']; + unset($credentials['password']); if (count($credentials) > 1) { throw AuthException::forTooManyCredentials(); diff --git a/src/Authentication/Passwords/CompositionValidator.php b/src/Authentication/Passwords/CompositionValidator.php index 4f81669..dd92374 100644 --- a/src/Authentication/Passwords/CompositionValidator.php +++ b/src/Authentication/Passwords/CompositionValidator.php @@ -14,7 +14,7 @@ * groups that you had to include, current NIST standards prefer to simply * set a minimum length and a long maximum (128+ chars). * - * @see https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 + * @see https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 * * * @package CI4\Auth\Authentication\Passwords\Validators diff --git a/src/Authentication/Passwords/NothingPersonalValidator.php b/src/Authentication/Passwords/NothingPersonalValidator.php index 691ef01..87ec7fd 100644 --- a/src/Authentication/Passwords/NothingPersonalValidator.php +++ b/src/Authentication/Passwords/NothingPersonalValidator.php @@ -62,6 +62,7 @@ public function check(string $password, $user = null): bool { * * @param string $password * @param Entity $user + * * @return boolean */ protected function isNotPersonal($password, $user) { @@ -152,6 +153,7 @@ protected function isNotPersonal($password, $user) { * * @param string $password * @param Entity $user + * * @return boolean */ protected function isNotSimilar($password, $user) { @@ -183,6 +185,7 @@ protected function isNotSimilar($password, $user) { * Then it explodes that result using the space for a delimiter. * * @param string $str + * * @return array */ protected function strip_explode($str) { diff --git a/src/Authentication/Passwords/PasswordValidator.php b/src/Authentication/Passwords/PasswordValidator.php index 5110db3..c65ce8c 100644 --- a/src/Authentication/Passwords/PasswordValidator.php +++ b/src/Authentication/Passwords/PasswordValidator.php @@ -22,13 +22,16 @@ public function __construct(AuthConfig $config) { $this->config = $config; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Check. + * -------------------------------------------------------------------------- + * * Checks a password against all of the Validators specified * in `$passwordValidators` setting in Config\Auth.php. * * @param string $password - * @param User $user + * @param User $user * * @return bool */ @@ -64,20 +67,25 @@ public function check(string $password, User $user = null): bool { return $valid; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Error. + * -------------------------------------------------------------------------- + * * Returns the current error, as defined by validator * it failed to pass. * * @return mixed */ public function error() { - return $this->error; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Suggestion. + * -------------------------------------------------------------------------- + * * Returns a string with any suggested fix * based on the validator it failed to pass. * diff --git a/src/Authentication/Passwords/PwnedValidator.php b/src/Authentication/Passwords/PwnedValidator.php index f897d65..dec900a 100644 --- a/src/Authentication/Passwords/PwnedValidator.php +++ b/src/Authentication/Passwords/PwnedValidator.php @@ -11,10 +11,11 @@ * * Checks if the password has been compromised by checking against * an online database of over 555 million stolen passwords. - * @see https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/ + * + * @see https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/ * * NIST recommend to check passwords against those obtained from previous data breaches. - * @see https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 + * @see https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 * * @package CI4\Auth\Authentication\Passwords\Validators */ diff --git a/src/Authentication/Passwords/ValidationRules.php b/src/Authentication/Passwords/ValidationRules.php index 234f18e..cee3a60 100644 --- a/src/Authentication/Passwords/ValidationRules.php +++ b/src/Authentication/Passwords/ValidationRules.php @@ -23,9 +23,9 @@ class ValidationRules { * better security if this is done manually, since you can * personalize based on a specific user at that point. * - * @param string $value Field value + * @param string $value Field value * @param string $error1 Error that will be returned (for call without validation data array) - * @param array $data Validation data array + * @param array $data Validation data array * @param string $error2 Error that will be returned (for call with validation data array) * * @return bool @@ -56,8 +56,9 @@ public function strong_password(string $value, string &$error1 = null, array $da * Specific validator for permission names. * Only lower case alpha characters and dots. * - * @param string $str - Field value + * @param string $str - Field value * @param string $error - Error that will be returned (for call without validation data array) + * * @return bool */ public function lower_alpha_dash_dot($str, ?string &$error = null): bool { diff --git a/src/Authentication/Resetters/BaseResetter.php b/src/Authentication/Resetters/BaseResetter.php index d796161..2d98200 100644 --- a/src/Authentication/Resetters/BaseResetter.php +++ b/src/Authentication/Resetters/BaseResetter.php @@ -53,7 +53,7 @@ public function setConfig(AuthConfig $config) { * @return object */ public function getResetterSettings() { - return (object)$this->config->userResetters[ static::class ]; + return (object)$this->config->userResetters[static::class]; } /** diff --git a/src/Authentication/Resetters/EmailResetter.php b/src/Authentication/Resetters/EmailResetter.php index 69859d5..1208bf9 100644 --- a/src/Authentication/Resetters/EmailResetter.php +++ b/src/Authentication/Resetters/EmailResetter.php @@ -29,7 +29,7 @@ public function send(User $user = null): bool { $sent = $email->setFrom($settings->fromEmail ?? $config->fromEmail, $settings->fromName ?? $config->fromName) ->setTo($user->email) ->setSubject(lang('Auth.forgot.subject')) - ->setMessage(view($this->config->views[ 'emailForgot' ], [ 'hash' => $user->reset_hash ])) + ->setMessage(view($this->config->views['emailForgot'], [ 'hash' => $user->reset_hash ])) ->setMailType('html') ->send(); diff --git a/src/Authorization/AuthorizeInterface.php b/src/Authorization/AuthorizeInterface.php index 2454b23..59e5c1c 100644 --- a/src/Authorization/AuthorizeInterface.php +++ b/src/Authorization/AuthorizeInterface.php @@ -22,7 +22,7 @@ public function error(); * to ONE of. (It's an OR check not an AND check) * * @param mixed $groups - * @param int $userId + * @param int $userId * * @return bool */ @@ -36,7 +36,7 @@ public function inGroup($groups, int $userId); * ONE of. (It's an OR check not an AND check) * * @param mixed $roles - * @param int $userId + * @param int $userId * * @return bool */ @@ -46,7 +46,7 @@ public function inRole($roles, int $userId); * Checks a user's roles to see if they have the specified permission. * * @param int|string $permission - * @param int $userId + * @param int $userId * * @return mixed */ @@ -55,7 +55,7 @@ public function hasPermission($permission, int $userId); /** * Adds a user to a group. * - * @param int $userid + * @param int $userid * @param int|string $group Either ID or name * * @return bool @@ -65,7 +65,7 @@ public function addUserToGroup(int $userid, $group); /** * Adds a user to a role. * - * @param int $userid + * @param int $userid * @param int|string $role Either ID or name * * @return bool @@ -75,7 +75,7 @@ public function addUserToRole(int $userid, $role); /** * Removes a single user from a group. * - * @param int $userId + * @param int $userId * @param int|string $group * * @return mixed @@ -85,7 +85,7 @@ public function removeUserFromGroup(int $userId, $group); /** * Removes a single user from a role. * - * @param int $userId + * @param int $userId * @param int|string $role * * @return mixed @@ -172,7 +172,7 @@ public function deleteGroup(int $groupId); /** * Updates a single group's information. * - * @param int $id + * @param int $id * @param string $name * @param string $description * @@ -220,7 +220,7 @@ public function deleteRole(int $roleId); /** * Updates a single role's information. * - * @param int $id + * @param int $id * @param string $name * @param string $description * @@ -270,7 +270,7 @@ public function deletePermission(int $permissionId); /** * Updates the details for a single permission. * - * @param int $id + * @param int $id * @param string $name * @param string $description * diff --git a/src/Authorization/FlatAuthorization.php b/src/Authorization/FlatAuthorization.php index ad45ae7..37ef070 100644 --- a/src/Authorization/FlatAuthorization.php +++ b/src/Authorization/FlatAuthorization.php @@ -49,12 +49,15 @@ class FlatAuthorization implements AuthorizeInterface { */ protected $userModel = null; - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Constructor. + * -------------------------------------------------------------------------- + * * Stores the models. * - * @param GroupModel $groupModel - * @param RoleModel $roleModel + * @param GroupModel $groupModel + * @param RoleModel $roleModel * @param PermissionModel $permissionModel */ public function __construct(Model $groupModel, Model $roleModel, Model $permissionModel) { @@ -63,16 +66,19 @@ public function __construct(Model $groupModel, Model $roleModel, Model $permissi $this->permissionModel = $permissionModel; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add Permission to Group. + * -------------------------------------------------------------------------- + * * Adds a single permission to a single group. * * @param int|string $permission * @param int|string $group * - * @return mixed + * @return bool */ - public function addPermissionToGroup($permission, $group) { + public function addPermissionToGroup($permission, $group): bool { $permissionId = $this->getPermissionID($permission); $groupId = $this->getGroupID($group); @@ -88,16 +94,19 @@ public function addPermissionToGroup($permission, $group) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add Permission to Role. + * -------------------------------------------------------------------------- + * * Adds a single permission to a single role. * * @param int|string $permission * @param int|string $role * - * @return mixed + * @return bool */ - public function addPermissionToRole($permission, $role) { + public function addPermissionToRole($permission, $role): bool { $permissionId = $this->getPermissionID($permission); $roleId = $this->getRoleID($role); @@ -113,17 +122,20 @@ public function addPermissionToRole($permission, $role) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add Permission to User. + * -------------------------------------------------------------------------- + * * Assigns a single permission to a user, irregardless of permissions * assigned by roles. This is saved to the user's meta information. * * @param int|string $permission - * @param int $userId + * @param int $userId * * @return bool|null */ - public function addPermissionToUser($permission, int $userId) { + public function addPermissionToUser($permission, int $userId): bool|null { $permissionId = $this->getPermissionID($permission); if (!is_numeric($permissionId)) return null; @@ -149,16 +161,19 @@ public function addPermissionToUser($permission, int $userId) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add User to Group. + * -------------------------------------------------------------------------- + * * Adds a user to group. * - * @param int $userid + * @param int $userid * @param mixed $group Either ID or name, fails on anything else * * @return bool|null */ - public function addUserToGroup(int $userid, $group) { + public function addUserToGroup(int $userid, $group): bool|null { if (empty($userid) || !is_numeric($userid)) return null; if (empty($group) || (!is_numeric($group) && !is_string($group))) return null; @@ -179,16 +194,19 @@ public function addUserToGroup(int $userid, $group) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add User to Role. + * -------------------------------------------------------------------------- + * * Adds a user to role. * - * @param int $userid + * @param int $userid * @param mixed $role Either ID or name, fails on anything else * * @return bool|null */ - public function addUserToRole(int $userid, $role) { + public function addUserToRole(int $userid, $role): bool|null { if (empty($userid) || !is_numeric($userid)) return null; if (empty($role) || (!is_numeric($role) && !is_string($role))) return null; @@ -209,8 +227,11 @@ public function addUserToRole(int $userid, $role) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Create Permission. + * -------------------------------------------------------------------------- + * * Creates a single permission. * * @param string $name @@ -218,7 +239,7 @@ public function addUserToRole(int $userid, $role) { * * @return mixed */ - public function createPermission(string $name, string $description = '') { + public function createPermission(string $name, string $description = ''): mixed { $data = [ 'name' => $name, 'description' => $description, @@ -244,14 +265,17 @@ public function createPermission(string $name, string $description = '') { return false; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Create Group. + * -------------------------------------------------------------------------- + * * @param string $name * @param string $description * * @return mixed */ - public function createGroup(string $name, string $description = '') { + public function createGroup(string $name, string $description = ''): mixed { $data = [ 'name' => $name, 'description' => $description, @@ -291,12 +315,16 @@ public function createGroup(string $name, string $description = '') { //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Create Role. + * -------------------------------------------------------------------------- + * * @param string $name * @param string $description * * @return mixed */ - public function createRole(string $name, string $description = '') { + public function createRole(string $name, string $description = ''): mixed { $data = [ 'name' => $name, 'description' => $description, @@ -334,63 +362,71 @@ public function createRole(string $name, string $description = '') { return false; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Group. + * -------------------------------------------------------------------------- + * * Deletes a single group. * * @param int $groupId * * @return bool */ - public function deleteGroup(int $groupId) { + public function deleteGroup(int $groupId): bool { if (!$this->groupModel->delete($groupId)) { $this->error = $this->groupModel->errors(); return false; } - return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Permission. + * -------------------------------------------------------------------------- + * * Deletes a single permission and removes that permission from all roles. * - * @param int $permissionIdId + * @param int $permissionId * - * @return mixed + * @return bool */ - public function deletePermission(int $permissionIdId) { - if (!$this->permissionModel->delete($permissionIdId)) { + public function deletePermission(int $permissionId): bool { + if (!$this->permissionModel->delete($permissionId)) { $this->error = $this->permissionModel->errors(); return false; } - // Remove the permission from all roles and groups - $this->roleModel->removePermissionFromAllRoles($permissionIdId); - $this->groupModel->removePermissionFromAllGroups($permissionIdId); - + $this->roleModel->removePermissionFromAllRoles($permissionId); + $this->groupModel->removePermissionFromAllGroups($permissionId); return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Role. + * -------------------------------------------------------------------------- + * * Deletes a single role. * * @param int $roleId * * @return bool */ - public function deleteRole(int $roleId) { + public function deleteRole(int $roleId): bool { if (!$this->roleModel->delete($roleId)) { $this->error = $this->roleModel->errors(); return false; } - return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Does User Have Permission. + * -------------------------------------------------------------------------- + * * Checks to see if a user has personal permission assigned to it (not via * a group or role). * @@ -399,7 +435,7 @@ public function deleteRole(int $roleId) { * * @return bool|null */ - public function doesUserHavePermission($userId, $permission) { + public function doesUserHavePermission($userId, $permission): bool|null { $permissionId = $this->getPermissionID($permission); if (!is_numeric($permissionId)) return false; @@ -409,18 +445,24 @@ public function doesUserHavePermission($userId, $permission) { return $this->permissionModel->doesUserHavePermission($userId, $permissionId); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Error. + * -------------------------------------------------------------------------- + * * Returns any error(s) from the last call. * * @return array|string|null */ - public function error() { + public function error(): array|string|null { return $this->error; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Group ID. + * -------------------------------------------------------------------------- + * * Given a group, will return the group ID. The group can be either * the ID or the name of the group. * @@ -428,7 +470,7 @@ public function error() { * * @return int|false */ - protected function getGroupID($group) { + protected function getGroupID($group): int|false { if (is_numeric($group)) return (int)$group; $g = $this->groupModel->where('name', $group)->first(); @@ -441,8 +483,11 @@ protected function getGroupID($group) { return (int)$g->id; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Permission ID. + * -------------------------------------------------------------------------- + * * Verifies that a permission (either ID or the name) exists and returns * the permission ID. * @@ -450,7 +495,7 @@ protected function getGroupID($group) { * * @return int|false */ - protected function getPermissionID($permission) { + protected function getPermissionID($permission): int|false { // If it's a number, we're done here. if (is_numeric($permission)) return (int)$permission; @@ -465,8 +510,11 @@ protected function getPermissionID($permission) { return (int)$p->id; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Role ID. + * -------------------------------------------------------------------------- + * * Given a role, will return the role ID. The role can be either * the ID or the name of the role. * @@ -474,45 +522,50 @@ protected function getPermissionID($permission) { * * @return int|false */ - protected function getRoleID($role) { + protected function getRoleID($role): int|false { if (is_numeric($role)) return (int)$role; - $r = $this->roleModel->where('name', $role)->first(); - if (!$r) { $this->error = lang('Auth.role.not_found', [ $role ]); return false; } - return (int)$r->id; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Group. + * -------------------------------------------------------------------------- + * * Grabs the details about a single group. * * @param int|string $group * * @return object|null */ - public function group($group) { + public function group($group): object|null { if (is_numeric($group)) return $this->groupModel->find((int)$group); - return $this->groupModel->where('name', $group)->first(); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Groups. + * -------------------------------------------------------------------------- + * * Grabs an array of all groups. * * @return array of objects */ - public function groups() { + public function groups(): array { return $this->groupModel->orderBy('name', 'asc')->findAll(); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Group Permissions. + * -------------------------------------------------------------------------- + * * Returns an array of all permissions in the system for a group. * The group can be either the ID or the name of the group. * @@ -520,7 +573,7 @@ public function groups() { * * @return mixed */ - public function groupPermissions($group) { + public function groupPermissions($group): mixed { if (is_numeric($group)) { return $this->groupModel->getPermissionsForGroup($group); } else { @@ -529,16 +582,19 @@ public function groupPermissions($group) { } } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Has Permission. + * -------------------------------------------------------------------------- + * * Checks whether a user has a given permission. * * @param int|string $permission Permission ID or name - * @param int $userId + * @param int $userId * * @return mixed */ - public function hasPermission($permission, int $userId) { + public function hasPermission($permission, int $userId): mixed { if (empty($permission) || (!is_string($permission) && !is_numeric($permission))) return null; if (empty($userId) || !is_numeric($userId)) return null; @@ -555,8 +611,11 @@ public function hasPermission($permission, int $userId) { return $this->doesUserHavePermission($userId, (int)$permissionId); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Has Permissions. + * -------------------------------------------------------------------------- + * * Checks whether a user has any of the given permissions. * * Permissions can be either a string, with the name of the permission, an @@ -565,11 +624,11 @@ public function hasPermission($permission, int $userId) { * (It's an OR check not an AND check) * * @param mixed $permissions Permission ID or name (or array of) - * @param int $userId + * @param int $userId * - * @return bool + * @return bool|null */ - public function hasPermissions($permissions, int $userId) { + public function hasPermissions($permissions, int $userId): bool|null { if (empty($userId) || !is_numeric($userId)) return null; if (!is_array($permissions)) $permissions = [ $permissions ]; @@ -587,20 +646,23 @@ public function hasPermissions($permissions, int $userId) { return false; } - //------------------------------------------------------------------------- /** - * Checks to see if a user is in a group. + * -------------------------------------------------------------------------- + * In Group. + * -------------------------------------------------------------------------- + * + * Checks whether a user is in a group. * * Groups can be either a string, with the name of the group, an INT with the * ID of the group, or an array of strings/ids that the user must belong to * ONE of. (It's an OR check not an AND check) * * @param mixed $groups - * @param int $userId + * @param int $userId * * @return bool */ - public function inGroup($groups, int $userId) { + public function inGroup($groups, int $userId): bool { if ($userId === 0) return false; if (!is_array($groups)) $groups = [ $groups ]; @@ -622,20 +684,23 @@ public function inGroup($groups, int $userId) { return false; } - //------------------------------------------------------------------------- /** - * Checks to see if a user is in a role. + * -------------------------------------------------------------------------- + * In Role. + * -------------------------------------------------------------------------- + * + * Checks whether a user is in a role. * * Roles can be either a string, with the name of the role, an INT * with the ID of the role, or an array of strings/ids that the * user must belong to ONE of. (It's an OR check not an AND check) * * @param mixed $roles - * @param int $userId + * @param int $userId * * @return bool */ - public function inRole($roles, int $userId) { + public function inRole($roles, int $userId): bool { if ($userId === 0) return false; if (!is_array($roles)) $roles = [ $roles ]; @@ -657,32 +722,40 @@ public function inRole($roles, int $userId) { return false; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permission. + * -------------------------------------------------------------------------- + * * Returns the details about a single permission. * * @param int|string $permission * * @return object|null */ - public function permission($permission) { + public function permission($permission): object|null { if (is_numeric($permission)) return $this->permissionModel->find((int)$permission); - return $this->permissionModel->like('name', $permission, 'none', null, true)->first(); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permissions. + * -------------------------------------------------------------------------- + * * Returns an array of all permissions in the system. * * @return mixed */ - public function permissions() { + public function permissions(): mixed { return $this->permissionModel->orderBy('name', 'asc')->findAll(); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from Group. + * -------------------------------------------------------------------------- + * * Removes a single permission from a group. * * @param int|string $permission @@ -690,7 +763,7 @@ public function permissions() { * * @return mixed */ - public function removePermissionFromGroup($permission, $group) { + public function removePermissionFromGroup($permission, $group): mixed { $permissionId = $this->getPermissionID($permission); $groupId = $this->getRoleID($group); @@ -706,8 +779,11 @@ public function removePermissionFromGroup($permission, $group) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from Role. + * -------------------------------------------------------------------------- + * * Removes a single permission from a role. * * @param int|string $permission @@ -715,7 +791,7 @@ public function removePermissionFromGroup($permission, $group) { * * @return mixed */ - public function removePermissionFromRole($permission, $role) { + public function removePermissionFromRole($permission, $role): mixed { $permissionId = $this->getPermissionID($permission); $roleId = $this->getRoleID($role); @@ -731,59 +807,61 @@ public function removePermissionFromRole($permission, $role) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove all Permissions from User. + * -------------------------------------------------------------------------- + * * Removes all individual permissions from a user. * * @param int $userId * - * @return bool|mixed|null + * @return bool|null */ - public function removeAllPermissionsFromUser(int $userId) { + public function removeAllPermissionsFromUser(int $userId): bool|null { if (empty($userId) || !is_numeric($userId)) return null; - $userId = (int)$userId; - if (!Events::trigger('beforeRemoveAllPermissionsFromUser', $userId)) return false; - - return $this->permissionModel->removeAllPermissionsFromUser($userId); + $this->permissionModel->removeAllPermissionsFromUser($userId); + return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from User. + * -------------------------------------------------------------------------- + * * Removes a single permission from a user. Only applies to permissions * that have been assigned with addPermissionToUser, not to permissions * inherited based on roles they belong to. * * @param int|string $permission - * @param int $userId + * @param int $userId * * @return bool|mixed|null */ - public function removePermissionFromUser($permission, int $userId) { + public function removePermissionFromUser($permission, int $userId): bool|null { $permissionId = $this->getPermissionID($permission); - if (!is_numeric($permissionId)) return false; - if (empty($userId) || !is_numeric($userId)) return null; - $userId = (int)$userId; - if (!Events::trigger('beforeRemovePermissionFromUser', $userId, $permissionId)) return false; - return $this->permissionModel->removePermissionFromUser($permissionId, $userId); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from Group. + * -------------------------------------------------------------------------- + * * Removes a single user from a group. * - * @param int $userId + * @param int $userId * @param mixed $group * * @return mixed */ - public function removeUserFromGroup(int $userId, $group) { + public function removeUserFromGroup(int $userId, $group): mixed { if (empty($userId) || !is_numeric($userId)) return null; if (empty($group) || (!is_numeric($group) && !is_string($group))) return null; @@ -792,7 +870,6 @@ public function removeUserFromGroup(int $userId, $group) { if (!Events::trigger('beforeRemoveUserFromGroup', $userId, $groupId)) return false; - // Role ID if (!is_numeric($groupId)) return false; if (!$this->groupModel->removeUserFromGroup($userId, $groupId)) { @@ -805,16 +882,19 @@ public function removeUserFromGroup(int $userId, $group) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from Role. + * -------------------------------------------------------------------------- + * * Removes a single user from a role. * - * @param int $userId + * @param int $userId * @param mixed $role * * @return mixed */ - public function removeUserFromRole(int $userId, $role) { + public function removeUserFromRole(int $userId, $role): mixed { if (empty($userId) || !is_numeric($userId)) return null; if (empty($role) || (!is_numeric($role) && !is_string($role))) return null; @@ -823,7 +903,6 @@ public function removeUserFromRole(int $userId, $role) { if (!Events::trigger('beforeRemoveUserFromRole', $userId, $roleId)) return false; - // Role ID if (!is_numeric($roleId)) return false; if (!$this->roleModel->removeUserFromRole($userId, $roleId)) { @@ -836,15 +915,18 @@ public function removeUserFromRole(int $userId, $role) { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from all Groups. + * -------------------------------------------------------------------------- + * * Removes a user from all groups. * * @param int $userId * * @return bool|mixed|null */ - public function removeUserFromAllGroups(int $userId) { + public function removeUserFromAllGroups(int $userId): bool|null { if (empty($userId) || !is_numeric($userId)) return null; $userId = (int)$userId; @@ -854,15 +936,18 @@ public function removeUserFromAllGroups(int $userId) { return $this->groupModel->removeUserFromAllGroups($userId); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * * Remove User from all Roles. + * * -------------------------------------------------------------------------- + * * * Removes a user from all roles. * * @param int $userId * * @return bool|mixed|null */ - public function removeUserFromAllRoles(int $userId) { + public function removeUserFromAllRoles(int $userId): bool|null { if (empty($userId) || !is_numeric($userId)) return null; $userId = (int)$userId; @@ -872,32 +957,40 @@ public function removeUserFromAllRoles(int $userId) { return $this->roleModel->removeUserFromAllRoles($userId); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Role. + * -------------------------------------------------------------------------- + * * Grabs the details about a single role. * * @param int|string $role * * @return object|null */ - public function role($role) { + public function role($role): object|null { if (is_numeric($role)) return $this->roleModel->find((int)$role); - return $this->roleModel->where('name', $role)->first(); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Roles. + * -------------------------------------------------------------------------- + * * Grabs an array of all roles. * * @return array of objects */ - public function roles() { + public function roles(): array { return $this->roleModel->orderBy('name', 'asc')->findAll(); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Role Permissions. + * -------------------------------------------------------------------------- + * * Returns an array of all permissions in the system for a role * The role can be either the ID or the name of the role. * @@ -905,7 +998,7 @@ public function roles() { * * @return mixed */ - public function rolePermissions($role) { + public function rolePermissions($role): mixed { if (is_numeric($role)) { return $this->roleModel->getPermissionsForRole($role); } else { @@ -914,36 +1007,42 @@ public function rolePermissions($role) { } } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Set User Model. + * -------------------------------------------------------------------------- + * * Allows the consuming application to pass in a reference to the * model that should be used. * * @param UserModel $model * - * @return mixed + * @return $this */ - public function setUserModel(Model $model) { + public function setUserModel(Model $model): self { $this->userModel = $model; return $this; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Update Group. + * -------------------------------------------------------------------------- + * * Updates a single group's information. * - * @param int $id + * @param int $id * @param string $name * @param string $description * * @return mixed */ - public function updateGroup(int $id, string $name, string $description = '') { + public function updateGroup(int $id, string $name, string $description = ''): mixed { $data = [ 'name' => $name, ]; - if (!empty($description)) $data[ 'description' ] = $description; + if (!empty($description)) $data['description'] = $description; if (!$this->groupModel->update($id, $data)) { $this->error = $this->groupModel->errors(); @@ -953,22 +1052,25 @@ public function updateGroup(int $id, string $name, string $description = '') { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Update Permission. + * -------------------------------------------------------------------------- + * * Updates the details for a single permission. * - * @param int $id + * @param int $id * @param string $name * @param string $description * * @return bool */ - public function updatePermission(int $id, string $name, string $description = '') { + public function updatePermission(int $id, string $name, string $description = ''): bool { $data = [ 'name' => $name, ]; - if (!empty($description)) $data[ 'description' ] = $description; + if (!empty($description)) $data['description'] = $description; if (!$this->permissionModel->update((int)$id, $data)) { $this->error = $this->permissionModel->errors(); @@ -978,22 +1080,25 @@ public function updatePermission(int $id, string $name, string $description = '' return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Update Role. + * -------------------------------------------------------------------------- + * * Updates a single role's information. * - * @param int $id + * @param int $id * @param string $name * @param string $description * * @return mixed */ - public function updateRole(int $id, string $name, string $description = '') { + public function updateRole(int $id, string $name, string $description = ''): mixed { $data = [ 'name' => $name, ]; - if (!empty($description)) $data[ 'description' ] = $description; + if (!empty($description)) $data['description'] = $description; if (!$this->roleModel->update($id, $data)) { $this->error = $this->roleModel->errors(); @@ -1003,8 +1108,11 @@ public function updateRole(int $id, string $name, string $description = '') { return true; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users in Group. + * -------------------------------------------------------------------------- + * * Returns an array of all users in a group. * The group can be either the ID or the name of the group. * @@ -1012,7 +1120,7 @@ public function updateRole(int $id, string $name, string $description = '') { * * @return mixed */ - public function usersInGroup($group) { + public function usersInGroup($group): mixed { if (is_numeric($group)) { return $this->groupModel->getUsersForGroup($group); } else { @@ -1021,8 +1129,11 @@ public function usersInGroup($group) { } } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users in Role. + * -------------------------------------------------------------------------- + * * Returns an array of all users in a role. * The role can be either the ID or the name of the role. * @@ -1030,7 +1141,7 @@ public function usersInGroup($group) { * * @return mixed */ - public function usersInRole($role) { + public function usersInRole($role): mixed { if (is_numeric($role)) { return $this->roleModel->getUsersForRole($role); } else { @@ -1039,30 +1150,36 @@ public function usersInRole($role) { } } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * User Groups. + * -------------------------------------------------------------------------- + * * Returns an array of all groups of a user. * * @param int $userId * * @return mixed */ - public function userGroups($userId) { + public function userGroups($userId): mixed { if (is_numeric($userId)) { return $this->groupModel->getGroupsForUser($userId); } return false; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * User Roles. + * -------------------------------------------------------------------------- + * * Returns an array of all roles of a user. * * @param int $userId * * @return mixed */ - public function userRoles($userId) { + public function userRoles($userId): mixed { if (is_numeric($userId)) { return $this->roleModel->getRolesForUser($userId); } diff --git a/src/Authorization/GroupModel.php b/src/Authorization/GroupModel.php index 59ec91d..1cbb819 100644 --- a/src/Authorization/GroupModel.php +++ b/src/Authorization/GroupModel.php @@ -12,8 +12,11 @@ class GroupModel extends Model { protected $useTimestamps = false; protected $skipValidation = false; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add Permission to Group. + * -------------------------------------------------------------------------- + * * Add a single permission to a single group, by IDs. * * @param int $permissionId @@ -21,7 +24,7 @@ class GroupModel extends Model { * * @return mixed */ - public function addPermissionToGroup(int $permissionId, int $groupId) { + public function addPermissionToGroup(int $permissionId, int $groupId): bool { $data = [ 'group_id' => (int)$groupId, 'permission_id' => (int)$permissionId, @@ -30,8 +33,11 @@ public function addPermissionToGroup(int $permissionId, int $groupId) { return $this->db->table('auth_groups_permissions')->insert($data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add User to Group. + * -------------------------------------------------------------------------- + * * Adds a single user to a single group. * * @param int $userId @@ -39,7 +45,7 @@ public function addPermissionToGroup(int $permissionId, int $groupId) { * * @return bool */ - public function addUserToGroup(int $userId, int $groupId) { + public function addUserToGroup(int $userId, int $groupId): bool { cache()->delete("{$groupId}_users"); cache()->delete("{$userId}_groups"); cache()->delete("{$userId}_permissions"); @@ -52,15 +58,18 @@ public function addUserToGroup(int $userId, int $groupId) { return (bool)$this->db->table('auth_groups_users')->insert($data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Group. + * -------------------------------------------------------------------------- + * * Deletes a group. * * @param int $id Group ID * * @return bool */ - public function deleteGroup(int $id) { + public function deleteGroup(int $id): bool { if (!$this->delete($id)) { $this->error = $this->errors(); return false; @@ -69,15 +78,18 @@ public function deleteGroup(int $id) { return true; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Groups for User. + * -------------------------------------------------------------------------- + * * Returns an array of all groups that a user is a member of. * * @param int $userId * * @return array */ - public function getGroupsForUser(int $userId) { + public function getGroupsForUser(int $userId): array { if (null === $found = cache("{$userId}_groups")) { $found = $this->builder() ->select('auth_groups_users.*, auth_groups.name, auth_groups.description') @@ -91,8 +103,11 @@ public function getGroupsForUser(int $userId) { return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Permissions for Group. + * -------------------------------------------------------------------------- + * * Gets all permissions for a group in a way that can be easily used to * check against: * @@ -115,21 +130,24 @@ public function getPermissionsForGroup(int $groupId): array { $found = []; foreach ($fromGroup as $permission) { - $found[ $permission->id ] = $permission; + $found[$permission->id] = $permission; } return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Users for Group. + * -------------------------------------------------------------------------- + * * Returns an array of all users that are members of a group. * * @param int $groupId * * @return array */ - public function getUsersForGroup(int $groupId) { + public function getUsersForGroup(int $groupId): array { if (null === $found = cache("{$groupId}_users")) { $found = $this->builder() ->select('auth_groups_users.*, users.*') @@ -144,8 +162,11 @@ public function getUsersForGroup(int $groupId) { return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from Group. + * -------------------------------------------------------------------------- + * * Removes a single permission from a single group. * * @param int $permissionId @@ -153,7 +174,7 @@ public function getUsersForGroup(int $groupId) { * * @return mixed */ - public function removePermissionFromGroup(int $permissionId, int $groupId) { + public function removePermissionFromGroup(int $permissionId, int $groupId): bool { return $this->db->table('auth_groups_permissions') ->where([ 'permission_id' => $permissionId, @@ -161,40 +182,49 @@ public function removePermissionFromGroup(int $permissionId, int $groupId) { ])->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove all Permissions from Group. + * -------------------------------------------------------------------------- + * * Removes all permissions from a single group. * * @param int $groupId * * @return mixed */ - public function removeAllPermissionsFromGroup(int $groupId) { + public function removeAllPermissionsFromGroup(int $groupId): bool { return $this->db->table('auth_groups_permissions')->where([ 'group_id' => $groupId ])->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from all Groups. + * -------------------------------------------------------------------------- + * * Removes a single permission from all groups. * * @param int $permissionId * * @return mixed */ - public function removePermissionFromAllGroups(int $permissionId) { + public function removePermissionFromAllGroups(int $permissionId): bool { return $this->db->table('auth_groups_permissions')->where('permission_id', $permissionId)->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from Group. + * -------------------------------------------------------------------------- + * * Removes a single user from a single group. * - * @param int $userId + * @param int $userId * @param int|string $groupId * * @return bool */ - public function removeUserFromGroup(int $userId, $groupId) { + public function removeUserFromGroup(int $userId, $groupId): bool { cache()->delete("{$groupId}_users"); cache()->delete("{$userId}_groups"); cache()->delete("{$userId}_permissions"); @@ -202,15 +232,18 @@ public function removeUserFromGroup(int $userId, $groupId) { return $this->db->table('auth_groups_users')->where([ 'user_id' => $userId, 'group_id' => (int)$groupId ])->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from all Groups. + * -------------------------------------------------------------------------- + * * Removes a single user from all groups. * * @param int $userId * * @return bool */ - public function removeUserFromAllGroups(int $userId) { + public function removeUserFromAllGroups(int $userId): bool { cache()->delete("{$userId}_groups"); cache()->delete("{$userId}_permissions"); diff --git a/src/Authorization/PermissionModel.php b/src/Authorization/PermissionModel.php index ce5b5f3..89e0377 100644 --- a/src/Authorization/PermissionModel.php +++ b/src/Authorization/PermissionModel.php @@ -11,8 +11,11 @@ class PermissionModel extends Model { protected $allowedFields = [ 'name', 'description' ]; protected $useTimestamps = false; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add Permission to User. + * -------------------------------------------------------------------------- + * * Adds a single permission to a single user. * * @param int $permissionId @@ -20,7 +23,7 @@ class PermissionModel extends Model { * * @return bool */ - public function addPermissionToUser(int $permissionId, int $userId) { + public function addPermissionToUser(int $permissionId, int $userId): bool { cache()->delete("{$userId}_permissions"); return $this->db->table('auth_users_permissions')->insert([ @@ -29,8 +32,11 @@ public function addPermissionToUser(int $permissionId, int $userId) { ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Permission. + * -------------------------------------------------------------------------- + * * Deletes a permission. * * @param int $id Permission ID @@ -46,8 +52,11 @@ public function deletePermission(int $id) { return true; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Does User have Permission. + * -------------------------------------------------------------------------- + * * Checks if a user has a specific permission (personal, group, role). * * @param int $userId @@ -87,10 +96,13 @@ public function doesUserHavePermission(int $userId, int $permissionId): bool { return $count > 0; } - //--------------------------------------------------------------------------- /** - * Gets all permissions for a user in a way that can be easily used to check - * against: + * -------------------------------------------------------------------------- + * Get Permissions for User. + * -------------------------------------------------------------------------- + * + * Gets all personal, group and role permissions for a user in a way that can + * be easily used to check against: * * [ * id => name, @@ -140,7 +152,7 @@ public function getPermissionsForUser(int $userId): array { $found = []; foreach ($combined as $row) { - $found[ $row->id ] = strtolower($row->name); + $found[$row->id] = strtolower($row->name); } cache()->save("{$userId}_permissions", $found, 300); @@ -149,10 +161,13 @@ public function getPermissionsForUser(int $userId): array { return $found; } - //--------------------------------------------------------------------------- /** - * Gets all permissions for a user in a way that can be easily used to check - * against: + * -------------------------------------------------------------------------- + * Get Personal Permissions for User. + * -------------------------------------------------------------------------- + * + * Gets all personal permissions for a user in a way that can be easily used + * to check against: * * [ * id => name, @@ -177,7 +192,7 @@ public function getPersonalPermissionsForUser(int $userId): array { $found = []; foreach ($fromUser as $row) { - $found[ $row->id ] = strtolower($row->name); + $found[$row->id] = strtolower($row->name); } cache()->save("{$userId}_personal_permissions", $found, 300); @@ -186,8 +201,11 @@ public function getPersonalPermissionsForUser(int $userId): array { return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Groups for Permission. + * -------------------------------------------------------------------------- + * * Gets all groups that have a single permission assigned. * * @param int $permId Permission ID to check @@ -208,7 +226,7 @@ public function getGroupsForPermission(int $permId): array { $found = []; foreach ($permGroups as $row) { - $found[ $row->id ] = $row->name; + $found[$row->id] = $row->name; } cache()->save("{$permId}_permissions_groups", $found, 300); @@ -217,8 +235,11 @@ public function getGroupsForPermission(int $permId): array { return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Roles for Permission. + * -------------------------------------------------------------------------- + * * Gets all groups that have a single permission assigned. * * @param int $permId Permission ID to check @@ -239,7 +260,7 @@ public function getRolesForPermission(int $permId): array { $found = []; foreach ($permRoles as $row) { - $found[ $row->id ] = $row->name; + $found[$row->id] = $row->name; } cache()->save("{$permId}_permissions_roles", $found, 300); @@ -248,8 +269,11 @@ public function getRolesForPermission(int $permId): array { return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Users for Permission. + * -------------------------------------------------------------------------- + * * Gets all users that hold a single personal permission. * * @param int $permId Permission ID to check @@ -270,7 +294,7 @@ public function getUsersForPermission(int $permId): array { $found = []; foreach ($permUsers as $row) { - $found[ $row->id ] = $row->username; + $found[$row->id] = $row->username; } cache()->save("{$permId}_permissions_users", $found, 300); @@ -279,25 +303,31 @@ public function getUsersForPermission(int $permId): array { return $found; } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from User. + * -------------------------------------------------------------------------- + * * Removes a permission from a user. * * @param int $permissionId * @param int $userId */ - public function removePermissionFromUser(int $permissionId, int $userId) { + public function removePermissionFromUser(int $permissionId, int $userId): void { $this->db->table('auth_users_permissions')->where([ 'user_id' => $userId, 'permission_id' => $permissionId ])->delete(); cache()->delete("{$userId}_permissions"); } - //------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove all Permissions from User. + * -------------------------------------------------------------------------- + * * Removes all permissions from a user. * * @param int $userId */ - public function removeAllPermissionsFromUser(int $userId) { + public function removeAllPermissionsFromUser(int $userId): void { $this->db->table('auth_users_permissions')->where([ 'user_id' => $userId ])->delete(); cache()->delete("{$userId}_permissions"); } diff --git a/src/Authorization/RoleModel.php b/src/Authorization/RoleModel.php index 81321fa..59b996e 100644 --- a/src/Authorization/RoleModel.php +++ b/src/Authorization/RoleModel.php @@ -12,16 +12,19 @@ class RoleModel extends Model { protected $useTimestamps = false; protected $skipValidation = false; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add Permission to Role. + * -------------------------------------------------------------------------- + * * Add a single permission to a single role, by IDs. * * @param int $permissionId * @param int $roleId * - * @return mixed + * @return bool */ - public function addPermissionToRole(int $permissionId, int $roleId) { + public function addPermissionToRole(int $permissionId, int $roleId): bool { $data = [ 'role_id' => (int)$roleId, 'permission_id' => (int)$permissionId, @@ -30,8 +33,11 @@ public function addPermissionToRole(int $permissionId, int $roleId) { return $this->db->table('auth_roles_permissions')->insert($data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add User to Role. + * -------------------------------------------------------------------------- + * * Adds a single user to a single role. * * @param int $userId @@ -39,7 +45,7 @@ public function addPermissionToRole(int $permissionId, int $roleId) { * * @return bool */ - public function addUserToRole(int $userId, int $roleId) { + public function addUserToRole(int $userId, int $roleId): bool { cache()->delete("{$roleId}_users"); cache()->delete("{$userId}_roles"); cache()->delete("{$userId}_permissions"); @@ -52,15 +58,18 @@ public function addUserToRole(int $userId, int $roleId) { return (bool)$this->db->table('auth_roles_users')->insert($data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Role. + * -------------------------------------------------------------------------- + * * Deletes a role. * * @param int $id Role ID * * @return bool */ - public function deleteRole(int $id) { + public function deleteRole(int $id): bool { if (!$this->delete($id)) { $this->error = $this->errors(); return false; @@ -69,8 +78,11 @@ public function deleteRole(int $id) { return true; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Permissions for Role. + * -------------------------------------------------------------------------- + * * Gets all permissions for a role in a way that can be easily used to check * against: * @@ -93,21 +105,24 @@ public function getPermissionsForRole(int $roleId): array { $found = []; foreach ($fromRole as $permission) { - $found[ $permission->id ] = $permission; + $found[$permission->id] = $permission; } return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Roles for User. + * -------------------------------------------------------------------------- + * * Returns an array of all roles that a user is a member of. * * @param int $userId * * @return array */ - public function getRolesForUser(int $userId) { + public function getRolesForUser(int $userId): array { if (null === $found = cache("{$userId}_roles")) { $found = $this->builder() ->select('auth_roles_users.*, auth_roles.name, auth_roles.description') @@ -121,15 +136,18 @@ public function getRolesForUser(int $userId) { return $found; } - //--------------------------------------------------------------------------- /** - * Returns an array of all users that are members of a role. + * -------------------------------------------------------------------------- + * Get Users for Role. + * -------------------------------------------------------------------------- + * + * Returns an array of all users that are member of a role. * * @param int $roleId * * @return array */ - public function getUsersForRole(int $roleId) { + public function getUsersForRole(int $roleId): array { if (null === $found = cache("{$roleId}_users")) { $found = $this->builder() ->select('auth_roles_users.*, users.*') @@ -144,20 +162,26 @@ public function getUsersForRole(int $roleId) { return $found; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove all Permissions from Role. + * -------------------------------------------------------------------------- + * * Removes all permission from a single role. * * @param int $roleId * * @return mixed */ - public function removeAllPermissionsFromRole(int $roleId) { + public function removeAllPermissionsFromRole(int $roleId): bool { return $this->db->table('auth_roles_permissions')->where([ 'role_id' => $roleId ])->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from Role. + * -------------------------------------------------------------------------- + * * Removes a single permission from a single role. * * @param int $permissionId @@ -165,7 +189,7 @@ public function removeAllPermissionsFromRole(int $roleId) { * * @return mixed */ - public function removePermissionFromRole(int $permissionId, int $roleId) { + public function removePermissionFromRole(int $permissionId, int $roleId): bool { return $this->db->table('auth_roles_permissions') ->where([ 'permission_id' => $permissionId, @@ -173,28 +197,34 @@ public function removePermissionFromRole(int $permissionId, int $roleId) { ])->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove Permission from all Roles. + * -------------------------------------------------------------------------- + * * Removes a single permission from all roles. * * @param int $permissionId * * @return mixed */ - public function removePermissionFromAllRoles(int $permissionId) { + public function removePermissionFromAllRoles(int $permissionId): bool { return $this->db->table('auth_roles_permissions')->where('permission_id', $permissionId)->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from Role. + * -------------------------------------------------------------------------- + * * Removes a single user from a single role. * - * @param int $userId + * @param int $userId * @param int|string $roleId * * @return bool */ - public function removeUserFromRole(int $userId, $roleId) { + public function removeUserFromRole(int $userId, $roleId): bool { cache()->delete("{$roleId}_users"); cache()->delete("{$userId}_roles"); cache()->delete("{$userId}_permissions"); @@ -202,15 +232,18 @@ public function removeUserFromRole(int $userId, $roleId) { return $this->db->table('auth_roles_users')->where([ 'user_id' => $userId, 'role_id' => (int)$roleId ])->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remove User from all Roles. + * -------------------------------------------------------------------------- + * * Removes a single user from all roles. * * @param int $userId * * @return bool */ - public function removeUserFromAllRoles(int $userId) { + public function removeUserFromAllRoles(int $userId): bool { cache()->delete("{$userId}_roles"); cache()->delete("{$userId}_permissions"); diff --git a/src/Collectors/Auth.php b/src/Collectors/Auth.php index f0acd27..333c113 100644 --- a/src/Collectors/Auth.php +++ b/src/Collectors/Auth.php @@ -42,8 +42,11 @@ class Auth extends BaseCollector { */ protected $title = 'Auth'; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Title Details. + * -------------------------------------------------------------------------- + * * Returns any information that should be shown next to the title. * * @return string @@ -52,8 +55,11 @@ public function getTitleDetails(): string { return get_class(service('authentication')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Display. + * -------------------------------------------------------------------------- + * * Returns the data of this collector to be formatted in the toolbar * * @return string @@ -84,8 +90,11 @@ public function display(): string { return $html; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Badge Value. + * -------------------------------------------------------------------------- + * * Gets the "badge" value for the button. * * @return int|null ID of the current User, or null when not logged in @@ -94,8 +103,11 @@ public function getBadgeValue(): ?int { return service('authentication')->isLoggedIn() ? service('authentication')->id() : null; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Title Details. + * -------------------------------------------------------------------------- + * * Display the icon. * * Icon from https://icons8.com - 1em package diff --git a/src/Commands/ActivateUser.php b/src/Commands/ActivateUser.php index 0d7d4c2..bdd6df1 100644 --- a/src/Commands/ActivateUser.php +++ b/src/Commands/ActivateUser.php @@ -16,8 +16,11 @@ class ActivateUser extends BaseCommand { 'identity' => 'User identity.', ]; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * This method is responsible for activating a user in the system. * It takes an array of parameters as input, which should contain the user's identity. * If the identity is not provided, it prompts the user to enter it. @@ -29,8 +32,10 @@ class ActivateUser extends BaseCommand { * If the activation fails, it outputs a failure message. * * @param array $params An array of parameters. The first element should be the user's identity. + * + * @return void */ - public function run(array $params = []) { + public function run(array $params = []): void { // Consume or prompt for password $identity = array_shift($params); diff --git a/src/Commands/CreateRole.php b/src/Commands/CreateRole.php index 4307429..23bbf82 100644 --- a/src/Commands/CreateRole.php +++ b/src/Commands/CreateRole.php @@ -17,8 +17,11 @@ class CreateRole extends BaseCommand { 'description' => "Optional description 'in quotes'", ]; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * This method is responsible for creating a new role in the system. * It takes an array of parameters as input, which should contain the role's * name and description. diff --git a/src/Commands/CreateUser.php b/src/Commands/CreateUser.php index 9659345..5f531c3 100644 --- a/src/Commands/CreateUser.php +++ b/src/Commands/CreateUser.php @@ -18,8 +18,11 @@ class CreateUser extends BaseCommand { 'email' => "The email address of the new user to create", ]; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * This method is responsible for creating a new user in the system. * It takes an array of parameters as input, which should contain the user's username and email. * If the username is not provided, it prompts the user to enter it. @@ -40,15 +43,15 @@ public function run(array $params = []) { ]; // Consume or prompt for username - $row[ 'username' ] = array_shift($params); - if (empty($row[ 'username' ])) { - $row[ 'username' ] = CLI::prompt('Username', null, 'required'); + $row['username'] = array_shift($params); + if (empty($row['username'])) { + $row['username'] = CLI::prompt('Username', null, 'required'); } // Consume or prompt for email - $row[ 'email' ] = array_shift($params); - if (empty($row[ 'email' ])) { - $row[ 'email' ] = CLI::prompt('Email', null, 'required'); + $row['email'] = array_shift($params); + if (empty($row['email'])) { + $row['email'] = CLI::prompt('Email', null, 'required'); } // Run the user through the entity and insert it @@ -56,7 +59,7 @@ public function run(array $params = []) { $users = model(UserModel::class); if ($userId = $users->insert($user)) { - CLI::write(lang('Auth.register.create_success', [ $row[ 'username' ], $userId ]), 'green'); + CLI::write(lang('Auth.register.create_success', [ $row['username'], $userId ]), 'green'); } else { foreach ($users->errors() as $message) { CLI::write($message, 'red'); diff --git a/src/Commands/HashPassword.php b/src/Commands/HashPassword.php index 78cc789..07827ff 100644 --- a/src/Commands/HashPassword.php +++ b/src/Commands/HashPassword.php @@ -16,8 +16,11 @@ class HashPassword extends BaseCommand { 'password' => 'Password value you want to hash.', ]; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * This method is responsible for hashing a given password. * It takes an array of parameters as input, which should contain the password. * If the password is not provided, it prompts the user to enter it. diff --git a/src/Commands/ListRoles.php b/src/Commands/ListRoles.php index d8b94a9..5e3f423 100644 --- a/src/Commands/ListRoles.php +++ b/src/Commands/ListRoles.php @@ -12,8 +12,11 @@ class ListRoles extends BaseCommand { protected $description = 'Lists roles from the database.'; protected $usage = 'auth:list_roles'; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * This method is responsible for listing all the roles from the database. * It does not require any parameters. * It first establishes a connection to the database. diff --git a/src/Commands/Publish.php b/src/Commands/Publish.php index 0ebe08a..5ec13e1 100644 --- a/src/Commands/Publish.php +++ b/src/Commands/Publish.php @@ -66,8 +66,11 @@ class Publish extends BaseCommand { */ protected $viewsPublished = false; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * Displays the help for the spark cli script itself. * * @param array $params @@ -244,8 +247,11 @@ protected function publishLanguage() { // Utilities //--------------------------------------------------------------------------- - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Replace Namespace. + * -------------------------------------------------------------------------- + * * Replaces the Lewe\Auth namespace in the published * file with the applications current namespace. * @@ -263,8 +269,11 @@ protected function replaceNamespace(string $contents, string $originalNamespace, return str_replace($originalNamespace, $newNamespace, $contents); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Determine Source Path. + * -------------------------------------------------------------------------- + * * Determines the current source path from which all other files are located. */ protected function determineSourcePath() { @@ -276,17 +285,22 @@ protected function determineSourcePath() { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Write File. + * -------------------------------------------------------------------------- + * * Write a file, catching any exceptions and showing a * nicely formatted error. * * @param string $path * @param string $content + * + * @return void */ - protected function writeFile(string $path, string $content) { + protected function writeFile(string $path, string $content): void { $config = new Autoload(); - $appPath = $config->psr4[ APP_NAMESPACE ]; + $appPath = $config->psr4[APP_NAMESPACE]; $filename = $appPath . $path; $directory = dirname($filename); diff --git a/src/Commands/SetPassword.php b/src/Commands/SetPassword.php index d9e1488..8f9828b 100644 --- a/src/Commands/SetPassword.php +++ b/src/Commands/SetPassword.php @@ -17,8 +17,11 @@ class SetPassword extends BaseCommand { 'password' => 'Password value you want to set.', ]; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Run. + * -------------------------------------------------------------------------- + * * This method is responsible for setting a new password for a user. * It takes an array of parameters as input, which should contain the user's identity and the new password. * If the identity is not provided, it prompts the user to enter it. @@ -34,8 +37,8 @@ class SetPassword extends BaseCommand { */ public function run(array $params = []) { // Consume or prompt for password - $identity = isset($params[ 0 ]) ? $params[ 0 ] : null; - $password = isset($params[ 1 ]) ? $params[ 1 ] : null; + $identity = isset($params[0]) ? $params[0] : null; + $password = isset($params[1]) ? $params[1] : null; if (empty($identity)) { $identity = CLI::prompt('Identity', null, 'required'); diff --git a/src/Config/AuthInfo.php b/src/Config/AuthInfo.php index 4cb657c..42b68de 100644 --- a/src/Config/AuthInfo.php +++ b/src/Config/AuthInfo.php @@ -21,7 +21,7 @@ class AuthInfo extends BaseConfig { * * @var string */ - public $version = '3.5.1'; + public $version = '3.6.0'; /** * -------------------------------------------------------------------------- diff --git a/src/Controllers/AuthController.php b/src/Controllers/AuthController.php index fe75024..227a609 100644 --- a/src/Controllers/AuthController.php +++ b/src/Controllers/AuthController.php @@ -8,6 +8,7 @@ use CI4\Auth\Config\Auth as AuthConfig; use CI4\Auth\Entities\User; use CI4\Auth\Models\UserModel; +use Exception; use RobThree\Auth\TwoFactorAuth; use App\Controllers\BaseController; @@ -48,9 +49,10 @@ class AuthController extends BaseController { */ protected $passphrase; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- * Constructor. + * -------------------------------------------------------------------------- */ public function __construct() { // @@ -64,13 +66,14 @@ public function __construct() { $this->passphrase = hex2bin('8849523a8e0e1ff45f440da048428b2554d2660c80957fcedbeb9575c079d7eb'); } - //--------------------------------------------------------------------------- /** - * Activate account. + * -------------------------------------------------------------------------- + * Activate Account. + * -------------------------------------------------------------------------- * * @return mixed */ - public function activateAccount() { + public function activateAccount(): mixed { $users = model(UserModel::class); // @@ -98,13 +101,16 @@ public function activateAccount() { return redirect()->route('login')->with('message', lang('Auth.register.success')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Activate Account Resend. + * -------------------------------------------------------------------------- + * * Resend activation account. * * @return mixed */ - public function activateAccountResend() { + public function activateAccountResend(): mixed { if ($this->authConfig->requireActivation === null) { return redirect()->route('login'); } @@ -139,32 +145,45 @@ public function activateAccountResend() { return redirect()->route('login')->with('message', lang('Auth.activation.success')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Error. + * -------------------------------------------------------------------------- + * * Displays the CI4-Auth error page. */ - public function error() { - return $this->_render($this->authConfig->views[ 'error_auth' ], [ 'config' => $this->authConfig ]); + public function error(): mixed { + return $this->_render($this->authConfig->views['error_auth'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Forgot Password. + * -------------------------------------------------------------------------- + * * Displays the forgot password form. + * + * @return mixed */ - public function forgotPassword() { + public function forgotPassword(): mixed { if ($this->authConfig->activeResetter === null) { return redirect()->route('login')->with('error', lang('Auth.forgot.disabled')); } - return $this->_render($this->authConfig->views[ 'forgot' ], [ 'config' => $this->authConfig ]); + return $this->_render($this->authConfig->views['forgot'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Forgot Password Do. + * -------------------------------------------------------------------------- + * * Attempts to find a user account with the given email address and sends * password reset instructions to them. + * + * @return mixed */ - public function forgotPasswordDo() { + public function forgotPasswordDo(): mixed { if ($this->authConfig->activeResetter === null) { return redirect()->route('login')->with('error', lang('Auth.forgot.disabled')); } @@ -193,41 +212,51 @@ public function forgotPasswordDo() { return redirect()->route('reset-password')->with('message', lang('Auth.forgot.email_sent')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Login. + * -------------------------------------------------------------------------- + * * Displays the login form, or redirects the user to their destination/home * if they are already logged in. + * + * @return mixed */ - public function login() { + public function login(): mixed { // // No need to show a login form if the user is already logged in. // if ($this->auth->check()) { $redirectURL = session('redirect_url') ?? site_url('/'); - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL); } // // Set a return URL if none is specified // - $_SESSION[ 'redirect_url' ] = session('redirect_url') ?? previous_url() ?? site_url('/'); + $_SESSION['redirect_url'] = session('redirect_url') ?? previous_url() ?? site_url('/'); - return $this->_render($this->authConfig->views[ 'login' ], [ 'config' => $this->authConfig ]); + return $this->_render($this->authConfig->views['login'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Login Do. + * -------------------------------------------------------------------------- + * * Attempts to verify the user's credentials through a POST request. + * + * @return mixed */ - public function loginDo() { + public function loginDo(): mixed { $rules = [ 'login' => 'required', 'password' => 'required', ]; if ($this->authConfig->validFields == [ 'email' ]) { - $rules[ 'login' ] .= '|valid_email'; + $rules['login'] .= '|valid_email'; } if (!$this->validate($rules)) { @@ -283,7 +312,7 @@ public function loginDo() { // session()->set('2fa_setup_required', $user->email); $redirectURL = site_url('/setup2fa'); - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL)->withCookies(); } else { // @@ -291,23 +320,28 @@ public function loginDo() { // $this->auth->login($user, $remember); $redirectURL = session('redirect_url') ?? site_url('/'); - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL)->withCookies()->with('message', lang('Auth.login.success')); } } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Login 2FA. + * -------------------------------------------------------------------------- + * * Displays the 2FA login page. + * + * @return mixed */ - public function login2fa() { + public function login2fa(): mixed { // // Redirect back if already logged in // if ($this->auth->check()) { $redirectURL = session('redirect_url') ?? site_url('/'); - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL); } @@ -316,7 +350,7 @@ public function login2fa() { // if (!session('2fa_in_progress')) { $redirectURL = session('redirect_url') ?? site_url('/'); - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL); } @@ -329,7 +363,7 @@ public function login2fa() { $user = $users->where('email', session('2fa_in_progress'))->first(); return $this->_render( - $this->authConfig->views[ 'login2fa' ], + $this->authConfig->views['login2fa'], [ 'config' => $this->authConfig, 'user' => $user, @@ -338,11 +372,16 @@ public function login2fa() { ); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Login 2FA Do. + * -------------------------------------------------------------------------- + * * Attempts to verify the user's 2FA PIN through a POST request. + * + * @return mixed */ - public function login2faDo() { + public function login2faDo(): mixed { $rules = [ 'pin' => 'required|numeric', ]; @@ -360,7 +399,7 @@ public function login2faDo() { // if (!session('2fa_in_progress')) { $redirectURL = session('redirect_url') ?? site_url('/'); - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL)->withCookies()->with('errors', lang('Auth.2fa.login.no_2fa_in_progress')); } // @@ -382,9 +421,9 @@ public function login2faDo() { // $this->auth->login($user, session('ci4auth-remember')); $redirectURL = session('redirect_url') ?? site_url('/'); - unset($_SESSION[ 'redirect_url' ]); - unset($_SESSION[ '2fa_in_progress' ]); - unset($_SESSION[ 'ci4auth-remember' ]); + unset($_SESSION['redirect_url']); + unset($_SESSION['2fa_in_progress']); + unset($_SESSION['ci4auth-remember']); return redirect()->to($redirectURL)->withCookies()->with('message', lang('Auth.login.success')); } else { // @@ -393,7 +432,7 @@ public function login2faDo() { $qrcode = $this->tfa->getQRCodeImageAsDataUri($user->email, $secret); session()->setFlashdata('error', lang('Auth.2fa.setup.mismatch')); return $this->_render( - $this->authConfig->views[ 'login2fa' ], + $this->authConfig->views['login2fa'], [ 'config' => $this->authConfig, 'user' => $user, @@ -409,20 +448,30 @@ public function login2faDo() { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Logout. + * -------------------------------------------------------------------------- + * * Log the user out. + * + * @return mixed */ - public function logout() { + public function logout(): mixed { if ($this->auth->check()) $this->auth->logout(); return redirect()->to(site_url('/')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Register. + * -------------------------------------------------------------------------- + * * Displays the user registration page. + * + * @return mixed */ - public function register() { + public function register(): mixed { // // Redirect back if already logged in // @@ -433,14 +482,19 @@ public function register() { // if (!$this->authConfig->allowRegistration) return redirect()->back()->withInput()->with('error', lang('Auth.register.disabled')); - return $this->_render($this->authConfig->views[ 'register' ], [ 'config' => $this->authConfig ]); + return $this->_render($this->authConfig->views['register'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Register Do. + * -------------------------------------------------------------------------- + * * Attempt to register a new user. + * + * @return mixed */ - public function registerDo() { + public function registerDo(): mixed { // // Check if registration is allowed // @@ -502,31 +556,39 @@ public function registerDo() { return redirect()->route('login')->with('message', lang('Auth.register.success')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Reset Password. + * -------------------------------------------------------------------------- + * * Displays the Reset Password form. + * + * @return mixed */ - public function resetPassword() { + public function resetPassword(): mixed { if ($this->authConfig->activeResetter === null) { return redirect()->route('login')->with('error', lang('Auth.forgot.disabled')); } $token = $this->request->getGet('token'); - return $this->_render($this->authConfig->views[ 'reset' ], [ + return $this->_render($this->authConfig->views['reset'], [ 'config' => $this->authConfig, 'token' => $token, ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Reset Password Do. + * -------------------------------------------------------------------------- + * * Verifies the code with the email and saves the new password, * if they all pass validation. * * @return mixed */ - public function resetPasswordDo() { + public function resetPasswordDo(): mixed { if ($this->authConfig->activeResetter === null) { return redirect()->route('login')->with('error', lang('Auth.forgot.disabled')); } @@ -618,13 +680,18 @@ public function resetPasswordDo() { return redirect()->route('login')->with('message', lang('Auth.forgot.reset_success')); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Setup 2FA. + * -------------------------------------------------------------------------- + * * Displays the 2FA setup page. * * @param string $secret - Optional, to show the same QR code on wrong verify + * + * @return mixed */ - public function setup2fa($secret = null) { + public function setup2fa($secret = null): mixed { // // Redirect back if not logged in and no forced 2FA setup is in progress // @@ -660,7 +727,7 @@ public function setup2fa($secret = null) { // Render the page // return $this->_render( - $this->authConfig->views[ 'setup2fa' ], + $this->authConfig->views['setup2fa'], [ 'config' => $this->authConfig, 'qrcode' => $qrcode, @@ -671,11 +738,16 @@ public function setup2fa($secret = null) { ); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Setup 2FA Do. + * -------------------------------------------------------------------------- + * * Attempt to setup 2FA for a user. + * + * @return mixed */ - public function setup2faDo() { + public function setup2faDo(): mixed { $users = model(UserModel::class); $user = $users->where('email', $this->request->getPost('hidden_email'))->first(); @@ -715,10 +787,10 @@ public function setup2faDo() { $remember = session('ci4auth-remember'); } $this->auth->login($user, $remember); - unset($_SESSION[ 'redirect_url' ]); - unset($_SESSION[ '2fa_in_progress' ]); - unset($_SESSION[ '2fa_setup_progress' ]); - unset($_SESSION[ 'ci4auth-remember' ]); + unset($_SESSION['redirect_url']); + unset($_SESSION['2fa_in_progress']); + unset($_SESSION['2fa_setup_progress']); + unset($_SESSION['ci4auth-remember']); } return redirect()->route('/')->with('message', lang('Auth.2fa.setup.success')); } else { @@ -728,7 +800,7 @@ public function setup2faDo() { $qrcode = $this->tfa->getQRCodeImageAsDataUri($user->email, $secret); session()->setFlashdata('error', lang('Auth.2fa.setup.mismatch')); return $this->_render( - $this->authConfig->views[ 'setup2fa' ], + $this->authConfig->views['setup2fa'], [ 'config' => $this->authConfig, 'qrcode' => $qrcode, @@ -746,39 +818,58 @@ public function setup2faDo() { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * About. + * -------------------------------------------------------------------------- + * * Displays the About page. + * + * @return mixed */ - public function about() { - return $this->_render($this->authConfig->views[ 'about' ], [ 'config' => $this->authConfig ]); + public function about(): mixed { + return $this->_render($this->authConfig->views['about'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Welcome. + * -------------------------------------------------------------------------- + * * Displays the Welcome page. + * + * @return mixed */ - public function welcome() { - return $this->_render($this->authConfig->views[ 'welcome' ], [ 'config' => $this->authConfig ]); + public function welcome(): mixed { + return $this->_render($this->authConfig->views['welcome'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * WhoAmI. + * -------------------------------------------------------------------------- + * * Displays the Whoami page. + * + * @return mixed */ - public function whoami() { - return $this->_render($this->authConfig->views[ 'whoami' ], [ 'config' => $this->authConfig ]); + public function whoami(): mixed { + return $this->_render($this->authConfig->views['whoami'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Encrypt. + * -------------------------------------------------------------------------- + * * Encrypts (but does not authenticate) a string. * - * @param string $plaintext - String to encrypt - * @param boolean $encode - Return base64-encoded or not + * @param string $plaintext - String to encrypt + * @param boolean $encode - Return base64-encoded or not + * * @return string */ - protected function encrypt($plaintext, $encode = false) { + protected function encrypt($plaintext, $encode = false): string { $nonceSize = openssl_cipher_iv_length($this->cipher); $nonce = openssl_random_pseudo_bytes($nonceSize); @@ -800,15 +891,19 @@ protected function encrypt($plaintext, $encode = false) { return $nonce . $ciphertext; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Decrypt. + * -------------------------------------------------------------------------- + * * Decrypts (but does not verify) an encrypted string. * - * @param string $ciphertext - Encrypted string - * @param boolean $encoded - Is base64 encoded string submitted or not? + * @param string $ciphertext - Encrypted string + * @param boolean $encoded - Is base64 encoded string submitted or not? + * * @return string */ - protected function decrypt($ciphertext, $encoded = false) { + protected function decrypt($ciphertext, $encoded = false): string { if ($encoded) { $message = base64_decode($ciphertext, true); if ($message === false) { @@ -831,16 +926,19 @@ protected function decrypt($ciphertext, $encoded = false) { return $plaintext; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Render. + * -------------------------------------------------------------------------- + * * Render View. * * @param string $view - * @param array $data + * @param array $data * * @return string */ - protected function _render(string $view, array $data = []) { + protected function _render(string $view, array $data = []): string { // // In case you have a custom configuration that you want to pass to // your views (e.g. theme settings), it is added here. @@ -848,7 +946,7 @@ protected function _render(string $view, array $data = []) { // It is assumed that have declared and set the variable $myConfig in // your BaseController. // - if (isset($this->myConfig)) $data[ 'myConfig' ] = $this->myConfig; + if (isset($this->myConfig)) $data['myConfig'] = $this->myConfig; return view($view, $data); } diff --git a/src/Controllers/GroupController.php b/src/Controllers/GroupController.php index 768bf83..aadcfc0 100644 --- a/src/Controllers/GroupController.php +++ b/src/Controllers/GroupController.php @@ -28,9 +28,10 @@ class GroupController extends BaseController { */ protected $validation; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- * Constructor. + * -------------------------------------------------------------------------- */ public function __construct() { // @@ -42,13 +43,16 @@ public function __construct() { $this->validation = service('validation'); } - // ------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Groups. + * -------------------------------------------------------------------------- + * * Shows all user records. * * @return \CodeIgniter\HTTP\RedirectResponse | string */ - public function groups() { + public function groups(): string { $groups = model(GroupModel::class); $allGroups = $groups->orderBy('name', 'asc')->findAll(); @@ -58,9 +62,9 @@ public function groups() { ]; foreach ($allGroups as $group) { - $groupPermissions[ $group->id ][] = $groups->getPermissionsForGroup($group->id); + $groupPermissions[$group->id][] = $groups->getPermissionsForGroup($group->id); } - $data[ 'groupPermissions' ] = $groupPermissions; + $data['groupPermissions'] = $groupPermissions; if ($this->request->withMethod('post')) { // @@ -79,7 +83,7 @@ public function groups() { if (!$groups->deleteGroup($recId)) { $this->session->set('errors', $groups->errors()); - return $this->_render($this->authConfig->views[ 'groups' ], $data); + return $this->_render($this->authConfig->views['groups'], $data); } return redirect()->route('groups')->with('success', lang('Auth.group.delete_success', [ $group->name ])); } @@ -89,40 +93,46 @@ public function groups() { // $search = $this->request->getPost('search'); $where = '`name` LIKE "%' . $search . '%" OR `description` LIKE "%' . $search . '%"';; - $data[ 'groups' ] = $groups->where($where)->orderBy('name', 'asc')->findAll(); - $data[ 'search' ] = $search; + $data['groups'] = $groups->where($where)->orderBy('name', 'asc')->findAll(); + $data['search'] = $search; } } - return $this->_render($this->authConfig->views[ 'groups' ], $data); + return $this->_render($this->authConfig->views['groups'], $data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Groups Create. + * -------------------------------------------------------------------------- + * * Displays the user create page. * * @return string */ public function groupsCreate($id = null): string { - return $this->_render($this->authConfig->views[ 'groupsCreate' ], [ 'config' => $this->authConfig ]); + return $this->_render($this->authConfig->views['groupsCreate'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Groups Create Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new user. * To be be used by administrators. User will be activated automatically. * * @return \CodeIgniter\HTTP\RedirectResponse */ - public function groupsCreateDo() { + public function groupsCreateDo(): \CodeIgniter\HTTP\RedirectResponse { $groups = model(GroupModel::class); $form = array(); // // Get form fields // - $form[ 'name' ] = $this->request->getPost('name'); - $form[ 'description' ] = $this->request->getPost('description'); + $form['name'] = $this->request->getPost('name'); + $form['description'] = $this->request->getPost('description'); // // Set validation rules for adding a new group @@ -132,7 +142,7 @@ public function groupsCreateDo() { 'label' => lang('Auth.group.name'), 'rules' => 'required|trim|max_length[255]|is_unique[auth_groups.name]', 'errors' => [ - 'is_unique' => lang('Auth.group.not_unique', [ $form[ 'name' ] ]) + 'is_unique' => lang('Auth.group.not_unique', [ $form['name'] ]) ] ], 'description' => [ @@ -165,13 +175,18 @@ public function groupsCreateDo() { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Groups Edit. + * -------------------------------------------------------------------------- + * * Displays the user edit page. * * @param int $id Group ID + * + * @return string */ - public function groupsEdit($id = null) { + public function groupsEdit($id = null): string { $groups = model(GroupModel::class); if (!$group = $groups->where('id', $id)->first()) return redirect()->to('groups'); @@ -179,7 +194,7 @@ public function groupsEdit($id = null) { $permissions = $this->auth->permissions(); $groupPermissions = $groups->getPermissionsForGroup($id); - return $this->_render($this->authConfig->views[ 'groupsEdit' ], [ + return $this->_render($this->authConfig->views['groupsEdit'], [ 'config' => $this->authConfig, 'group' => $group, 'permissions' => $permissions, @@ -187,13 +202,18 @@ public function groupsEdit($id = null) { ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Groups Edit Do. + * -------------------------------------------------------------------------- + * * Attempt to edit a group. * * @param int $id Group ID + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function groupsEditDo($id = null) { + public function groupsEditDo($id = null): \CodeIgniter\HTTP\RedirectResponse { $groups = model(GroupModel::class); $form = array(); @@ -219,18 +239,18 @@ public function groupsEditDo($id = null) { // // Get form fields // - $form[ 'name' ] = $this->request->getPost('name'); - $form[ 'description' ] = $this->request->getPost('description'); + $form['name'] = $this->request->getPost('name'); + $form['description'] = $this->request->getPost('description'); // // If the group name changed, make sure the validator checks its uniqueness. // - if ($form[ 'name' ] != $group->name) { - $validationRules[ 'name' ] = [ + if ($form['name'] != $group->name) { + $validationRules['name'] = [ 'label' => lang('Auth.group.name'), 'rules' => 'required|trim|max_length[255]|is_unique[auth_groups.name]', 'errors' => [ - 'is_unique' => lang('Auth.group.not_unique', [ $form[ 'name' ] ]) + 'is_unique' => lang('Auth.group.not_unique', [ $form['name'] ]) ] ]; } @@ -266,16 +286,19 @@ public function groupsEditDo($id = null) { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Render. + * -------------------------------------------------------------------------- + * * Render View. * * @param string $view - * @param array $data + * @param array $data * * @return string */ - protected function _render(string $view, array $data = []) { + protected function _render(string $view, array $data = []): string { // // In case you have a custom configuration that you want to pass to // your views (e.g. theme settings), it is added here. @@ -283,7 +306,7 @@ protected function _render(string $view, array $data = []) { // It is assumed that have declared and set the variable $myConfig in // your BaseController. // - if (isset($this->myConfig)) $data[ 'myConfig' ] = $this->myConfig; + if (isset($this->myConfig)) $data['myConfig'] = $this->myConfig; return view($view, $data); } diff --git a/src/Controllers/PermissionController.php b/src/Controllers/PermissionController.php index fa616f7..0b1a1ca 100644 --- a/src/Controllers/PermissionController.php +++ b/src/Controllers/PermissionController.php @@ -28,9 +28,10 @@ class PermissionController extends BaseController { */ protected $validation; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- * Constructor. + * -------------------------------------------------------------------------- */ public function __construct() { // @@ -42,13 +43,16 @@ public function __construct() { $this->validation = service('validation'); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permissions. + * -------------------------------------------------------------------------- + * * Shows all permission records. * * @return \CodeIgniter\HTTP\RedirectResponse | string */ - public function permissions() { + public function permissions(): \CodeIgniter\HTTP\RedirectResponse|string { $permissions = model(PermissionModel::class); $data = [ @@ -70,7 +74,7 @@ public function permissions() { } else { if (!$permissions->deletePermission($recId)) { $this->session->set('errors', $permissions->errors()); - return $this->_render($this->authConfig->views[ 'permissions' ], $data); + return $this->_render($this->authConfig->views['permissions'], $data); } return redirect()->route('permissions')->with('success', lang('Auth.permission.delete_success', [ $permission->name ])); } @@ -80,39 +84,51 @@ public function permissions() { // $search = $this->request->getPost('search'); $where = '`name` LIKE "%' . $search . '%" OR `description` LIKE "%' . $search . '%"';; - $data[ 'permissions' ] = $permissions->where($where)->orderBy('name', 'asc')->findAll(); - $data[ 'search' ] = $search; + $data['permissions'] = $permissions->where($where)->orderBy('name', 'asc')->findAll(); + $data['search'] = $search; } } // // Show the list view // - return $this->_render($this->authConfig->views[ 'permissions' ], $data); + return $this->_render($this->authConfig->views['permissions'], $data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permissions Create. + * -------------------------------------------------------------------------- + * * Displays the user create page. + * + * @param int $id Permission ID + * + * @return string */ - public function permissionsCreate($id = null) { - return $this->_render($this->authConfig->views[ 'permissionsCreate' ], [ 'config' => $this->authConfig ]); + public function permissionsCreate($id = null): string { + return $this->_render($this->authConfig->views['permissionsCreate'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permissions Create Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new user. * To be be used by administrators. User will be activated automatically. + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function permissionsCreateDo() { + public function permissionsCreateDo(): \CodeIgniter\HTTP\RedirectResponse { $permissions = model(PermissionModel::class); $form = array(); // // Get form fields // - $form[ 'name' ] = $this->request->getPost('name'); - $form[ 'description' ] = $this->request->getPost('description'); + $form['name'] = $this->request->getPost('name'); + $form['description'] = $this->request->getPost('description'); // // Set validation rules for adding a new group @@ -122,7 +138,7 @@ public function permissionsCreateDo() { 'label' => lang('Auth.permission.name'), 'rules' => 'required|trim|max_length[255]|lower_alpha_dash_dot|is_unique[auth_permissions.name]', 'errors' => [ - 'is_unique' => lang('Auth.permission.not_unique', [ $form[ 'name' ] ]) + 'is_unique' => lang('Auth.permission.not_unique', [ $form['name'] ]) ] ], 'description' => [ @@ -155,13 +171,18 @@ public function permissionsCreateDo() { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permissions Edit. + * -------------------------------------------------------------------------- + * * Displays the user edit page. * * @param int $id Permission ID + * + * @return \CodeIgniter\HTTP\RedirectResponse|string */ - public function permissionsEdit($id = null) { + public function permissionsEdit($id = null): \CodeIgniter\HTTP\RedirectResponse|string { $permissions = model(PermissionModel::class); if (!$permission = $permissions->where('id', $id)->first()) return redirect()->to('permissions'); @@ -169,7 +190,7 @@ public function permissionsEdit($id = null) { $permRoles = $permissions->getRolesForPermission($id); $permUsers = $permissions->getUsersForPermission($id); - return $this->_render($this->authConfig->views[ 'permissionsEdit' ], [ + return $this->_render($this->authConfig->views['permissionsEdit'], [ 'config' => $this->authConfig, 'permission' => $permission, 'permGroups' => $permGroups, @@ -178,13 +199,18 @@ public function permissionsEdit($id = null) { ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Permissions Edit Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new permission. * * @param int $id Permission ID + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function permissionsEditDo($id = null) { + public function permissionsEditDo($id = null): \CodeIgniter\HTTP\RedirectResponse { $permissions = model(PermissionModel::class); $form = array(); @@ -210,18 +236,18 @@ public function permissionsEditDo($id = null) { // // Get form fields // - $form[ 'name' ] = $this->request->getPost('name'); - $form[ 'description' ] = $this->request->getPost('description'); + $form['name'] = $this->request->getPost('name'); + $form['description'] = $this->request->getPost('description'); // // If the permission name changed, make sure the validator checks its uniqueness. // - if ($form[ 'name' ] != $permission->name) { - $validationRules[ 'name' ] = [ + if ($form['name'] != $permission->name) { + $validationRules['name'] = [ 'label' => lang('Auth.permission.name'), 'rules' => 'required|trim|max_length[255]|lower_alpha_dash_dot|is_unique[auth_permissions.name]', 'errors' => [ - 'is_unique' => lang('Auth.permission.not_unique', [ $form[ 'name' ] ]) + 'is_unique' => lang('Auth.permission.not_unique', [ $form['name'] ]) ] ]; } @@ -239,7 +265,7 @@ public function permissionsEditDo($id = null) { // // Save the permission // - $id = $this->auth->updatePermission($id, strtolower($form[ 'name' ]), $form[ 'description' ]); + $id = $this->auth->updatePermission($id, strtolower($form['name']), $form['description']); if (!$id) return redirect()->back()->withInput()->with('errors', $permissions->errors()); // @@ -249,28 +275,34 @@ public function permissionsEditDo($id = null) { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * _Format Permission. + * -------------------------------------------------------------------------- + * * Format permission name. * * @param string $name * * @return string */ - protected function _formatPermission(string $name) { + protected function _formatPermission(string $name): string { return ""; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Render. + * -------------------------------------------------------------------------- + * * Render View. * * @param string $view - * @param array $data + * @param array $data * * @return string */ - protected function _render(string $view, array $data = []) { + protected function _render(string $view, array $data = []): string { // // In case you have a custom configuration that you want to pass to // your views (e.g. theme settings), it is added here. @@ -278,7 +310,7 @@ protected function _render(string $view, array $data = []) { // It is assumed that have declared and set the variable $myConfig in // your BaseController. // - if (isset($this->myConfig)) $data[ 'myConfig' ] = $this->myConfig; + if (isset($this->myConfig)) $data['myConfig'] = $this->myConfig; return view($view, $data); } diff --git a/src/Controllers/RoleController.php b/src/Controllers/RoleController.php index 0f27b89..0d206b4 100644 --- a/src/Controllers/RoleController.php +++ b/src/Controllers/RoleController.php @@ -28,9 +28,10 @@ class RoleController extends BaseController { */ protected $validation; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- * Constructor. + * -------------------------------------------------------------------------- */ public function __construct() { // @@ -42,13 +43,16 @@ public function __construct() { $this->validation = service('validation'); } - //----------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Roles. + * -------------------------------------------------------------------------- + * * Shows all role records. * * @return \CodeIgniter\HTTP\RedirectResponse | string */ - public function roles() { + public function roles(): \CodeIgniter\HTTP\RedirectResponse|string { $roles = model(RoleModel::class); $allRoles = $roles->orderBy('name', 'asc')->findAll(); @@ -58,9 +62,9 @@ public function roles() { ]; foreach ($allRoles as $role) { - $rolePermissions[ $role->id ][] = $roles->getPermissionsForRole($role->id); + $rolePermissions[$role->id][] = $roles->getPermissionsForRole($role->id); } - $data[ 'rolePermissions' ] = $rolePermissions; + $data['rolePermissions'] = $rolePermissions; if ($this->request->withMethod('post')) { // @@ -76,7 +80,7 @@ public function roles() { } else { if (!$roles->deleteRole($recId)) { $this->session->set('errors', $roles->errors()); - return $this->_render($this->authConfig->views[ 'roles' ], $data); + return $this->_render($this->authConfig->views['roles'], $data); } return redirect()->route('roles')->with('success', lang('Auth.role.delete_success', [ $role->name ])); } @@ -86,36 +90,48 @@ public function roles() { // $search = $this->request->getPost('search'); $where = '`name` LIKE "%' . $search . '%" OR `description` LIKE "%' . $search . '%"'; - $data[ 'roles' ] = $roles->where($where)->orderBy('name', 'asc')->findAll(); - $data[ 'search' ] = $search; + $data['roles'] = $roles->where($where)->orderBy('name', 'asc')->findAll(); + $data['search'] = $search; } } - return $this->_render($this->authConfig->views[ 'roles' ], $data); + return $this->_render($this->authConfig->views['roles'], $data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Roles Create. + * -------------------------------------------------------------------------- + * * Displays the user create page. + * + * @param int $id Role ID + * + * @return string */ - public function rolesCreate($id = null) { - return $this->_render($this->authConfig->views[ 'rolesCreate' ], [ 'config' => $this->authConfig ]); + public function rolesCreate($id = null): string { + return $this->_render($this->authConfig->views['rolesCreate'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Roles Create Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new user. * To be be used by administrators. User will be activated automatically. + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function rolesCreateDo() { + public function rolesCreateDo(): \CodeIgniter\HTTP\RedirectResponse { $roles = model(RoleModel::class); $form = array(); // // Get form fields // - $form[ 'name' ] = $this->request->getPost('name'); - $form[ 'description' ] = $this->request->getPost('description'); + $form['name'] = $this->request->getPost('name'); + $form['description'] = $this->request->getPost('description'); // // Set validation rules for adding a new role @@ -125,7 +141,7 @@ public function rolesCreateDo() { 'label' => lang('Auth.role.name'), 'rules' => 'required|trim|max_length[255]|is_unique[auth_roles.name]', 'errors' => [ - 'is_unique' => lang('Auth.role.not_unique', [ $form[ 'name' ] ]) + 'is_unique' => lang('Auth.role.not_unique', [ $form['name'] ]) ] ], 'description' => [ @@ -158,13 +174,18 @@ public function rolesCreateDo() { } } - //--------------------------------------------------------------------------- /** - * Displays the user edit page. + * -------------------------------------------------------------------------- + * Roles Edit. + * -------------------------------------------------------------------------- + * + * Displays the role edit page. * * @param int $id Role ID + * + * @return \CodeIgniter\HTTP\RedirectResponse|string */ - public function rolesEdit($id = null) { + public function rolesEdit($id = null): \CodeIgniter\HTTP\RedirectResponse|string { $roles = model(RoleModel::class); if (!$role = $roles->where('id', $id)->first()) return redirect()->to('roles'); @@ -172,7 +193,7 @@ public function rolesEdit($id = null) { $permissions = $this->auth->permissions(); $rolePermissions = $roles->getPermissionsForRole($id); - return $this->_render($this->authConfig->views[ 'rolesEdit' ], [ + return $this->_render($this->authConfig->views['rolesEdit'], [ 'config' => $this->authConfig, 'role' => $role, 'permissions' => $permissions, @@ -180,13 +201,18 @@ public function rolesEdit($id = null) { ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Roles Edit Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new role. * * @param int $id Role ID + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function rolesEditDo($id = null) { + public function rolesEditDo($id = null): \CodeIgniter\HTTP\RedirectResponse { $roles = model(RoleModel::class); $form = array(); @@ -212,18 +238,18 @@ public function rolesEditDo($id = null) { // // Get form fields // - $form[ 'name' ] = $this->request->getPost('name'); - $form[ 'description' ] = $this->request->getPost('description'); + $form['name'] = $this->request->getPost('name'); + $form['description'] = $this->request->getPost('description'); // // If the role name changed, make sure the validator checks its uniqueness. // - if ($form[ 'name' ] != $role->name) { - $validationRules[ 'name' ] = [ + if ($form['name'] != $role->name) { + $validationRules['name'] = [ 'label' => lang('Auth.role.name'), 'rules' => 'required|trim|max_length[255]|is_unique[auth_roles.name]', 'errors' => [ - 'is_unique' => lang('Auth.role.not_unique', [ $form[ 'name' ] ]) + 'is_unique' => lang('Auth.role.not_unique', [ $form['name'] ]) ] ]; } @@ -241,7 +267,7 @@ public function rolesEditDo($id = null) { // // Save the role name and description // - $res = $this->auth->updateRole($id, $form[ 'name' ], $form[ 'description' ]); + $res = $this->auth->updateRole($id, $form['name'], $form['description']); if (!$res) return redirect()->back()->withInput()->with('errors', $roles->errors()); // @@ -262,16 +288,19 @@ public function rolesEditDo($id = null) { } } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Render. + * -------------------------------------------------------------------------- + * * Render View. * * @param string $view - * @param array $data + * @param array $data * * @return string */ - protected function _render(string $view, array $data = []) { + protected function _render(string $view, array $data = []): string { // // In case you have a custom configuration that you want to pass to // your views (e.g. theme settings), it is added here. @@ -279,7 +308,7 @@ protected function _render(string $view, array $data = []) { // It is assumed that have declared and set the variable $myConfig in // your BaseController. // - if (isset($this->myConfig)) $data[ 'myConfig' ] = $this->myConfig; + if (isset($this->myConfig)) $data['myConfig'] = $this->myConfig; return view($view, $data); } diff --git a/src/Controllers/UserController.php b/src/Controllers/UserController.php index d5c3ad4..2b2f1f7 100644 --- a/src/Controllers/UserController.php +++ b/src/Controllers/UserController.php @@ -29,9 +29,10 @@ class UserController extends BaseController { */ protected $validation; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- * Constructor. + * -------------------------------------------------------------------------- */ public function __construct() { // @@ -43,13 +44,16 @@ public function __construct() { $this->validation = service('validation'); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users. + * -------------------------------------------------------------------------- + * * Shows all user records. * * @return \CodeIgniter\HTTP\RedirectResponse | string */ - public function users() { + public function users(): \CodeIgniter\HTTP\RedirectResponse|string { $users = model(UserModel::class); $data = [ @@ -71,7 +75,7 @@ public function users() { } else { if (!$users->deleteUser($recId)) { $this->session->set('errors', $users->errors()); - return $this->_render($this->authConfig->views[ 'users' ], $data); + return $this->_render($this->authConfig->views['users'], $data); } return redirect()->route('users')->with('success', lang('Auth.user.delete_success', [ $user->username, $user->email ])); } @@ -97,28 +101,40 @@ public function users() { // $search = $this->request->getPost('search'); $where = '`username` LIKE "%' . $search . '%" OR `email` LIKE "%' . $search . '%" OR `firstname` LIKE "%' . $search . '%" OR `lastname` LIKE "%' . $search . '%"'; - $data[ 'users' ] = $users->where($where)->orderBy('username', 'asc')->findAll(); - $data[ 'search' ] = $search; + $data['users'] = $users->where($where)->orderBy('username', 'asc')->findAll(); + $data['search'] = $search; } } - return $this->_render($this->authConfig->views[ 'users' ], $data); + return $this->_render($this->authConfig->views['users'], $data); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users Create. + * -------------------------------------------------------------------------- + * * Displays the user create page. + * + * @param int $id User ID + * + * @return string */ - public function usersCreate($id = null) { - return $this->_render($this->authConfig->views[ 'usersCreate' ], [ 'config' => $this->authConfig ]); + public function usersCreate($id = null): string { + return $this->_render($this->authConfig->views['usersCreate'], [ 'config' => $this->authConfig ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users Create Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new user. * To be be used by administrators. User will be activated automatically. + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function usersCreateDo() { + public function usersCreateDo(): \CodeIgniter\HTTP\RedirectResponse { $users = model(UserModel::class); // @@ -186,13 +202,18 @@ public function usersCreateDo() { return redirect()->route('users')->with('success', lang('Auth.user.create_success', [ $user->username, $user->email ])); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users Edit. + * -------------------------------------------------------------------------- + * * Displays the user edit page. * * @param int $id User ID + * + * @return \CodeIgniter\HTTP\RedirectResponse|string */ - public function usersEdit($id = null) { + public function usersEdit($id = null): \CodeIgniter\HTTP\RedirectResponse|string { $users = model(UserModel::class); if (!$user = $users->where('id', $id)->first()) return redirect()->to('users'); @@ -206,7 +227,7 @@ public function usersEdit($id = null) { $userPersonalPermissions = $user->getPersonalPermissions(); $userRoles = $this->authorize->userRoles($id); - return $this->_render($this->authConfig->views[ 'usersEdit' ], [ + return $this->_render($this->authConfig->views['usersEdit'], [ 'auth' => $this->authorize, 'config' => $this->authConfig, 'user' => $user, @@ -220,14 +241,19 @@ public function usersEdit($id = null) { ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Users Edit Do. + * -------------------------------------------------------------------------- + * * Attempt to create a new user. * To be be used by administrators. User will be activated automatically. * * @param int $id User ID + * + * @return \CodeIgniter\HTTP\RedirectResponse */ - public function usersEditDo($id = null) { + public function usersEditDo($id = null): \CodeIgniter\HTTP\RedirectResponse { $users = model(UserModel::class); // @@ -251,13 +277,13 @@ public function usersEditDo($id = null) { // $emailChange = true; if ($this->request->getPost('email') == $user->email) { - $rules[ 'email' ] = 'required|valid_email'; + $rules['email'] = 'required|valid_email'; $emailChange = false; } $usernameChange = true; if ($this->request->getPost('username') == $user->username) { - $rules[ 'username' ] = 'required|alpha_numeric_space|min_length[3]|max_length[30]'; + $rules['username'] = 'required|alpha_numeric_space|min_length[3]|max_length[30]'; $usernameChange = false; } @@ -396,16 +422,19 @@ public function usersEditDo($id = null) { return redirect()->back()->withInput()->with('success', lang('Auth.user.update_success', [ $user->username, $user->email ])); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Render. + * -------------------------------------------------------------------------- + * * Render View. * * @param string $view - * @param array $data + * @param array $data * * @return string */ - protected function _render(string $view, array $data = []) { + protected function _render(string $view, array $data = []): string { // // In case you have a custom configuration that you want to pass to // your views (e.g. theme settings), it is added here. @@ -413,7 +442,7 @@ protected function _render(string $view, array $data = []) { // It is assumed that have declared and set the variable $myConfig in // your BaseController. // - if (isset($this->myConfig)) $data[ 'myConfig' ] = $this->myConfig; + if (isset($this->myConfig)) $data['myConfig'] = $this->myConfig; return view($view, $data); } diff --git a/src/Entities/User.php b/src/Entities/User.php index 5713e05..c695165 100644 --- a/src/Entities/User.php +++ b/src/Entities/User.php @@ -38,145 +38,184 @@ class User extends Entity { /** * Per-user permissions cache + * * @var array */ protected $permissions = []; /** * Per-user personal permissions cache + * * @var array */ protected $personalPermissions = []; /** * Per-user groups cache + * * @var array */ protected $groups = []; /** * Per-user options cache + * * @var array */ protected $options = []; /** * Per-user roles cache + * * @var array */ protected $roles = []; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Activate. + * -------------------------------------------------------------------------- + * * Activate user. * * @return $this */ - public function activate() { - $this->attributes[ 'active' ] = 1; - $this->attributes[ 'activate_hash' ] = null; + public function activate(): User { + $this->attributes['active'] = 1; + $this->attributes['activate_hash'] = null; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Ban. + * -------------------------------------------------------------------------- + * * Bans a user. * * @param string $reason * * @return $this */ - public function ban(string $reason) { - $this->attributes[ 'status' ] = 'banned'; - $this->attributes[ 'status_message' ] = $reason; + public function ban(string $reason): User { + $this->attributes['status'] = 'banned'; + $this->attributes['status_message'] = $reason; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Can. + * -------------------------------------------------------------------------- + * * Determines whether the user has the appropriate permission, either - * directly, or through one of it's roles. + * directly, or through a group or role. * * @param string $permission * * @return bool */ - public function can(string $permission) { + public function can(string $permission): bool { return in_array(strtolower($permission), $this->getPermissions()); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Deactivate. + * -------------------------------------------------------------------------- + * * Deactivate user. * * @return $this */ - public function deactivate() { - $this->attributes[ 'active' ] = 0; + public function deactivate(): User { + $this->attributes['active'] = 0; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Force Password Reset. + * -------------------------------------------------------------------------- + * * Force a user to reset their password on next page refresh * or login. Checked in the LocalAuthenticator's check() method. * * @return $this - * @throws \Exception * + * @throws \Exception */ - public function forcePasswordReset() { + public function forcePasswordReset(): User { $this->generateResetHash(); - $this->attributes[ 'force_pass_reset' ] = 1; + $this->attributes['force_pass_reset'] = 1; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Generate Activate Hash. + * * -------------------------------------------------------------------------- + * * * Generates a secure random hash to use for account activation. * * @return $this + * * @throws \Exception */ - public function generateActivateHash() { - $this->attributes[ 'activate_hash' ] = bin2hex(random_bytes(16)); + public function generateActivateHash(): User { + $this->attributes['activate_hash'] = bin2hex(random_bytes(16)); return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Generate Reset Hash. + * -------------------------------------------------------------------------- + * * Generates a secure hash to use for password reset purposes, * saves it to the instance. * * @return $this + * * @throws \Exception */ - public function generateResetHash() { - $this->attributes[ 'reset_hash' ] = bin2hex(random_bytes(16)); - $this->attributes[ 'reset_expires' ] = date('Y-m-d H:i:s', time() + config('Auth')->resetTime); + public function generateResetHash(): User { + $this->attributes['reset_hash'] = bin2hex(random_bytes(16)); + $this->attributes['reset_expires'] = date('Y-m-d H:i:s', time() + config('Auth')->resetTime); return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Attribute. + * -------------------------------------------------------------------------- + * * Returns a single attribute value. * + * @param string $attr */ - public function getAttribute($attr) { - return $this->attributes[ $attr ]; + public function getAttribute($attr): string { + return $this->attributes[$attr]; } - //--------------------------------------------------------------------------- /** - * Returns a single attribute value. + * -------------------------------------------------------------------------- + * Get Attributes. + * -------------------------------------------------------------------------- + * + * Returns an array of all attributes. * + * @return array */ - public function getAttributes() { + public function getAttributes(): array { return $this->attributes; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Groups. + * -------------------------------------------------------------------------- + * * Returns the user's groups, formatted for simple checking: * * [ @@ -184,30 +223,33 @@ public function getAttributes() { * id => name, * ] * - * @return array|mixed + * @return array */ - public function getGroups() { + public function getGroups(): array { if (empty($this->id)) throw new \RuntimeException('Users must be created before getting groups.'); if (empty($this->groups)) { $groups = model(GroupModel::class)->getGroupsForUser($this->id); foreach ($groups as $group) { - $this->groups[ $group[ 'group_id' ] ] = strtolower($group[ 'name' ]); + $this->groups[$group['group_id']] = strtolower($group['name']); } } return $this->groups; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Option. + * -------------------------------------------------------------------------- + * * Returns a specific user options. * * @param string $option Option to get * * @return string */ - public function getOption($option) { + public function getOption($option): string { if (empty($this->id)) throw new \RuntimeException('Users must be created before getting options.'); return model(UserOptionModel::class)->getOption([ @@ -216,32 +258,38 @@ public function getOption($option) { ]); } - //--------------------------------------------------------------------------- /** - * Returns the user's options, formatted for simple checking: + * -------------------------------------------------------------------------- + * Get Options. + * -------------------------------------------------------------------------- + * + * Returns all the user's options, formatted for simple checking: * * [ * option => value, * option => value, * ] * - * @return array|mixed + * @return array */ - public function getOptions() { + public function getOptions(): array { if (empty($this->id)) throw new \RuntimeException('Users must be created before getting options.'); if (empty($this->options)) { $options = model(UserOptionModel::class)->getOptionsForUser($this->id); foreach ($options as $option) { - $this->options[ $option[ 'option' ] ] = $option[ 'value' ]; + $this->options[$option['option']] = $option['value']; } } return $this->options; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Permissions. + * -------------------------------------------------------------------------- + * * Returns the user's permissions, formatted for simple checking: * * [ @@ -249,16 +297,19 @@ public function getOptions() { * id=> name, * ] * - * @return array|mixed + * @return array */ - public function getPermissions() { + public function getPermissions(): array { if (empty($this->id)) throw new \RuntimeException('Users must be created before getting permissions.'); if (empty($this->permissions)) $this->permissions = model(PermissionModel::class)->getPermissionsForUser($this->id); return $this->permissions; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Personal Permissions. + * -------------------------------------------------------------------------- + * * Returns the user's permissions, formatted for simple checking: * * [ @@ -266,16 +317,19 @@ public function getPermissions() { * id=> name, * ] * - * @return array|mixed + * @return array */ - public function getPersonalPermissions() { + public function getPersonalPermissions(): array { if (empty($this->id)) throw new \RuntimeException('Users must be created before getting permissions.'); if (empty($this->personalPermissions)) $this->personalPermissions = model(PermissionModel::class)->getPersonalPermissionsForUser($this->id); return $this->personalPermissions; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Roles. + * -------------------------------------------------------------------------- + * * Returns the user's roles, formatted for simple checking: * * [ @@ -283,70 +337,91 @@ public function getPersonalPermissions() { * id => name, * ] * - * @return array|mixed + * @return array */ - public function getRoles() { + public function getRoles(): array { if (empty($this->id)) throw new \RuntimeException('Users must be created before getting roles.'); if (empty($this->roles)) { $roles = model(RoleModel::class)->getRolesForUser($this->id); foreach ($roles as $role) { - $this->roles[ $role[ 'role_id' ] ] = strtolower($role[ 'name' ]); + $this->roles[$role['role_id']] = strtolower($role['name']); } } return $this->roles; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Has Secret. + * -------------------------------------------------------------------------- + * * Checks to see if a user has a secret hash (2FA setup). * * @return bool */ public function hasSecret(): bool { - return isset($this->attributes[ 'secret_hash' ]) && $this->attributes[ 'secret_hash' ] != ''; + return isset($this->attributes['secret_hash']) && $this->attributes['secret_hash'] != ''; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Is Activated. + * -------------------------------------------------------------------------- + * * Checks to see if a user is active. * * @return bool */ public function isActivated(): bool { - return isset($this->attributes[ 'active' ]) && $this->attributes[ 'active' ] == true; + return isset($this->attributes['active']) && $this->attributes['active'] == true; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Is Banned. + * -------------------------------------------------------------------------- + * * Checks to see if a user has been banned. * * @return bool */ public function isBanned(): bool { - return isset($this->attributes[ 'status' ]) && $this->attributes[ 'status' ] === 'banned'; + return isset($this->attributes['status']) && $this->attributes['status'] === 'banned'; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Set Attribute. + * -------------------------------------------------------------------------- + * * Sets a single attribute value. * + * @param string $attr + * @param string $val + * + * @return void */ - public function setAttribute($attr, $val) { - $this->attributes[ $attr ] = $val; + public function setAttribute($attr, $val): void { + $this->attributes[$attr] = $val; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Set Password. + * -------------------------------------------------------------------------- + * * Automatically hashes the password when set. * * @see https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence * * @param string $password + * + * @return void */ - public function setPassword(string $password) { - $this->attributes[ 'password_hash' ] = Password::hash($password); + public function setPassword(string $password): void { + $this->attributes['password_hash'] = Password::hash($password); // // Set these vars to null in case a reset password was asked. @@ -358,59 +433,80 @@ public function setPassword(string $password) { // User would have a new password but still anyone with the reset-token // would be able to change the password. // - $this->attributes[ 'reset_hash' ] = null; - $this->attributes[ 'reset_at' ] = null; - $this->attributes[ 'reset_expires' ] = null; + $this->attributes['reset_hash'] = null; + $this->attributes['reset_at'] = null; + $this->attributes['reset_expires'] = null; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Set Permissions. + * -------------------------------------------------------------------------- + * * Warns the developer it won't work, so they don't spend hours tracking stuff down. * * @param array $permissions * - * @return $this + * @return void + * + * @throws \RuntimeException */ - public function setPermissions(array $permissions = null) { + public function setPermissions(array $permissions = null): void { throw new \RuntimeException('User entity does not support saving permissions directly.'); } - //--------------------------------------------------------------------------- /** - * Encrypts the secret when set. + * -------------------------------------------------------------------------- + * Set Secret. + * -------------------------------------------------------------------------- + * + * Sets the secret hash. * * @param string $secret + * + * @return void */ - public function setSecret(string $secret) { - $this->attributes[ 'secret_hash' ] = $secret; + public function setSecret(string $secret): void { + $this->attributes['secret_hash'] = $secret; } - //--------------------------------------------------------------------------- /** - * Encrypts the secret when set. + * -------------------------------------------------------------------------- + * Get Secret. + * -------------------------------------------------------------------------- + * + * Gets the secret hash. * * @return string */ - public function getSecret() { - return $this->attributes[ 'secret_hash' ]; + public function getSecret(): string { + return $this->attributes['secret_hash']; } - //--------------------------------------------------------------------------- /** - * Removes the secret. + * -------------------------------------------------------------------------- + * Set Secret. + * -------------------------------------------------------------------------- + * + * Removes the secret hash. + * + * @return void */ - public function removeSecret() { - $this->attributes[ 'secret_hash' ] = ''; + public function removeSecret(): void { + $this->attributes['secret_hash'] = ''; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Unban. + * -------------------------------------------------------------------------- + * * Removes a ban from a user. * * @return $this */ - public function unBan() { - $this->attributes[ 'status' ] = $this->status_message = ''; + public function unBan(): User { + $this->attributes['status'] = $this->status_message = ''; return $this; } } diff --git a/src/Exceptions/UserNotFoundException.php b/src/Exceptions/UserNotFoundException.php index f406d37..15a77be 100644 --- a/src/Exceptions/UserNotFoundException.php +++ b/src/Exceptions/UserNotFoundException.php @@ -3,7 +3,6 @@ namespace CI4\Auth\Exceptions; class UserNotFoundException extends \RuntimeException implements ExceptionInterface { - //--------------------------------------------------------------------------- /** * This static method is responsible for creating a new instance of the UserNotFoundException. * It takes an integer as input, which should be the user's ID. diff --git a/src/Filters/GroupFilter.php b/src/Filters/GroupFilter.php index 0165091..9654a4f 100644 --- a/src/Filters/GroupFilter.php +++ b/src/Filters/GroupFilter.php @@ -8,8 +8,11 @@ use CI4\Auth\Exceptions\PermissionException; class GroupFilter implements FilterInterface { - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Before. + * -------------------------------------------------------------------------- + * * Do whatever processing this filter needs to do. By default it should not * return anything during normal execution. However, when an abnormal state * is found, it should return an instance of CodeIgniter\HTTP\Response. If @@ -17,14 +20,14 @@ class GroupFilter implements FilterInterface { * to the client, allowing for error pages, redirects, etc. * * @param RequestInterface $request - * @param array|null $params + * @param array|null $arguments * - * @return mixed + * @return \CodeIgniter\HTTP\RedirectResponse|void; */ - public function before(RequestInterface $request, $params = null) { + public function before(RequestInterface $request, $arguments = null) { if (!function_exists('logged_in')) helper('auth'); - if (empty($params)) return; + if (empty($arguments)) return; $authenticate = service('authentication'); @@ -41,30 +44,32 @@ public function before(RequestInterface $request, $params = null) { // // Check each requested group // - foreach ($params as $group) { + foreach ($arguments as $group) { if ($authorize->inGroup($group, $authenticate->id())) return; } if ($authenticate->silent()) { // $redirectURL = session('redirect_url') ?? '/'; $redirectURL = '/error'; - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL)->with('error', lang('Auth.exception.insufficient_permissions')); } else { throw new PermissionException(lang('Auth.exception.insufficient_permissions')); } } - //--------------------------------------------------------------------------- /** - * Allows After filters to inspect and modify the response - * object as needed. This method does not allow any way - * to stop execution of other after filters, short of - * throwing an Exception or Error. + * -------------------------------------------------------------------------- + * After. + * -------------------------------------------------------------------------- * - * @param RequestInterface $request + * Allows After filters to inspect and modify the response object as needed. + * This method does not allow any way to stop execution of other after filters, + * short of throwing an Exception or Error. + * + * @param RequestInterface $request * @param ResponseInterface $response - * @param array|null $arguments + * @param array|null $arguments * * @return void */ diff --git a/src/Filters/LoginFilter.php b/src/Filters/LoginFilter.php index a94b33a..fd86264 100644 --- a/src/Filters/LoginFilter.php +++ b/src/Filters/LoginFilter.php @@ -8,16 +8,19 @@ use Config\App; class LoginFilter implements FilterInterface { - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Before. + * -------------------------------------------------------------------------- + * * Verifies that a user is logged in, or redirects to login. * * @param RequestInterface $request - * @param array|null $params + * @param array|null $arguments * - * @return mixed + * @return \CodeIgniter\HTTP\RedirectResponse|bool */ - public function before(RequestInterface $request, $params = null) { + public function before(RequestInterface $request, $arguments = null): \CodeIgniter\HTTP\RedirectResponse|bool { if (!function_exists('logged_in')) { helper('auth'); } @@ -53,11 +56,18 @@ public function before(RequestInterface $request, $params = null) { return true; } - //--------------------------------------------------------------------------- /** - * @param RequestInterface $request + * -------------------------------------------------------------------------- + * After. + * -------------------------------------------------------------------------- + * + * Allows After filters to inspect and modify the response object as needed. + * This method does not allow any way to stop execution of other after filters, + * short of throwing an Exception or Error. + * + * @param RequestInterface $request * @param ResponseInterface $response - * @param array|null $arguments + * @param array|null $arguments * * @return void */ diff --git a/src/Filters/PermissionFilter.php b/src/Filters/PermissionFilter.php index 2685bad..b63e4d2 100644 --- a/src/Filters/PermissionFilter.php +++ b/src/Filters/PermissionFilter.php @@ -10,6 +10,10 @@ class PermissionFilter implements FilterInterface { //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Before. + * -------------------------------------------------------------------------- + * * Do whatever processing this filter needs to do. By default it should not * return anything during normal execution. However, when an abnormal state * is found, it should return an instance of CodeIgniter\HTTP\Response. If @@ -17,14 +21,14 @@ class PermissionFilter implements FilterInterface { * to the client, allowing for error pages, redirects, etc. * * @param RequestInterface $request - * @param array|null $params + * @param array|null $arguments * * @return mixed */ - public function before(RequestInterface $request, $params = null) { + public function before(RequestInterface $request, $arguments = null): mixed { if (!function_exists('logged_in')) helper('auth'); - if (empty($params)) return false; + if (empty($arguments)) return false; $authenticate = service('authentication'); @@ -41,7 +45,7 @@ public function before(RequestInterface $request, $params = null) { // // Check each requested permission // - foreach ($params as $permission) { + foreach ($arguments as $permission) { $result = $result && $authorize->hasPermission($permission, $authenticate->id()); } @@ -49,12 +53,12 @@ public function before(RequestInterface $request, $params = null) { if ($authenticate->silent()) { // $redirectURL = session('redirect_url') ?? '/'; $redirectURL = '/error_auth'; - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL)->with('error', lang('Auth.exception.insufficient_permissions')); } else { // $redirectURL = session('redirect_url') ?? '/'; $redirectURL = '/error_auth'; - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); // throw new PermissionException(lang('Auth.exception.insufficient_permissions')); return redirect()->to($redirectURL)->with('error', lang('Auth.exception.insufficient_permissions')); } @@ -62,16 +66,18 @@ public function before(RequestInterface $request, $params = null) { return false; } - //---------------------------------------------------------------------------- /** - * Allows After filters to inspect and modify the response - * object as needed. This method does not allow any way - * to stop execution of other after filters, short of - * throwing an Exception or Error. + * -------------------------------------------------------------------------- + * After. + * -------------------------------------------------------------------------- * - * @param RequestInterface $request + * Allows After filters to inspect and modify the response object as needed. + * This method does not allow any way to stop execution of other after filters, + * short of throwing an Exception or Error. + * + * @param RequestInterface $request * @param ResponseInterface $response - * @param array|null $arguments + * @param array|null $arguments * * @return void */ diff --git a/src/Filters/RoleFilter.php b/src/Filters/RoleFilter.php index 1a67938..ca4f22b 100644 --- a/src/Filters/RoleFilter.php +++ b/src/Filters/RoleFilter.php @@ -8,8 +8,11 @@ use CI4\Auth\Exceptions\PermissionException; class RoleFilter implements FilterInterface { - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Before. + * -------------------------------------------------------------------------- + * * Do whatever processing this filter needs to do. By default it should not * return anything during normal execution. However, when an abnormal state * is found, it should return an instance of CodeIgniter\HTTP\Response. If @@ -17,14 +20,14 @@ class RoleFilter implements FilterInterface { * to the client, allowing for error pages, redirects, etc. * * @param RequestInterface $request - * @param array|null $params + * @param array|null $arguments * - * @return mixed + * @return \CodeIgniter\HTTP\RedirectResponse|void */ - public function before(RequestInterface $request, $params = null) { + public function before(RequestInterface $request, $arguments = null): \CodeIgniter\HTTP\RedirectResponse { if (!function_exists('logged_in')) helper('auth'); - if (empty($params)) return; + if (empty($arguments)) return; $authenticate = service('authentication'); @@ -41,30 +44,32 @@ public function before(RequestInterface $request, $params = null) { // // Check each requested role // - foreach ($params as $role) { + foreach ($arguments as $role) { if ($authorize->inRole($role, $authenticate->id())) return; } if ($authenticate->silent()) { // $redirectURL = session('redirect_url') ?? '/'; $redirectURL = '/error'; - unset($_SESSION[ 'redirect_url' ]); + unset($_SESSION['redirect_url']); return redirect()->to($redirectURL)->with('error', lang('Auth.exception.insufficient_permissions')); } else { throw new PermissionException(lang('Auth.exception.insufficient_permissions')); } } - //---------------------------------------------------------------------------- /** - * Allows After filters to inspect and modify the response - * object as needed. This method does not allow any way - * to stop execution of other after filters, short of - * throwing an Exception or Error. + * -------------------------------------------------------------------------- + * After. + * -------------------------------------------------------------------------- * - * @param RequestInterface $request + * Allows After filters to inspect and modify the response object as needed. + * This method does not allow any way to stop execution of other after filters, + * short of throwing an Exception or Error. + * + * @param RequestInterface $request * @param ResponseInterface $response - * @param array|null $arguments + * @param array|null $arguments * * @return void */ diff --git a/src/Models/LoginModel.php b/src/Models/LoginModel.php index ea22dad..c50ae97 100644 --- a/src/Models/LoginModel.php +++ b/src/Models/LoginModel.php @@ -26,18 +26,21 @@ class LoginModel extends Model { protected $validationMessages = []; protected $skipValidation = false; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Remember User. + * -------------------------------------------------------------------------- + * * Stores a remember-me token for the user. * - * @param int $userID + * @param int $userID * @param string $selector * @param string $validator * @param string $expires * * @return mixed */ - public function rememberUser(int $userID, string $selector, string $validator, string $expires) { + public function rememberUser(int $userID, string $selector, string $validator, string $expires): mixed { $expires = new \DateTime($expires); return $this->db->table('auth_tokens')->insert([ @@ -48,23 +51,29 @@ public function rememberUser(int $userID, string $selector, string $validator, s ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Remember Token. + * -------------------------------------------------------------------------- + * * Returns the remember-me token info for a given selector. * * @param string $selector * * @return mixed */ - public function getRememberToken(string $selector) { + public function getRememberToken(string $selector): mixed { return $this->db->table('auth_tokens') ->where('selector', $selector) ->get() ->getRow(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Update Remember Validator. + * -------------------------------------------------------------------------- + * * Updates the validator for a given selector. * * @param string $selector @@ -72,7 +81,7 @@ public function getRememberToken(string $selector) { * * @return mixed */ - public function updateRememberValidator(string $selector, string $validator) { + public function updateRememberValidator(string $selector, string $validator): mixed { return $this->db->table('auth_tokens') ->where('selector', $selector) ->update([ @@ -81,30 +90,35 @@ public function updateRememberValidator(string $selector, string $validator) { ]); } - //--------------------------------------------------------------------------- /** - * Removes all persistent login tokens (RememberMe) for a single user - * across all devices they may have logged in with. + * -------------------------------------------------------------------------- + * Purge Remember Tokens. + * -------------------------------------------------------------------------- + * + * Removes all persistent login tokens (RememberMe) for a single user across + * all devices they may have logged in with. * * @param int $id * * @return mixed */ - public function purgeRememberTokens(int $id) { + public function purgeRememberTokens(int $id): mixed { return $this->builder('auth_tokens')->where([ 'user_id' => $id ])->delete(); } - //--------------------------------------------------------------------------- /** - * Purges the 'auth_tokens' table of any records that are past - * their expiration date already. + * -------------------------------------------------------------------------- + * Purge Old Remember Tokens. + * -------------------------------------------------------------------------- + * + * Purges the 'auth_tokens' table of any records that are past their expiration + * date already. + * + * @return void */ - public function purgeOldRememberTokens() { - + public function purgeOldRememberTokens(): void { $config = config('Auth'); - if (!$config->allowRemembering) return; - $this->db->table('auth_tokens') ->where('expires <=', date('Y-m-d H:i:s')) ->delete(); diff --git a/src/Models/UserModel.php b/src/Models/UserModel.php index fb1a3d7..75e678f 100644 --- a/src/Models/UserModel.php +++ b/src/Models/UserModel.php @@ -87,8 +87,11 @@ class UserModel extends Model { */ protected $assignRole; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Add to Group. + * -------------------------------------------------------------------------- + * * If a default role is assigned in Config\Auth, will add this user to that * role. Will do nothing if the role cannot be found. * @@ -96,65 +99,76 @@ class UserModel extends Model { * * @return mixed */ - protected function addToGroup($data) { + protected function addToGroup($data): mixed { if (is_numeric($this->assignGroup)) { $groupModel = model(GroupModel::class); - $groupModel->addUserToGroup($data[ 'id' ], $this->assignGroup); + $groupModel->addUserToGroup($data['id'], $this->assignGroup); } return $data; } - //--------------------------------------------------------------------------- /** - * If a default role is assigned in Config\Auth, will - * add this user to that role. Will do nothing - * if the role cannot be found. + * -------------------------------------------------------------------------- + * Add to Role. + * -------------------------------------------------------------------------- + * + * If a default role is assigned in Config\Auth, will add this user to that + * role. Will do nothing if the role cannot be found. * * @param mixed $data * * @return mixed */ - protected function addToRole($data) { + protected function addToRole($data): mixed { if (is_numeric($this->assignRole)) { $roleModel = model(RoleModel::class); - $roleModel->addUserToRole($data[ 'id' ], $this->assignRole); + $roleModel->addUserToRole($data['id'], $this->assignRole); } return $data; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Clear Group. + * -------------------------------------------------------------------------- + * * Clears the group to assign to newly created users. * * @return $this */ - public function clearGroup() { + public function clearGroup(): UserModel { $this->assignGroup = null; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Clear Role. + * -------------------------------------------------------------------------- + * * Clears the role to assign to newly created users. * * @return $this */ - public function clearRole() { + public function clearRole(): UserModel { $this->assignRole = null; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Create User. + * -------------------------------------------------------------------------- + * * Creates a user. * * @param array $data User data * * @return mixed */ - public function createUser($data) { + public function createUser($data): mixed { $validation = service('validation', null, false); $validation->setRules($this->validationRules, $this->validationMessages); @@ -172,15 +186,18 @@ public function createUser($data) { return false; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete User. + * -------------------------------------------------------------------------- + * * Deletes a user. * * @param int $teamId * * @return bool */ - public function deleteUser(int $id) { + public function deleteUser(int $id): bool { if (!$this->delete($id)) { $this->error = $this->errors(); return false; @@ -189,15 +206,20 @@ public function deleteUser(int $id) { return true; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Log Activation Attempt. + * -------------------------------------------------------------------------- + * * Logs an activation attempt for posterity sake. * * @param string|null $token * @param string|null $ipAddress * @param string|null $userAgent + * + * @return void */ - public function logActivationAttempt(string $token = null, string $ipAddress = null, string $userAgent = null) { + public function logActivationAttempt(string $token = null, string $ipAddress = null, string $userAgent = null): void { $this->db->table('auth_activation_attempts')->insert([ 'ip_address' => $ipAddress, 'user_agent' => $userAgent, @@ -206,16 +228,21 @@ public function logActivationAttempt(string $token = null, string $ipAddress = n ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Log Reset Attempt. + * -------------------------------------------------------------------------- + * * Logs a password reset attempt for posterity sake. * - * @param string $email + * @param string $email * @param string|null $token * @param string|null $ipAddress * @param string|null $userAgent + * + * @return void */ - public function logResetAttempt(string $email, string $token = null, string $ipAddress = null, string $userAgent = null) { + public function logResetAttempt(string $email, string $token = null, string $ipAddress = null, string $userAgent = null): void { $this->db->table('auth_reset_attempts')->insert([ 'email' => $email, 'ip_address' => $ipAddress, @@ -225,29 +252,35 @@ public function logResetAttempt(string $email, string $token = null, string $ipA ]); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * With Group. + * -------------------------------------------------------------------------- + * * Sets the group to assign when a user is created. * * @param string $groupName * * @return $this */ - public function withGroup(string $groupName) { + public function withGroup(string $groupName): UserModel { $group = $this->db->table('auth_groups')->where('name', $groupName)->get()->getFirstRow(); $this->assignGroup = $group->id; return $this; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * With Role. + * -------------------------------------------------------------------------- + * * Sets the role to assign any users created. * * @param string $roleName * * @return $this */ - public function withRole(string $roleName) { + public function withRole(string $roleName): UserModel { $role = $this->db->table('auth_roles')->where('name', $roleName)->get()->getFirstRow(); $this->assignRole = $role->id; return $this; diff --git a/src/Models/UserOptionModel.php b/src/Models/UserOptionModel.php index 7008023..2cfbeab 100644 --- a/src/Models/UserOptionModel.php +++ b/src/Models/UserOptionModel.php @@ -10,50 +10,60 @@ class UserOptionModel extends Model { protected $useTimestamps = true; protected $skipValidation = true; - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Option. + * -------------------------------------------------------------------------- + * * Deletes a given option record. * * @param array $data ['user_id', 'option'] * - * @return mixed + * @return bool */ - public function deleteOption($data) { + public function deleteOption($data): bool { $conditions = array( - 'user_id' => $data[ 'user_id' ], - 'option' => $data[ 'option' ] + 'user_id' => $data['user_id'], + 'option' => $data['option'] ); return $this->builder($this->table)->where($conditions)->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Delete Options for User. + * -------------------------------------------------------------------------- + * * Deletes all options for a given user. * * @param int $userId * + * @return bool */ - public function deleteOptionsForUser(int $userId) { + public function deleteOptionsForUser(int $userId): bool { $conditions = array( 'user_id' => $userId, ); return $this->builder($this->table)->where($conditions)->delete(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Option. + * -------------------------------------------------------------------------- + * * Reads the value of a given option and user. * * @param array $data ['user_id', 'option'] * * @return mixed */ - public function getOption($data) { + public function getOption($data): mixed { $found = $this->db->table($this->table) ->select('value') ->where(array( - 'user_id' => $data[ 'user_id' ], - 'option' => $data[ 'option' ] + 'user_id' => $data['user_id'], + 'option' => $data['option'] )) ->get() ->getRow(); @@ -64,33 +74,39 @@ public function getOption($data) { return false; } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Get Options for User. + * -------------------------------------------------------------------------- + * * Returns an array of all options that a user has set. * * @param int $userId * * @return array */ - public function getOptionsForUser(int $userId) { + public function getOptionsForUser(int $userId): array { return $this->builder() ->select($this->table . '.option, ' . $this->table . '.value') ->where('user_id', $userId) ->get()->getResultArray(); } - //--------------------------------------------------------------------------- /** + * -------------------------------------------------------------------------- + * Save Option. + * -------------------------------------------------------------------------- + * * Saves (create/insert) an option for a user. * * @param array $data ['user_id', 'option', 'value'] * * @return bool */ - public function saveOption($data) { + public function saveOption($data): bool { $conditions = array( - 'user_id' => $data[ 'user_id' ], - 'option' => $data[ 'option' ] + 'user_id' => $data['user_id'], + 'option' => $data['option'] ); $row = $this->db->table($this->table)->where($conditions)->get()->getRow(); @@ -100,7 +116,7 @@ public function saveOption($data) { // return $this->db->table($this->table) ->where($conditions) - ->update([ 'value' => $data[ 'value' ] ]); + ->update([ 'value' => $data['value'] ]); } else { // // Record does not exist. Insert.