diff --git a/.idea/.idea.Foxnouns.NET/.idea/CSharpierPlugin.xml b/.idea/.idea.Foxnouns.NET/.idea/CSharpierPlugin.xml
new file mode 100644
index 0000000..5e24061
--- /dev/null
+++ b/.idea/.idea.Foxnouns.NET/.idea/CSharpierPlugin.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Foxnouns.Backend/Controllers/Authentication/EmailAuthController.cs b/Foxnouns.Backend/Controllers/Authentication/EmailAuthController.cs
index 41eab25..937ab3a 100644
--- a/Foxnouns.Backend/Controllers/Authentication/EmailAuthController.cs
+++ b/Foxnouns.Backend/Controllers/Authentication/EmailAuthController.cs
@@ -183,10 +183,48 @@ public class EmailAuthController(
[HttpPost("add")]
[Authorize("*")]
- public async Task AddEmailAddressAsync()
+ public async Task AddEmailAddressAsync([FromBody] AddEmailAddressRequest req)
{
- _logger.Information("beep");
+ var emails = await db
+ .AuthMethods.Where(m => m.UserId == CurrentUser!.Id && m.AuthType == AuthType.Email)
+ .ToListAsync();
+ if (emails.Count > AuthUtils.MaxAuthMethodsPerType)
+ {
+ throw new ApiError.BadRequest(
+ "Too many email addresses, maximum of 3 per account.",
+ "email",
+ null
+ );
+ }
+ if (emails.Count != 0)
+ {
+ var validPassword = await authService.ValidatePasswordAsync(CurrentUser!, req.Password);
+ if (!validPassword)
+ {
+ throw new ApiError.Forbidden("Invalid password");
+ }
+ }
+ else
+ {
+ await authService.SetUserPasswordAsync(CurrentUser!, req.Password);
+ await db.SaveChangesAsync();
+ }
+
+ var state = await keyCacheService.GenerateRegisterEmailStateAsync(
+ req.Email,
+ userId: CurrentUser!.Id
+ );
+
+ var emailExists = await db
+ .AuthMethods.Where(m => m.AuthType == AuthType.Email && m.RemoteId == req.Email)
+ .AnyAsync();
+ if (emailExists)
+ {
+ return NoContent();
+ }
+
+ mailService.QueueAddEmailAddressEmail(req.Email, state, CurrentUser.Username);
return NoContent();
}
diff --git a/Foxnouns.Backend/ExpectedError.cs b/Foxnouns.Backend/ExpectedError.cs
index 0630892..fdd0b5d 100644
--- a/Foxnouns.Backend/ExpectedError.cs
+++ b/Foxnouns.Backend/ExpectedError.cs
@@ -42,7 +42,7 @@ public class ApiError(
IReadOnlyDictionary>? errors = null
) : ApiError(message, statusCode: HttpStatusCode.BadRequest)
{
- public BadRequest(string message, string field, object actualValue)
+ public BadRequest(string message, string field, object? actualValue)
: this(
"Error validating input",
new Dictionary>
diff --git a/Foxnouns.Backend/Mailables/AddEmailMailable.cs b/Foxnouns.Backend/Mailables/AddEmailMailable.cs
new file mode 100644
index 0000000..ee5792d
--- /dev/null
+++ b/Foxnouns.Backend/Mailables/AddEmailMailable.cs
@@ -0,0 +1,18 @@
+using Coravel.Mailer.Mail;
+
+namespace Foxnouns.Backend.Mailables;
+
+public class AddEmailMailable(Config config, AddEmailMailableView view)
+ : Mailable
+{
+ public override void Build()
+ {
+ To(view.To).From(config.EmailAuth.From!).View("~/Views/Mail/AddEmail.cshtml", view);
+ }
+}
+
+public class AddEmailMailableView : BaseView
+{
+ public required string Code { get; init; }
+ public required string Username { get; init; }
+}
diff --git a/Foxnouns.Backend/Services/AuthService.cs b/Foxnouns.Backend/Services/AuthService.cs
index 1aaa5e4..d03496c 100644
--- a/Foxnouns.Backend/Services/AuthService.cs
+++ b/Foxnouns.Backend/Services/AuthService.cs
@@ -135,6 +135,43 @@ public class AuthService(IClock clock, DatabaseContext db, ISnowflakeGenerator s
MfaRequired,
}
+ ///
+ /// Validates a user's password outside an authentication context, for when a password is required for changing
+ /// a setting, such as adding a new email address or changing passwords.
+ ///
+ public async Task ValidatePasswordAsync(
+ User user,
+ string password,
+ CancellationToken ct = default
+ )
+ {
+ if (user.Password == null)
+ {
+ throw new FoxnounsError("Password for user supplied to ValidatePasswordAsync was null");
+ }
+
+ var pwResult = await Task.Run(
+ () => _passwordHasher.VerifyHashedPassword(user, user.Password!, password),
+ ct
+ );
+ return pwResult
+ is PasswordVerificationResult.SuccessRehashNeeded
+ or PasswordVerificationResult.Success;
+ }
+
+ ///
+ /// Sets or updates a password for the given user. This method does not save the updated password automatically.
+ ///
+ public async Task SetUserPasswordAsync(
+ User user,
+ string password,
+ CancellationToken ct = default
+ )
+ {
+ user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
+ db.Update(user);
+ }
+
///
/// Authenticates a user with a remote authentication provider.
///
diff --git a/Foxnouns.Backend/Services/MailService.cs b/Foxnouns.Backend/Services/MailService.cs
index c605866..888f5fb 100644
--- a/Foxnouns.Backend/Services/MailService.cs
+++ b/Foxnouns.Backend/Services/MailService.cs
@@ -33,4 +33,31 @@ public class MailService(ILogger logger, IMailer mailer, IQueue queue, Config co
}
});
}
+
+ public void QueueAddEmailAddressEmail(string to, string code, string username)
+ {
+ _logger.Debug("Sending add email address email to {ToEmail}", to);
+ queue.QueueAsyncTask(async () =>
+ {
+ try
+ {
+ await mailer.SendAsync(
+ new AddEmailMailable(
+ config,
+ new AddEmailMailableView
+ {
+ BaseUrl = config.BaseUrl,
+ To = to,
+ Code = code,
+ Username = username,
+ }
+ )
+ );
+ }
+ catch (Exception exc)
+ {
+ _logger.Error(exc, "Sending add email address email");
+ }
+ });
+ }
}
diff --git a/Foxnouns.Backend/Views/Mail/AddEmail.cshtml b/Foxnouns.Backend/Views/Mail/AddEmail.cshtml
new file mode 100644
index 0000000..dabef6c
--- /dev/null
+++ b/Foxnouns.Backend/Views/Mail/AddEmail.cshtml
@@ -0,0 +1,12 @@
+@model Foxnouns.Backend.Mailables.AddEmailMailableView
+
+
+ Hello @@@Model.Username, please confirm adding this email address to your account by using the following link:
+
+ Confirm your email address
+
+ Note that this link will expire in one hour.
+
+
+ If you didn't mean to link this email address to @@@Model.Username, feel free to ignore this email.
+
\ No newline at end of file
diff --git a/Foxnouns.Frontend/app/lib/request.server.ts b/Foxnouns.Frontend/app/lib/request.server.ts
index c92f67d..562666d 100644
--- a/Foxnouns.Frontend/app/lib/request.server.ts
+++ b/Foxnouns.Frontend/app/lib/request.server.ts
@@ -11,7 +11,7 @@ export type RequestParams = {
isInternal?: boolean;
};
-async function requestInternal(
+export async function baseRequest(
method: string,
path: string,
params: RequestParams = {},
@@ -44,7 +44,7 @@ async function requestInternal(
}
export async function fastRequest(method: string, path: string, params: RequestParams = {}) {
- await requestInternal(method, path, params);
+ await baseRequest(method, path, params);
}
export default async function serverRequest(
@@ -52,7 +52,7 @@ export default async function serverRequest(
path: string,
params: RequestParams = {},
) {
- const resp = await requestInternal(method, path, params);
+ const resp = await baseRequest(method, path, params);
return (await resp.json()) as T;
}
diff --git a/Foxnouns.Frontend/app/routes/settings.auth/route.tsx b/Foxnouns.Frontend/app/routes/settings.auth/route.tsx
new file mode 100644
index 0000000..22d2fcd
--- /dev/null
+++ b/Foxnouns.Frontend/app/routes/settings.auth/route.tsx
@@ -0,0 +1,76 @@
+import i18n from "~/i18next.server";
+import { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
+import { Link, useRouteLoaderData } from "@remix-run/react";
+import { Button, ListGroup } from "react-bootstrap";
+import { loader as settingsLoader } from "~/routes/settings/route";
+import { useTranslation } from "react-i18next";
+import { AuthMethod, MeUser } from "~/lib/api/user";
+
+export const meta: MetaFunction = ({ data }) => {
+ return [{ title: `${data?.meta.title || "Authentication"} • pronouns.cc` }];
+};
+
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ const t = await i18n.getFixedT(request);
+ return { meta: { title: t("settings.auth.title") } };
+};
+
+export default function AuthSettings() {
+ const { user } = useRouteLoaderData("routes/settings")!;
+
+ return (
+
+ >
+ );
+}
diff --git a/Foxnouns.Frontend/public/locales/en.json b/Foxnouns.Frontend/public/locales/en.json
index c35a1d7..5a25098 100644
--- a/Foxnouns.Frontend/public/locales/en.json
+++ b/Foxnouns.Frontend/public/locales/en.json
@@ -107,6 +107,23 @@
"role": "Account role",
"username-update-error": "Could not update your username as the new username is invalid:\n{{message}}"
},
+ "auth": {
+ "title": "Authentication",
+ "form": {
+ "add-first-email": "Set an email address",
+ "add-extra-email": "Add another email address",
+ "email-address": "Email address",
+ "password-1": "Password",
+ "password-2": "Confirm password",
+ "add-email-button": "Add email address"
+ },
+ "no-email": "You haven't linked any email addresses yet. You can add one using this form.",
+ "new-email-pending": "Email address added! Click the link in your inbox to confirm.",
+ "email-link-success": "Email successfully linked",
+ "redirect-to-auth-hint": "You will be redirected back to the authentication page in a few seconds.",
+ "email-addresses": "Email addresses",
+ "remove-auth-method": "Remove"
+ },
"title": "Settings",
"nav": {
"general-information": "General information",