Compare commits
No commits in common. "e0303423583992571cacc5ffe1255890121938a9" and "7f971e8549adbb9b6b5f8f69b3410befae6337c6" have entirely different histories.
e030342358
...
7f971e8549
12 changed files with 6 additions and 381 deletions
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="com.intellij.csharpier">
|
||||
<option name="customPath" value="" />
|
||||
<option name="runOnSave" value="true" />
|
||||
</component>
|
||||
</project>
|
|
@ -183,48 +183,10 @@ public class EmailAuthController(
|
|||
|
||||
[HttpPost("add")]
|
||||
[Authorize("*")]
|
||||
public async Task<IActionResult> AddEmailAddressAsync([FromBody] AddEmailAddressRequest req)
|
||||
public async Task<IActionResult> AddEmailAddressAsync()
|
||||
{
|
||||
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
|
||||
);
|
||||
}
|
||||
_logger.Information("beep");
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
|
|
|
@ -42,7 +42,7 @@ public class ApiError(
|
|||
IReadOnlyDictionary<string, IEnumerable<ValidationError>>? 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<string, IEnumerable<ValidationError>>
|
||||
|
|
|
@ -1,18 +0,0 @@
|
|||
using Coravel.Mailer.Mail;
|
||||
|
||||
namespace Foxnouns.Backend.Mailables;
|
||||
|
||||
public class AddEmailMailable(Config config, AddEmailMailableView view)
|
||||
: Mailable<AddEmailMailableView>
|
||||
{
|
||||
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; }
|
||||
}
|
|
@ -135,43 +135,6 @@ public class AuthService(IClock clock, DatabaseContext db, ISnowflakeGenerator s
|
|||
MfaRequired,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets or updates a password for the given user. This method does <i>not</i> save the updated password automatically.
|
||||
/// </summary>
|
||||
public async Task SetUserPasswordAsync(
|
||||
User user,
|
||||
string password,
|
||||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
|
||||
db.Update(user);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authenticates a user with a remote authentication provider.
|
||||
/// </summary>
|
||||
|
|
|
@ -33,31 +33,4 @@ 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");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,12 +0,0 @@
|
|||
@model Foxnouns.Backend.Mailables.AddEmailMailableView
|
||||
|
||||
<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/>
|
||||
Note that this link will expire in one hour.
|
||||
</p>
|
||||
<p>
|
||||
If you didn't mean to link this email address to @@@Model.Username, feel free to ignore this email.
|
||||
</p>
|
|
@ -11,7 +11,7 @@ export type RequestParams = {
|
|||
isInternal?: boolean;
|
||||
};
|
||||
|
||||
export async function baseRequest(
|
||||
async function requestInternal(
|
||||
method: string,
|
||||
path: string,
|
||||
params: RequestParams = {},
|
||||
|
@ -44,7 +44,7 @@ export async function baseRequest(
|
|||
}
|
||||
|
||||
export async function fastRequest(method: string, path: string, params: RequestParams = {}) {
|
||||
await baseRequest(method, path, params);
|
||||
await requestInternal(method, path, params);
|
||||
}
|
||||
|
||||
export default async function serverRequest<T>(
|
||||
|
@ -52,7 +52,7 @@ export default async function serverRequest<T>(
|
|||
path: string,
|
||||
params: RequestParams = {},
|
||||
) {
|
||||
const resp = await baseRequest(method, path, params);
|
||||
const resp = await requestInternal(method, path, params);
|
||||
return (await resp.json()) as T;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,76 +0,0 @@
|
|||
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<typeof loader> = ({ 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<typeof settingsLoader>("routes/settings")!;
|
||||
|
||||
return (
|
||||
<div className="px-md-5">
|
||||
<EmailSettings user={user} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmailSettings({ user }: { user: MeUser }) {
|
||||
const { t } = useTranslation();
|
||||
const oneAuthMethod = user.auth_methods.length === 1;
|
||||
const emails = user.auth_methods.filter((m) => m.type === "EMAIL");
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3>{t("settings.auth.email-addresses")}</h3>
|
||||
{emails.length > 0 && (
|
||||
<>
|
||||
<ListGroup className="pt-2 pb-3">
|
||||
{emails.map((e) => (
|
||||
<EmailRow email={e} key={e.id} disabled={oneAuthMethod} />
|
||||
))}
|
||||
</ListGroup>
|
||||
</>
|
||||
)}
|
||||
{emails.length < 3 && (
|
||||
<p>
|
||||
{/* @ts-expect-error using as=Link causes an error here, even though it runs completely fine */}
|
||||
<Button variant="primary" as={Link} to="/settings/auth/add-email">
|
||||
{emails.length === 0
|
||||
? t("settings.auth.form.add-first-email")
|
||||
: t("settings.auth.form.add-extra-email")}
|
||||
</Button>
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function EmailRow({ email, disabled }: { email: AuthMethod; disabled: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<ListGroup.Item>
|
||||
<div className="row">
|
||||
<div className="col">{email.remote_id}</div>
|
||||
{!disabled && (
|
||||
<div className="col text-end">
|
||||
<Link to={`/settings/auth/remove-method/${email.id}`}>
|
||||
{t("settings.auth.remove-auth-method")}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ListGroup.Item>
|
||||
);
|
||||
}
|
|
@ -1,105 +0,0 @@
|
|||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
|
||||
import i18n from "~/i18next.server";
|
||||
import { json, useActionData, useNavigate, useRouteLoaderData } from "@remix-run/react";
|
||||
import { loader as settingsLoader } from "~/routes/settings/route";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect } from "react";
|
||||
import { Button, Card, Form } from "react-bootstrap";
|
||||
import { Form as RemixForm } from "@remix-run/react/dist/components";
|
||||
import { ApiError, ErrorCode } from "~/lib/api/error";
|
||||
import { fastRequest, getToken } from "~/lib/request.server";
|
||||
import ErrorAlert from "~/components/ErrorAlert";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ 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 const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const token = getToken(request)!;
|
||||
const body = await request.formData();
|
||||
const email = body.get("email") as string | null;
|
||||
const password = body.get("password-1") as string | null;
|
||||
const password2 = body.get("password-2") as string | null;
|
||||
|
||||
if (!email || !password || !password2) {
|
||||
return json({
|
||||
error: {
|
||||
status: 400,
|
||||
code: ErrorCode.BadRequest,
|
||||
message: "One or more required fields are missing.",
|
||||
} as ApiError,
|
||||
ok: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (password !== password2) {
|
||||
return json({
|
||||
error: {
|
||||
status: 400,
|
||||
code: ErrorCode.BadRequest,
|
||||
message: "Passwords do not match.",
|
||||
} as ApiError,
|
||||
ok: false,
|
||||
});
|
||||
}
|
||||
|
||||
await fastRequest("POST", "/auth/email/add", {
|
||||
body: { email, password },
|
||||
token,
|
||||
isInternal: true,
|
||||
});
|
||||
|
||||
return json({ error: null, ok: true });
|
||||
};
|
||||
|
||||
export default function AddEmailPage() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useRouteLoaderData<typeof settingsLoader>("routes/settings")!;
|
||||
const actionData = useActionData<typeof action>();
|
||||
const navigate = useNavigate();
|
||||
const emails = user.auth_methods.filter((m) => m.type === "EMAIL");
|
||||
|
||||
useEffect(() => {
|
||||
if (emails.length >= 3) {
|
||||
navigate("/settings/auth");
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<RemixForm method="POST">
|
||||
<Card body>
|
||||
<Card.Title>
|
||||
{emails.length === 0
|
||||
? t("settings.auth.form.add-first-email")
|
||||
: t("settings.auth.form.add-extra-email")}
|
||||
</Card.Title>
|
||||
{emails.length === 0 && !actionData?.ok && <p>{t("settings.auth.no-email")}</p>}
|
||||
{actionData?.ok && <p>{t("settings.auth.new-email-pending")}</p>}
|
||||
{actionData?.error && <ErrorAlert error={actionData.error} />}
|
||||
<Form as="div">
|
||||
<Form.Group className="mb-3" controlId="email-address">
|
||||
<Form.Label>{t("settings.auth.form.email-address")}</Form.Label>
|
||||
<Form.Control type="email" name="email" required disabled={actionData?.ok} />
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-3" controlId="password-1">
|
||||
<Form.Label>{t("settings.auth.form.password-1")}</Form.Label>
|
||||
<Form.Control type="password" name="password-1" required disabled={actionData?.ok} />
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-3" controlId="password-2">
|
||||
<Form.Label>{t("settings.auth.form.password-2")}</Form.Label>
|
||||
<Form.Control type="password" name="password-2" required disabled={actionData?.ok} />
|
||||
</Form.Group>
|
||||
<Button variant="primary" type="submit">
|
||||
{t("settings.auth.form.add-email-button")}
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
</RemixForm>
|
||||
);
|
||||
}
|
|
@ -1,38 +0,0 @@
|
|||
import { LoaderFunctionArgs, json } from "@remix-run/node";
|
||||
import { baseRequest } from "~/lib/request.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect } from "react";
|
||||
import { useNavigate } from "@remix-run/react";
|
||||
|
||||
export const loader = async ({ params }: LoaderFunctionArgs) => {
|
||||
const state = params.code!;
|
||||
|
||||
const resp = await baseRequest("POST", "/auth/email/callback", {
|
||||
body: { state },
|
||||
isInternal: true,
|
||||
});
|
||||
if (resp.status !== 204) {
|
||||
// TODO: handle non-204 status (this indicates that the email was not linked to an account)
|
||||
}
|
||||
|
||||
return json({ ok: true });
|
||||
};
|
||||
|
||||
export default function ConfirmEmailPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
navigate("/settings/auth");
|
||||
}, 2000);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3>{t("settings.auth.email-link-success")}</h3>
|
||||
<p>{t("settings.auth.redirect-to-auth-hint")}</p>
|
||||
</>
|
||||
);
|
||||
}
|
|
@ -107,23 +107,6 @@
|
|||
"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",
|
||||
|
|
Loading…
Reference in a new issue