Fix invalid generated password when login with facebook or google

This commit is contained in:
2025-04-09 15:49:30 -04:00
parent 837458c526
commit 46b1dae2ad
3 changed files with 16 additions and 10 deletions

View File

@@ -1,4 +1,5 @@
using System.Text;
using System.Security.Cryptography;
using System.Text;
namespace Hutopy.Web.Common.Security;
@@ -13,15 +14,18 @@ public static class PasswordGenerator
private static readonly Random Random = new();
public static string GeneratePassword(
int minLength,
int maxLength,
int length = 15,
bool requireNumber = true,
bool requireLowercase = true,
bool requireCapital = true,
bool requireSpecialCharacter = true)
{
// Create pools based on the requirements
var characterPool = new StringBuilder(LowerLetters);
var characterPool = new StringBuilder();
if (requireNumber)
characterPool.Append(LowerLetters);
if (requireCapital)
characterPool.Append(UpperLetters);
@@ -32,12 +36,14 @@ public static class PasswordGenerator
characterPool.Append(SpecialCharacters);
// Ensure that the length is within the specified bounds
int length = Random.Next(minLength, maxLength + 1);
var password = new char[length];
// Ensure at least one character from each required category is included
int index = 0;
if (requireLowercase)
password[index++] = LowerLetters[Random.Next(LowerLetters.Length)];
if (requireCapital)
password[index++] = UpperLetters[Random.Next(UpperLetters.Length)];
@@ -46,11 +52,11 @@ public static class PasswordGenerator
if (requireSpecialCharacter)
password[index++] = SpecialCharacters[Random.Next(SpecialCharacters.Length)];
// Fill the rest of the password
// Fill the rest with the password
for (int i = index; i < length; i++)
{
password[i] = characterPool[Random.Next(characterPool.Length)];
password[i] = characterPool[RandomNumberGenerator.GetInt32(characterPool.Length)];
}
// Shuffle the password to randomize the placement of the required characters

View File

@@ -83,7 +83,7 @@ public class LoginWithFacebookHandler(
if (user is null)
{
var generatedPassword = PasswordGenerator.GeneratePassword(10, 12);
var generatedPassword = PasswordGenerator.GeneratePassword();
var generatedUser = new IdentityUser
{
UserName = userInfo.Email ?? $"fb_{userInfo.Id}",

View File

@@ -90,7 +90,7 @@ public class LoginWithGoogleHandler(
if (user is null)
{
var generatedPassword = PasswordGenerator.GeneratePassword(10, 12);
var generatedPassword = PasswordGenerator.GeneratePassword();
var generatedUser = new IdentityUser
{
UserName = userInfo.Email,