Username Handling

- When a new user is created using Discord OAuth information, if the username returned from Discord is already taken, append randomness to the end of the username.
- Validates that a new account name is unique.
- Validates that an updated account name is unique.
This commit is contained in:
Refringe 2024-09-30 16:43:31 -04:00
parent 7a68e31f30
commit 0d043ff880
Signed by: Refringe
SSH Key Fingerprint: SHA256:t865XsQpfTeqPRBMN2G6+N8wlDjkgUCZF3WGW6O9N/k
3 changed files with 12 additions and 4 deletions

View File

@ -20,7 +20,7 @@ class CreateNewUser implements CreatesNewUsers
public function create(array $input): User
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'name' => ['required', 'string', 'max:36', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',

View File

@ -16,7 +16,7 @@ class UpdateUserProfileInformation implements UpdatesUserProfileInformation
public function update(User $user, array $input): void
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'name' => ['required', 'string', 'max:255', Rule::unique('users')->ignore($user->id)],
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'],
'cover' => ['nullable', 'mimes:jpg,jpeg,png', 'max:2048'],

View File

@ -78,14 +78,22 @@ class SocialiteController extends Controller
return $oauthConnection->user;
}
// If the username already exists in the database, append a random string to it to ensure uniqueness.
$username = $providerUser->getName() ?? $providerUser->getNickname();
$random = '';
while (User::whereName($username.$random)->exists()) {
$random = '-'.Str::random(5);
}
$username .= $random;
// The user has not connected their account with this OAuth provider before, so a new connection needs to be
// established. Check if the user has an account with the same email address that's passed in from the provider.
// If one exists, connect that account. Otherwise, create a new one.
return DB::transaction(function () use ($providerUser, $provider) {
return DB::transaction(function () use ($providerUser, $provider, $username) {
$user = User::firstOrCreate(['email' => $providerUser->getEmail()], [
'name' => $providerUser->getName() ?? $providerUser->getNickname(),
'name' => $username,
'password' => null,
]);