Skip to content

Commit 247c53f

Browse files
davidnsaidatamwebkenjis
authored
Feature: Banning Users (#650)
* Added migration file * Added new feilds to the UserModel * Added methods to modify the ban status of a user * Added exception for banned users * Added banned user checks on access tokens * Added banned user checks on attempting to log in * Added language translations for banned user * Fixed coding standard fail * cs fix * Added user model to list of imported classes * Removed extra whitespace * ran composer cs-fix * Added a bannable trait * Completed banning logic * Added docs for banning feature * Fixed failing unit test * Update docs/banning_users.md Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> * Update src/Filters/SessionAuth.php Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> * Update src/Language/fa/Auth.php Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> * Update src/Language/ja/Auth.php Thank you for your translation Co-authored-by: kenjis <kenji.uui@gmail.com> * Removed migration adding banned and banned_message fields * Removed banned fields from user model * Implemented ban and unban logic * FIxed docs on banning users * removed unneccessary (bool) * Reverted redirect route for when a user is not activated * Added test for getBanMessage() * Removed unnecesary whitespaces from the docs * Update docs/banning_users.md Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> * Update docs/banning_users.md Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> * Update docs/banning_users.md Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> * Update docs/banning_users.md Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> --------- Co-authored-by: Pooya Parsa Dadashi <pooya_parsa_dadashi@yahoo.com> Co-authored-by: kenjis <kenji.uui@gmail.com>
1 parent f0a12ef commit 247c53f

File tree

19 files changed

+188
-0
lines changed

19 files changed

+188
-0
lines changed

docs/banning_users.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Banning Users
2+
3+
Shield provides a way to ban users from your application. This is useful if you need to prevent a user from logging in, or logging them out in the event that they breach your terms of service.
4+
5+
- [Checking if the User is Banned](#check-if-a-user-is-banned)
6+
- [Banning a User](#banning-a-user)
7+
- [Unbanning a User](#unbanning-a-user)
8+
- [Getting the Reason for Ban ](#getting-the-reason-for-ban)
9+
10+
### Check if a User is Banned
11+
12+
You can check if a user is banned using `isBanned()` method on the `User` entity. The method returns a boolean `true`/`false`.
13+
14+
```php
15+
if ($user->isBanned()) {
16+
//...
17+
}
18+
```
19+
20+
### Banning a User
21+
22+
To ban a user from the application, the `ban(?string $message = null)` method can be called on the `User` entity. The method takes an optional string as a parameter. The string acts as the reason for the ban.
23+
24+
```php
25+
// banning a user without passing a message
26+
$user->ban();
27+
// banning a user with a message and reason for the ban passed.
28+
$user->ban('Your reason for banning the user here');
29+
```
30+
31+
### Unbanning a User
32+
33+
Unbanning a user can be done using the `unBan()` method on the `User` entity. This method will also reset the `status_message` property.
34+
35+
```php
36+
$user->unBan();
37+
```
38+
39+
### Getting the Reason for Ban
40+
41+
The reason for the ban can be obtained user the `getBanMessage()` method on the `User` entity.
42+
43+
```php
44+
$user->getBanMessage();
45+
```

src/Authentication/AuthenticationException.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ public static function forInvalidUser(): self
2929
return new self(lang('Auth.invalidUser'));
3030
}
3131

32+
public static function forBannedUser(): self
33+
{
34+
return new self(lang('Auth.invalidUser'));
35+
}
36+
3237
public static function forNoEntityProvided(): self
3338
{
3439
return new self(lang('Auth.noUserEntity'), 500);

src/Authentication/Authenticators/AccessTokens.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ public function attempt(array $credentials): Result
6565

6666
$user = $result->extraInfo();
6767

68+
if ($user->isBanned()) {
69+
$this->user = null;
70+
71+
return new Result([
72+
'success' => false,
73+
'reason' => $user->getBanMessage() ?? lang('Auth.bannedUser'),
74+
]);
75+
}
76+
6877
$user = $user->setAccessToken(
6978
$user->getAccessToken($this->getBearerToken())
7079
);

src/Authentication/Authenticators/Session.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,15 @@ public function attempt(array $credentials): Result
147147
/** @var User $user */
148148
$user = $result->extraInfo();
149149

150+
if ($user->isBanned()) {
151+
$this->user = null;
152+
153+
return new Result([
154+
'success' => false,
155+
'reason' => $user->getBanMessage() ?? lang('Auth.bannedUser'),
156+
]);
157+
}
158+
150159
$this->user = $user;
151160

152161
// Update the user's last used date on their password identity.

src/Entities/User.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use CodeIgniter\Shield\Models\LoginModel;
1313
use CodeIgniter\Shield\Models\UserIdentityModel;
1414
use CodeIgniter\Shield\Traits\Activatable;
15+
use CodeIgniter\Shield\Traits\Bannable;
1516
use CodeIgniter\Shield\Traits\Resettable;
1617

1718
/**
@@ -29,6 +30,7 @@ class User extends Entity
2930
use HasAccessTokens;
3031
use Resettable;
3132
use Activatable;
33+
use Bannable;
3234

3335
/**
3436
* @var UserIdentity[]|null

src/Filters/SessionAuth.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ public function before(RequestInterface $request, $arguments = null)
5151

5252
// Block inactive users when Email Activation is enabled
5353
$user = $authenticator->getUser();
54+
55+
if ($user->isBanned()) {
56+
$error = $user->getBanMessage() ?? lang('Auth.logOutBannedUser');
57+
$authenticator->logout();
58+
59+
return redirect()->to(config('Auth')->logoutRedirect())
60+
->with('error', $error);
61+
}
62+
5463
if ($user !== null && ! $user->isActivated()) {
5564
$authenticator->logout();
5665

src/Language/de/Auth.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
'unknownAuthenticator' => '{0} ist kein gültiger Authentifikator.',
88
'unknownUserProvider' => 'Der zu verwendende User Provider konnte nicht ermittelt werden.',
99
'invalidUser' => 'Der angegebene Benutzer kann nicht gefunden werden.',
10+
'bannedUser' => '(To be translated) Can not log you in as you are currently banned.',
11+
'logOutBannedUser' => '(To be translated) You have been logged out because you have been banned.',
1012
'badAttempt' => 'Sie konnten nicht angemeldet werden. Bitte überprüfen Sie Ihre Anmeldedaten.',
1113
'noPassword' => 'Kann einen Benutzer ohne Passwort nicht validieren.',
1214
'invalidPassword' => 'Sie können nicht angemeldet werden. Bitte überprüfen Sie Ihr Passwort.',

src/Language/en/Auth.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
'unknownAuthenticator' => '{0} is not a valid authenticator.',
88
'unknownUserProvider' => 'Unable to determine the User Provider to use.',
99
'invalidUser' => 'Unable to locate the specified user.',
10+
'bannedUser' => 'Can not log you in as you are currently banned.',
11+
'logOutBannedUser' => 'You have been logged out because you have been banned.',
1012
'badAttempt' => 'Unable to log you in. Please check your credentials.',
1113
'noPassword' => 'Cannot validate a user without a password.',
1214
'invalidPassword' => 'Unable to log you in. Please check your password.',

src/Language/es/Auth.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
'unknownAuthenticator' => '{0} no es un handler válido.',
88
'unknownUserProvider' => 'No podemos determinar que Proveedor de Usuarios usar.',
99
'invalidUser' => 'No podemos localizar este usuario.',
10+
'bannedUser' => '(To be translated) Can not log you in as you are currently banned.',
11+
'logOutBannedUser' => '(To be translated) You have been logged out because you have been banned.',
1012
'badAttempt' => 'No puedes entrar. Por favor, comprueba tus creenciales.',
1113
'noPassword' => 'No se puede validar un usuario sin una contraseña.',
1214
'invalidPassword' => 'No uedes entrar. Por favor, comprueba tu contraseña.',

src/Language/fa/Auth.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
'unknownAuthenticator' => '{0} احراز هویت معتبری نمی باشد.',
88
'unknownUserProvider' => 'قادر به تعیین ارائه دهنده کاربر برای استفاده نیست.',
99
'invalidUser' => 'قادر به پیداکردن کاربر مشخص شده نیست',
10+
'bannedUser' => 'در حال حاضر نمی توانید وارد شوید، چون مسدود شده اید.',
11+
'logOutBannedUser' => 'شما به دلیل مسدود شدن، از سیستم خارج شده اید.',
1012
'badAttempt' => 'امکان ورود به سیستم نیست. لطفا اعتبارنامه خود را بررسی کنید.',
1113
'noPassword' => 'تایید کاربر بدون رمز عبور ممکن نیست.',
1214
'invalidPassword' => 'ناتوان در ورود به سیستم. لطفا رمز عبور خود را بررسی کنید.',

0 commit comments

Comments
 (0)