Compare commits

..

2 commits

Author SHA1 Message Date
sam
be34c4c77e
feat(frontend): working email login 2024-09-10 21:24:40 +02:00
sam
498d79de4e
feat(frontend): internationalization 2024-09-10 20:33:22 +02:00
20 changed files with 1174 additions and 177 deletions

View file

@ -0,0 +1,61 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<HTMLCodeStyleSettings>
<option name="HTML_SPACE_INSIDE_EMPTY_TAG" value="true" />
</HTMLCodeStyleSettings>
<JSCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
<option name="FORCE_QUOTE_STYlE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</JSCodeStyleSettings>
<TypeScriptCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
<option name="FORCE_QUOTE_STYlE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</TypeScriptCodeStyleSettings>
<VueCodeStyleSettings>
<option name="INTERPOLATION_NEW_LINE_AFTER_START_DELIMITER" value="false" />
<option name="INTERPOLATION_NEW_LINE_BEFORE_END_DELIMITER" value="false" />
</VueCodeStyleSettings>
<codeStyleSettings language="HTML">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="TypeScript">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Vue">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

View file

@ -121,6 +121,7 @@ public static class WebApplicationExtensions
public static async Task Initialize(this WebApplication app, string[] args)
{
// Read version information from .version in the repository root
await BuildInfo.ReadBuildInfo();
app.Services.ConfigureQueue().LogQueuedTaskProgress(app.Services.GetRequiredService<ILogger<IQueue>>());

View file

@ -9,9 +9,6 @@ using Newtonsoft.Json.Serialization;
using Prometheus;
using Sentry.Extensibility;
// Read version information from .version in the repository root
await BuildInfo.ReadBuildInfo();
var builder = WebApplication.CreateBuilder(args);
var config = builder.AddConfiguration();

View file

@ -81,11 +81,11 @@ public class AuthService(IClock clock, DatabaseContext db, ISnowflakeGenerator s
var user = await db.Users.FirstOrDefaultAsync(u =>
u.AuthMethods.Any(a => a.AuthType == AuthType.Email && a.RemoteId == email), ct);
if (user == null)
throw new ApiError.NotFound("No user with that email address found, or password is incorrect");
throw new ApiError.NotFound("No user with that email address found, or password is incorrect", ErrorCode.UserNotFound);
var pwResult = await Task.Run(() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password), ct);
if (pwResult == PasswordVerificationResult.Failed)
throw new ApiError.NotFound("No user with that email address found, or password is incorrect");
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", ErrorCode.UserNotFound);
if (pwResult == PasswordVerificationResult.SuccessRehashNeeded)
{
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);

View file

@ -7,6 +7,7 @@ import Nav from "react-bootstrap/Nav";
import Navbar from "react-bootstrap/Navbar";
import NavDropdown from "react-bootstrap/NavDropdown";
import { BrightnessHigh, BrightnessHighFill, MoonFill } from "react-bootstrap-icons";
import { useTranslation } from "react-i18next";
export default function MainNavbar({
user,
@ -17,23 +18,26 @@ export default function MainNavbar({
settings: UserSettings;
}) {
const fetcher = useFetcher();
const { t } = useTranslation();
const userMenu = user ? (
<NavDropdown title={<>@{user.username}</>} align="end">
<NavDropdown.Item as={Link} to={`/@${user.username}`}>
View profile
{t("navbar.view-profile")}
</NavDropdown.Item>
<NavDropdown.Item as={Link} to="/settings">
Settings
{t("navbar.settings")}
</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item as={Link} to="/auth/logout">
Log out
<fetcher.Form method="POST" action="/auth/log-out">
<NavDropdown.Item as="button" type="submit">
{t("navbar.log-out")}
</NavDropdown.Item>
</fetcher.Form>
</NavDropdown>
) : (
<Nav.Link to="/auth/login" as={Link}>
Log in or sign up
<Nav.Link to="/auth/log-in" as={Link}>
{t("navbar.log-in")}
</Nav.Link>
);
@ -59,19 +63,19 @@ export default function MainNavbar({
<NavDropdown
title={
<>
<ThemeIcon /> Theme
<ThemeIcon /> {t("navbar.theme")}
</>
}
align="end"
>
<NavDropdown.Item as="button" name="theme" value="auto" type="submit">
Automatic
{t("navbar.theme-auto")}
</NavDropdown.Item>
<NavDropdown.Item as="button" name="theme" value="dark" type="submit">
Dark mode
{t("navbar.theme-dark")}
</NavDropdown.Item>
<NavDropdown.Item as="button" name="theme" value="light" type="submit">
Light mode
{t("navbar.theme-light")}
</NavDropdown.Item>
</NavDropdown>
</fetcher.Form>

View file

@ -1,18 +1,50 @@
/**
* By default, Remix will handle hydrating your app on the client for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal`
* For more information, see https://remix.run/file-conventions/entry.client
*/
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import i18n from "./i18n";
import i18next from "i18next";
import { I18nextProvider, initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import { getInitialNamespaces } from "remix-i18next/client";
startTransition(() => {
async function hydrate() {
await i18next
.use(initReactI18next) // Tell i18next to use the react-i18next plugin
.use(LanguageDetector) // Set up a client-side language detector
.use(Backend) // Setup your backend
.init({
...i18n, // spread the configuration
// This function detects the namespaces your routes rendered while SSR use
ns: getInitialNamespaces(),
backend: { loadPath: "/locales/{{lng}}.json" },
detection: {
// Here only enable htmlTag detection, we'll detect the language only
// server-side with remix-i18next, by using the `<html lang>` attribute
// we can communicate to the client the language detected server-side
order: ["htmlTag"],
// Because we only use htmlTag, there's no reason to cache the language
// on the browser, so we disable it
caches: [],
},
});
startTransition(() => {
hydrateRoot(
document,
<I18nextProvider i18n={i18next}>
<StrictMode>
<RemixBrowser />
</StrictMode>,
</StrictMode>
</I18nextProvider>,
);
});
});
}
if (window.requestIdleCallback) {
window.requestIdleCallback(hydrate);
} else {
// Safari doesn't support requestIdleCallback
// https://caniuse.com/requestidlecallback
window.setTimeout(hydrate, 1);
}

View file

@ -1,56 +1,56 @@
/**
* By default, Remix will handle generating the HTTP Response for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal`
* For more information, see https://remix.run/file-conventions/entry.server
*/
import { PassThrough } from "node:stream";
import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { PassThrough } from "stream";
import { createReadableStreamFromReadable, type EntryContext } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";
import { createInstance } from "i18next";
import i18next from "./i18next.server";
import { I18nextProvider, initReactI18next } from "react-i18next";
import Backend from "i18next-fs-backend";
import i18n from "./i18n"; // your i18n configuration file
import { resolve } from "node:path";
const ABORT_DELAY = 5_000;
const ABORT_DELAY = 5000;
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext,
) {
return isbot(request.headers.get("user-agent") || "")
? handleBotRequest(request, responseStatusCode, responseHeaders, remixContext)
: handleBrowserRequest(request, responseStatusCode, responseHeaders, remixContext);
}
function handleBotRequest(
export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
const callbackName = isbot(request.headers.get("user-agent")) ? "onAllReady" : "onShellReady";
const instance = createInstance();
const lng = await i18next.getLocale(request);
const ns = i18next.getRouteNamespaces(remixContext);
await instance
.use(initReactI18next) // Tell our instance to use react-i18next
.use(Backend) // Set up our backend
.init({
...i18n, // spread the configuration
lng, // The locale we detected above
ns, // The namespaces the routes about to render wants to use
backend: { loadPath: resolve("./public/locales/{{lng}}.json") },
});
return new Promise((resolve, reject) => {
let shellRendered = false;
let didError = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer context={remixContext} url={request.url} abortDelay={ABORT_DELAY} />,
<I18nextProvider i18n={instance}>
<RemixServer context={remixContext} url={request.url} />
</I18nextProvider>,
{
onAllReady() {
shellRendered = true;
[callbackName]: () => {
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);
responseHeaders.set("Content-Type", "text/html");
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
status: didError ? 500 : responseStatusCode,
}),
);
@ -60,59 +60,9 @@ function handleBotRequest(
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
didError = true;
console.error(error);
}
},
},
);
setTimeout(abort, ABORT_DELAY);
});
}
function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer context={remixContext} url={request.url} abortDelay={ABORT_DELAY} />,
{
onShellReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);
responseHeaders.set("Content-Type", "text/html");
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
}),
);
pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
},
);

