feat(frontend): register/log in with email

This commit is contained in:
sam 2024-12-04 17:43:02 +01:00
parent 57e1ec09c0
commit bc7fd6d804
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
19 changed files with 598 additions and 380 deletions

View file

@ -119,6 +119,20 @@ public class AuthController(
CurrentUser!.Id
);
// If this is the user's last email, we should also clear the user's password.
if (
authMethod.AuthType == AuthType.Email
&& authMethods.Count(a => a.AuthType == AuthType.Email) == 1
)
{
_logger.Debug(
"Deleted last email address for user {UserId}, resetting their password",
CurrentUser.Id
);
CurrentUser.Password = null;
db.Update(CurrentUser);
}
db.Remove(authMethod);
await db.SaveChangesAsync();

View file

@ -1,3 +1,5 @@
using System.Net;
using EntityFramework.Exceptions.Common;
using Foxnouns.Backend.Database;
using Foxnouns.Backend.Database.Models;
using Foxnouns.Backend.Extensions;
@ -26,8 +28,8 @@ public class EmailAuthController(
{
private readonly ILogger _logger = logger.ForContext<EmailAuthController>();
[HttpPost("register")]
public async Task<IActionResult> RegisterAsync(
[HttpPost("register/init")]
public async Task<IActionResult> RegisterInitAsync(
[FromBody] RegisterRequest req,
CancellationToken ct = default
)
@ -62,25 +64,9 @@ public class EmailAuthController(
CheckRequirements();
var state = await keyCacheService.GetRegisterEmailStateAsync(req.State);
if (state == null)
if (state is not { ExistingUserId: null })
throw new ApiError.BadRequest("Invalid state", "state", req.State);
// If this callback is for an existing user, add the email address to their auth methods
if (state.ExistingUserId != null)
{
var authMethod = await authService.AddAuthMethodAsync(
state.ExistingUserId.Value,
AuthType.Email,
state.Email
);
_logger.Debug(
"Added email auth {AuthId} for user {UserId}",
authMethod.Id,
state.ExistingUserId
);
return NoContent();
}
var ticket = AuthUtils.RandomToken();
await keyCacheService.SetKeyAsync($"email:{ticket}", state.Email, Duration.FromMinutes(20));
@ -96,7 +82,7 @@ public class EmailAuthController(
);
}
[HttpPost("complete-registration")]
[HttpPost("register")]
public async Task<IActionResult> CompleteRegistrationAsync(
[FromBody] CompleteRegistrationRequest req
)
@ -107,12 +93,6 @@ public class EmailAuthController(
if (email == null)
throw new ApiError.BadRequest("Unknown ticket", "ticket", req.Ticket);
// Check if username is valid at all
ValidationUtils.Validate([("username", ValidationUtils.ValidateUsername(req.Username))]);
// Check if username is already taken
if (await db.Users.AnyAsync(u => u.Username == req.Username))
throw new ApiError.BadRequest("Username is already taken", "username", req.Username);
var user = await authService.CreateUserWithPasswordAsync(req.Username, email, req.Password);
var frontendApp = await db.GetFrontendApplicationAsync();
@ -184,7 +164,21 @@ public class EmailAuthController(
);
}
[HttpPost("add")]
[HttpPost("change-password")]
[Authorize("*")]
public async Task<IActionResult> UpdatePasswordAsync([FromBody] ChangePasswordRequest req)
{
if (!await authService.ValidatePasswordAsync(CurrentUser!, req.Current))
throw new ApiError.Forbidden("Invalid password");
ValidationUtils.Validate([("new", ValidationUtils.ValidatePassword(req.New))]);
await authService.SetUserPasswordAsync(CurrentUser!, req.New);
await db.SaveChangesAsync();
return NoContent();
}
[HttpPost("add-email")]
[Authorize("*")]
public async Task<IActionResult> AddEmailAddressAsync([FromBody] AddEmailAddressRequest req)
{
@ -204,11 +198,8 @@ public class EmailAuthController(
if (emails.Count != 0)
{
var validPassword = await authService.ValidatePasswordAsync(CurrentUser!, req.Password);
if (!validPassword)
{
if (!await authService.ValidatePasswordAsync(CurrentUser!, req.Password))
throw new ApiError.Forbidden("Invalid password");
}
}
else
{
@ -233,6 +224,48 @@ public class EmailAuthController(
return NoContent();
}
[HttpPost("add-email/callback")]
[Authorize("*")]
public async Task<IActionResult> AddEmailCallbackAsync([FromBody] CallbackRequest req)
{
CheckRequirements();
var state = await keyCacheService.GetRegisterEmailStateAsync(req.State);
if (state?.ExistingUserId != CurrentUser!.Id)
throw new ApiError.BadRequest("Invalid state", "state", req.State);
try
{
var authMethod = await authService.AddAuthMethodAsync(
CurrentUser.Id,
AuthType.Email,
state.Email
);
_logger.Debug(
"Added email auth {AuthId} for user {UserId}",
authMethod.Id,
CurrentUser.Id
);
return Ok(
new AuthController.AddOauthAccountResponse(
authMethod.Id,
AuthType.Email,
authMethod.RemoteId,
RemoteUsername: null
)
);
}
catch (UniqueConstraintException)
{
throw new ApiError(
"That email address is already linked.",
HttpStatusCode.BadRequest,
ErrorCode.AccountAlreadyLinked
);
}
}
public record AddEmailAddressRequest(string Email, string Password);
private void CheckRequirements()
@ -248,4 +281,6 @@ public class EmailAuthController(
public record CompleteRegistrationRequest(string Ticket, string Username, string Password);
public record CallbackRequest(string State);
public record ChangePasswordRequest(string Current, string New);
}

View file

@ -25,7 +25,7 @@ public static class KeyCacheExtensions
CancellationToken ct = default
)
{
var val = await keyCacheService.GetKeyAsync($"oauth_state:{state}", delete: true, ct);
var val = await keyCacheService.GetKeyAsync($"oauth_state:{state}", ct: ct);
if (val == null)
throw new ApiError.BadRequest("Invalid OAuth state");
}
@ -52,12 +52,7 @@ public static class KeyCacheExtensions
this KeyCacheService keyCacheService,
string state,
CancellationToken ct = default
) =>
await keyCacheService.GetKeyAsync<RegisterEmailState>(
$"email_state:{state}",
delete: true,
ct
);
) => await keyCacheService.GetKeyAsync<RegisterEmailState>($"email_state:{state}", ct: ct);
public static async Task<string> GenerateAddExtraAccountStateAsync(
this KeyCacheService keyCacheService,

View file

@ -31,6 +31,16 @@ public class AuthService(
CancellationToken ct = default
)
{
// Validate username and whether it's not taken
ValidationUtils.Validate(
[
("username", ValidationUtils.ValidateUsername(username)),
("password", ValidationUtils.ValidatePassword(password)),
]
);
if (await db.Users.AnyAsync(u => u.Username == username, ct))
throw new ApiError.BadRequest("Username is already taken", "username", username);
var user = new User
{
Id = snowflakeGenerator.GenerateSnowflake(),
@ -49,7 +59,7 @@ public class AuthService(
};
db.Add(user);
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
user.Password = await HashPasswordAsync(user, password, ct);
return user;
}
@ -70,6 +80,8 @@ public class AuthService(
{
AssertValidAuthType(authType, instance);
// Validate username and whether it's not taken
ValidationUtils.Validate([("username", ValidationUtils.ValidateUsername(username))]);
if (await db.Users.AnyAsync(u => u.Username == username, ct))
throw new ApiError.BadRequest("Username is already taken", "username", username);
@ -121,10 +133,7 @@ public class AuthService(
ErrorCode.UserNotFound
);
var pwResult = await Task.Run(
() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password),
ct
);
var pwResult = await VerifyHashedPasswordAsync(user, password, ct);
if (pwResult == PasswordVerificationResult.Failed) // TODO: this seems to fail on some valid passwords?
throw new ApiError.NotFound(
"No user with that email address found, or password is incorrect",
@ -132,7 +141,7 @@ public class AuthService(
);
if (pwResult == PasswordVerificationResult.SuccessRehashNeeded)
{
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
user.Password = await HashPasswordAsync(user, password, ct);
await db.SaveChangesAsync(ct);
}
@ -160,10 +169,7 @@ public class AuthService(
throw new FoxnounsError("Password for user supplied to ValidatePasswordAsync was null");
}
var pwResult = await Task.Run(
() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password),
ct
);
var pwResult = await VerifyHashedPasswordAsync(user, password, ct);
return pwResult
is PasswordVerificationResult.SuccessRehashNeeded
or PasswordVerificationResult.Success;
@ -178,7 +184,7 @@ public class AuthService(
CancellationToken ct = default
)
{
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
user.Password = await HashPasswordAsync(user, password, ct);
db.Update(user);
}
@ -316,6 +322,22 @@ public class AuthService(
);
}
private Task<string> HashPasswordAsync(
User user,
string password,
CancellationToken ct = default
) => Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
private Task<PasswordVerificationResult> VerifyHashedPasswordAsync(
User user,
string providedPassword,
CancellationToken ct = default
) =>
Task.Run(
() => _passwordHasher.VerifyHashedPassword(user, user.Password!, providedPassword),
ct
);
private static (string, byte[]) GenerateToken()
{
var token = AuthUtils.RandomToken();

View file

@ -185,6 +185,27 @@ public static partial class ValidationUtils
};
}
public const int MinimumPasswordLength = 12;
public const int MaximumPasswordLength = 1024;
public static ValidationError? ValidatePassword(string password) =>
password.Length switch
{
< MinimumPasswordLength => ValidationError.LengthError(
"Password is too short",
MinimumPasswordLength,
MaximumPasswordLength,
password.Length
),
> MaximumPasswordLength => ValidationError.LengthError(
"Password is too long",
MinimumPasswordLength,
MaximumPasswordLength,
password.Length
),
_ => null,
};
[GeneratedRegex(@"^[a-zA-Z_0-9\-\.]{2,40}$", RegexOptions.IgnoreCase, "en-NL")]
private static partial Regex UsernameRegex();

View file

@ -2,9 +2,9 @@
<p>
Please continue creating a new pronouns.cc account by using the following link:
<br/>
<a href="@Model.BaseUrl/auth/signup/confirm/@Model.Code">Confirm your email address</a>
<br/>
<br />
<a href="@Model.BaseUrl/auth/callback/email/@Model.Code">Confirm your email address</a>
<br />
Note that this link will expire in one hour.
</p>
<p>

View file

@ -2,9 +2,9 @@
<p>
Hello @@@Model.Username, please confirm adding this email address to your account by using the following link:
<br/>
<a href="@Model.BaseUrl/settings/auth/confirm-email/@Model.Code">Confirm your email address</a>
<br/>
<br />
<a href="@Model.BaseUrl/auth/callback/email/@Model.Code">Confirm your email address</a>
<br />
Note that this link will expire in one hour.
</p>
<p>