-
Notifications
You must be signed in to change notification settings - Fork 49
feat(identity,panel-app): permite alteração de @ (username) (#502) #558
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nikolasgds
wants to merge
4
commits into
he4rt:4.x
Choose a base branch
from
nikolasgds:feat/502-permite-alterar-@
base: 4.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bfcda5e
feat(identity,panel-app): permite alteração de @ (username) (#502)
nikolasgds ad619f9
fix(identity,panel-app): localiza excecoes de username e garante limp…
nikolasgds f2d46db
refactor(panel-app): remove aviso obsoleto para administradores na al…
nikolasgds 8fdb7f4
Merge branch '4.x' into feat/502-permite-alterar-@
nikolasgds File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
25 changes: 25 additions & 0 deletions
25
...les/identity/database/migrations/2026_09_02_195006_add_username_fields_to_users_table.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| use Illuminate\Database\Migrations\Migration; | ||
| use Illuminate\Database\Schema\Blueprint; | ||
| use Illuminate\Support\Facades\Schema; | ||
|
|
||
| return new class extends Migration | ||
| { | ||
| public function up(): void | ||
| { | ||
| Schema::table('users', static function (Blueprint $table): void { | ||
| $table->timestampTz('username_manually_set_at')->nullable()->after('username'); | ||
| $table->timestampTz('username_updated_at')->nullable()->after('username_manually_set_at'); | ||
| }); | ||
| } | ||
|
|
||
| public function down(): void | ||
| { | ||
| Schema::table('users', static function (Blueprint $table): void { | ||
| $table->dropColumn(['username_manually_set_at', 'username_updated_at']); | ||
| }); | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace He4rt\Identity\User\Actions; | ||
|
|
||
| use He4rt\Identity\User\Exceptions\UsernameException; | ||
| use He4rt\Identity\User\Models\User; | ||
| use He4rt\Identity\User\ValueObjects\UsernameValidator; | ||
| use Illuminate\Database\UniqueConstraintViolationException; | ||
| use Illuminate\Support\Facades\DB; | ||
|
|
||
| final class UpdateUsername | ||
| { | ||
| /** | ||
| * @throws UsernameException | ||
| */ | ||
| public function handle(User $user, string $newUsername): User | ||
| { | ||
| $normalized = UsernameValidator::normalizeAndValidate($newUsername, $user); | ||
|
|
||
| if ($normalized === mb_strtolower($user->username)) { | ||
| throw UsernameException::sameAsCurrent(); | ||
| } | ||
|
|
||
| if ($user->username_updated_at !== null && !$user->isAdmin()) { | ||
| $cooldownDays = (int) config('he4rt.username_cooldown_days', 7); | ||
| $availableAt = $user->username_updated_at->copy()->addDays($cooldownDays); | ||
|
|
||
| if (now()->lessThan($availableAt)) { | ||
| throw UsernameException::cooldownActive($availableAt); | ||
| } | ||
| } | ||
|
|
||
| $isTaken = User::query() | ||
| ->whereRaw('LOWER(username) = ?', [$normalized]) | ||
| ->where('id', '!=', $user->id) | ||
| ->exists(); | ||
|
|
||
| if ($isTaken) { | ||
| throw UsernameException::alreadyTaken($normalized); | ||
| } | ||
|
|
||
| try { | ||
| DB::transaction(function () use ($user, $normalized): void { | ||
| $user->update([ | ||
| 'username' => $normalized, | ||
| 'username_updated_at' => now(), | ||
| 'username_manually_set_at' => $user->username_manually_set_at ?? now(), | ||
| ]); | ||
| }); | ||
| } catch (UniqueConstraintViolationException) { | ||
| throw UsernameException::alreadyTaken($normalized); | ||
| } | ||
|
|
||
| return $user->refresh(); | ||
| } | ||
|
|
||
| /** | ||
| * Alias for handle | ||
| * | ||
| * @throws UsernameException | ||
| */ | ||
| public function execute(User $user, string $newUsername): User | ||
| { | ||
| return $this->handle($user, $newUsername); | ||
| } | ||
| } |
99 changes: 99 additions & 0 deletions
99
app-modules/identity/src/User/Exceptions/UsernameException.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace He4rt\Identity\User\Exceptions; | ||
|
|
||
| use Carbon\CarbonInterface; | ||
| use Exception; | ||
| use Throwable; | ||
|
|
||
| final class UsernameException extends Exception | ||
| { | ||
| /** | ||
| * @param array<string, mixed> $translationParams | ||
| */ | ||
| public function __construct( | ||
| string $message = '', | ||
| int $code = 422, | ||
| ?Throwable $previous = null, | ||
| public readonly ?string $translationKey = null, | ||
| public readonly array $translationParams = [], | ||
| ) { | ||
| parent::__construct($message, $code, $previous); | ||
| } | ||
|
|
||
| public static function alreadyTaken(string $username): self | ||
| { | ||
| return new self( | ||
| sprintf('O @%s já está em uso por outro membro.', $username), | ||
| 422, | ||
| translationKey: 'panel-app::profile.validation.username_already_taken', | ||
| translationParams: ['username' => $username], | ||
| ); | ||
| } | ||
|
|
||
| public static function invalidFormat(string $reason, ?string $reasonKey = null): self | ||
| { | ||
| return new self( | ||
| sprintf('Formato de @ inválido: %s.', $reason), | ||
| 422, | ||
| translationKey: 'panel-app::profile.validation.username_invalid_format', | ||
| translationParams: ['reason' => $reason, 'reason_key' => $reasonKey], | ||
| ); | ||
| } | ||
|
|
||
| public static function cooldownActive(CarbonInterface $availableAt): self | ||
| { | ||
| $timezone = (string) config('app.display_timezone', 'America/Sao_Paulo'); | ||
| $formattedDate = $availableAt->timezone($timezone)->format('d/m/Y H:i'); | ||
|
|
||
| return new self( | ||
| sprintf('Você só poderá alterar seu @ novamente a partir de %s.', $formattedDate), | ||
| 422, | ||
| translationKey: 'panel-app::profile.validation.username_cooldown_active', | ||
| translationParams: ['date' => $formattedDate], | ||
| ); | ||
| } | ||
|
|
||
| public static function sameAsCurrent(): self | ||
| { | ||
| return new self( | ||
| 'O novo @ deve ser diferente do atual.', | ||
| 422, | ||
| translationKey: 'panel-app::profile.validation.username_same_as_current', | ||
| ); | ||
| } | ||
|
|
||
| public static function reservedUsername(string $username): self | ||
| { | ||
| return new self( | ||
| sprintf('O @%s está reservado para o sistema e não pode ser utilizado.', $username), | ||
| 422, | ||
| translationKey: 'panel-app::profile.validation.username_reserved', | ||
| translationParams: ['username' => $username], | ||
| ); | ||
| } | ||
|
|
||
| public function getLocalizedMessage(): string | ||
| { | ||
| if ($this->translationKey !== null) { | ||
| $params = $this->translationParams; | ||
| if (isset($params['reason_key']) && is_string($params['reason_key'])) { | ||
| $translatedReason = __($params['reason_key']); | ||
| if ($translatedReason !== $params['reason_key']) { | ||
| $params['reason'] = $translatedReason; | ||
| } | ||
|
|
||
| unset($params['reason_key']); | ||
| } | ||
|
|
||
| $translated = __($this->translationKey, $params); | ||
| if ($translated !== $this->translationKey) { | ||
| return $translated; | ||
| } | ||
| } | ||
|
|
||
| return $this->getMessage(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
app-modules/identity/src/User/ValueObjects/UsernameValidator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace He4rt\Identity\User\ValueObjects; | ||
|
|
||
| use He4rt\Identity\User\Exceptions\UsernameException; | ||
| use He4rt\Identity\User\Models\User; | ||
|
|
||
| final class UsernameValidator | ||
| { | ||
| /** | ||
| * @var list<string> | ||
| */ | ||
| public const array RESERVED_USERNAMES = [ | ||
| 'admin', | ||
| 'administrator', | ||
| 'system', | ||
| 'root', | ||
| 'he4rt', | ||
| 'heart', | ||
| 'he4rtdevs', | ||
| 'mod', | ||
| 'moderator', | ||
| 'staff', | ||
| 'support', | ||
| 'help', | ||
| 'api', | ||
| 'bot', | ||
| 'null', | ||
| 'undefined', | ||
| 'anonymous', | ||
| 'everyone', | ||
| 'here', | ||
| ]; | ||
|
|
||
| /** | ||
| * @throws UsernameException | ||
| */ | ||
| public static function normalizeAndValidate(string $username, ?User $user = null): string | ||
| { | ||
| $normalized = mb_strtolower(mb_trim($username)); | ||
| $length = mb_strlen($normalized); | ||
|
|
||
| if ($length < 2 || $length > 32) { | ||
| throw UsernameException::invalidFormat( | ||
| 'o tamanho deve ter entre 2 e 32 caracteres', | ||
| 'panel-app::profile.validation.username_reason_length', | ||
| ); | ||
| } | ||
|
|
||
| if (!preg_match('/^[a-z0-9._-]+$/', $normalized)) { | ||
| throw UsernameException::invalidFormat( | ||
| 'apenas letras, números, sublinhado (_), hífen (-) e ponto (.) são permitidos', | ||
| 'panel-app::profile.validation.username_reason_characters', | ||
| ); | ||
| } | ||
|
|
||
| if (!preg_match('/^[a-z0-9]/', $normalized) || !preg_match('/[a-z0-9]$/', $normalized)) { | ||
| throw UsernameException::invalidFormat( | ||
| 'não pode começar ou terminar com caracteres especiais', | ||
| 'panel-app::profile.validation.username_reason_edges', | ||
| ); | ||
| } | ||
|
|
||
| if (preg_match('/[._-]{2,}/', $normalized)) { | ||
| throw UsernameException::invalidFormat( | ||
| 'não pode conter caracteres especiais consecutivos', | ||
| 'panel-app::profile.validation.username_reason_consecutive', | ||
| ); | ||
| } | ||
|
|
||
| if (in_array($normalized, self::RESERVED_USERNAMES, strict: true)) { | ||
| throw UsernameException::reservedUsername($normalized); | ||
| } | ||
|
|
||
| $adminsConfig = (string) config('he4rt.admins', ''); | ||
| $adminEntries = array_filter(array_map(trim(...), explode(',', $adminsConfig))); | ||
| $adminNames = array_map(strtolower(...), $adminEntries); | ||
|
|
||
| if (in_array($normalized, $adminNames, strict: true)) { | ||
| $isOwnAdminUsername = $user instanceof User && ( | ||
| mb_strtolower($user->username) === $normalized | ||
| || in_array(mb_strtolower($user->id), $adminNames, strict: true) | ||
| ); | ||
|
|
||
| if (!$isOwnAdminUsername) { | ||
| throw UsernameException::reservedUsername($normalized); | ||
| } | ||
| } | ||
|
|
||
| return $normalized; | ||
| } | ||
|
|
||
| /** | ||
| * @throws UsernameException | ||
| */ | ||
| public static function validate(string $username, ?User $user = null): string | ||
| { | ||
| return self::normalizeAndValidate($username, $user); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Acho que vale também adicionar os nomes em portuguê, como reservado também.