View file

@ -1,3 +1,4 @@
import { env } from "node:process";
export const API_BASE = env.API_BASE || "https://pronouns.localhost/api";
export const LANGUAGE = env.LANGUAGE || "en";

View file

@ -0,0 +1,5 @@
export default {
supportedLngs: ["en", "en-XX"],
fallbackLng: "en",
defaultNS: "common",
};

View file

@ -0,0 +1,28 @@
import Backend from "i18next-fs-backend";
import { resolve } from "node:path";
import { RemixI18Next } from "remix-i18next/server";
import i18n from "~/i18n";
import { LANGUAGE } from "~/env.server";
const i18next = new RemixI18Next({
detection: {
supportedLanguages: [LANGUAGE],
fallbackLanguage: LANGUAGE,
},
// This is the configuration for i18next used
// when translating messages server-side only
i18next: {
...i18n,
fallbackLng: LANGUAGE,
lng: LANGUAGE,
backend: {
loadPath: resolve("./public/locales/{{lng}}.json"),
},
},
// The i18next plugins you want RemixI18next to use for `i18n.getFixedT` inside loaders and actions.
// E.g. The Backend plugin for loading translations from the file system
// Tip: You could pass `resources` to the `i18next` configuration and avoid a backend here
plugins: [Backend],
});
export default i18next;

View file

@ -0,0 +1,7 @@
import { User } from "~/lib/api/user";
export type AuthResponse = {
user: User;
token: string;
expires_at: string;
};

View file

@ -7,8 +7,9 @@ import {
ScrollRestoration,
useLoaderData,
} from "@remix-run/react";
import { LoaderFunction } from "@remix-run/node";
import SSRProvider from "react-bootstrap/SSRProvider";
import { LoaderFunctionArgs } from "@remix-run/node";
import { useChangeLanguage } from "remix-i18next/react";
import { useTranslation } from "react-i18next";
import serverRequest, { getCookie, writeCookie } from "./lib/request.server";
import Meta from "./lib/api/meta";
@ -18,8 +19,9 @@ import { ApiError, ErrorCode } from "./lib/api/error";
import "./app.scss";
import getLocalSettings from "./lib/settings.server";
import { LANGUAGE } from "~/env.server";
export const loader: LoaderFunction = async ({ request }) => {
export const loader = async ({ request }: LoaderFunctionArgs) => {
const meta = await serverRequest<Meta>("GET", "/meta");
const token = getCookie(request, "pronounscc-token");
@ -29,8 +31,7 @@ export const loader: LoaderFunction = async ({ request }) => {
let settings = getLocalSettings(request);
if (token) {
try {
const user = await serverRequest<User>("GET", "/users/@me", { token });
meUser = user;
meUser = await serverRequest<User>("GET", "/users/@me", { token });
settings = await serverRequest<UserSettings>("GET", "/users/@me/settings", { token });
} catch (e) {
@ -42,7 +43,7 @@ export const loader: LoaderFunction = async ({ request }) => {
}
return json(
{ meta, meUser, settings },
{ meta, meUser, settings, locale: LANGUAGE },
{
headers: { "Set-Cookie": setCookie },
},
@ -50,10 +51,13 @@ export const loader: LoaderFunction = async ({ request }) => {
};
export function Layout({ children }: { children: React.ReactNode }) {
const { settings } = useLoaderData<typeof loader>();
const { settings, locale } = useLoaderData<typeof loader>();
const { i18n } = useTranslation();
i18n.language = locale;
useChangeLanguage(locale);
return (
<html lang="en" data-bs-theme={settings.dark_mode ? "dark" : "light"}>
<html lang={locale} data-bs-theme={settings.dark_mode ? "dark" : "light"} dir={i18n.dir()}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
@ -61,7 +65,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
<Links />
</head>
<body>
<SSRProvider>{children}</SSRProvider>
{children}
<ScrollRestoration />
<Scripts />
</body>

View file

@ -1,4 +1,4 @@
import { json, LoaderFunction, MetaFunction } from "@remix-run/node";
import { json, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { redirect, useLoaderData } from "@remix-run/react";
import { User } from "~/lib/api/user";
import serverRequest from "~/lib/request.server";
@ -9,7 +9,7 @@ export const meta: MetaFunction<typeof loader> = ({ data }) => {
return [{ title: `@${user.username} - pronouns.cc` }];
};
export const loader: LoaderFunction = async ({ params }) => {
export const loader = async ({ params }: LoaderFunctionArgs) => {
let username = params.username!;
if (!username.startsWith("@")) throw redirect(`/@${username}`);
username = username.substring("@".length);

View file

@ -6,40 +6,8 @@ export const meta: MetaFunction = () => {
export default function Index() {
return (
<div className="font-sans p-4">
<h1 className="text-3xl">Welcome to Remix</h1>
<ul className="list-disc mt-4 pl-6 space-y-2">
<li>
<a
className="text-blue-700 underline visited:text-purple-900"
target="_blank"
href="https://remix.run/start/quickstart"
rel="noreferrer"
>
5m Quick Start
</a>
</li>
<li>
<a
className="text-blue-700 underline visited:text-purple-900"
target="_blank"
href="https://remix.run/start/tutorial"
rel="noreferrer"
>
30m Tutorial
</a>
</li>
<li>
<a
className="text-blue-700 underline visited:text-purple-900"
target="_blank"
href="https://remix.run/docs"
rel="noreferrer"
>
Remix Docs
</a>
</li>
</ul>
<div>
<h1>pronouns.cc</h1>
</div>
);
}

View file

@ -0,0 +1,62 @@
import { MetaFunction, json, LoaderFunctionArgs, ActionFunction, redirect } from "@remix-run/node";
import { Form as RemixForm } from "@remix-run/react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import { useTranslation } from "react-i18next";
import i18n from "~/i18next.server";
import serverRequest, { writeCookie } from "~/lib/request.server";
import { AuthResponse } from "~/lib/api/auth";
export const meta: MetaFunction<typeof loader> = ({ data }) => {
return [{ title: `${data?.meta.title || "Log in"} - pronouns.cc` }];
};
export const loader = async ({ request }: LoaderFunctionArgs) => {
const t = await i18n.getFixedT(request);
return json({
meta: { title: t("log-in.title") },
});
};
export const action: ActionFunction = async ({ request }) => {
const body = await request.formData();
const email = body.get("email") as string | null;
const password = body.get("password") as string | null;
console.log(email, password);
const resp = await serverRequest<AuthResponse>("POST", "/auth/email/login", {
body: { email, password },
});
return redirect("/", {
status: 303,
headers: {
"Set-Cookie": writeCookie("pronounscc-token", resp.token),
},
});
};
export default function LoginPage() {
const { t } = useTranslation();
return (
<RemixForm action="/auth/log-in" method="POST">
<Form as="div">
<Form.Group className="mb-3" controlId="email">
<Form.Label>{t("log-in.email")}</Form.Label>
<Form.Control name="email" type="email" required />
</Form.Group>
<Form.Group className="mb-3" controlId="password">
<Form.Label>{t("log-in.password")}</Form.Label>
<Form.Control name="password" type="password" required />
</Form.Group>
<Button variant="primary" type="submit">
{t("log-in.log-in-button")}
</Button>
</Form>
</RemixForm>
);
}

View file

@ -0,0 +1,11 @@
import { ActionFunction } from "@remix-run/node";
import { writeCookie } from "~/lib/request.server";
export const action: ActionFunction = async () => {
return new Response(null, {
headers: {
"Set-Cookie": writeCookie("pronounscc-token", "token", 0),
},
status: 204,
});
};

View file

@ -0,0 +1,3 @@
export default {
locales: ["en"],
};

View file

@ -9,7 +9,8 @@
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "cross-env NODE_ENV=production node ./server.js",
"typecheck": "tsc",
"format": "prettier -w ."
"format": "prettier -w .",
"extract-translations": "i18next 'app/**/*.tsx' -o 'public/locales/$LOCALE.json'"
},
"dependencies": {
"@remix-run/express": "^2.11.2",
@ -22,12 +23,18 @@
"cookie": "^0.6.0",
"cross-env": "^7.0.3",
"express": "^4.19.2",
"i18next": "^23.15.1",
"i18next-browser-languagedetector": "^8.0.0",
"i18next-fs-backend": "^2.3.2",
"i18next-http-backend": "^2.6.1",
"isbot": "^4.1.0",
"morgan": "^1.10.0",
"react": "^18.2.0",
"react-bootstrap": "^2.10.4",
"react-bootstrap-icons": "^1.11.4",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"react-i18next": "^15.0.1",
"remix-i18next": "^6.3.0"
},
"devDependencies": {
"@fontsource/firago": "^5.0.11",
@ -46,6 +53,7 @@
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"i18next-parser": "^9.0.2",
"prettier": "^3.3.3",
"sass": "^1.78.0",
"typescript": "^5.1.6",

View file

@ -0,0 +1,18 @@
{
"navbar": {
"view-profile": "View profile",
"settings": "Settings",
"log-out": "Log out",
"log-in": "Log in or sign up",
"theme": "Theme",
"theme-auto": "Automatic",
"theme-dark": "Dark",
"theme-light": "Light"
},
"log-in": {
"title": "Log in",
"email": "Email address",
"password": "Password",
"log-in-button": "Log in"
}
}

File diff suppressed because it is too large Load diff