mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-25 23:43:12 +09:00
Address review of the Discord plugin
The plugin is now exp_discord_auth, so later Discord plugins can sit next to it. Config keys, permissions, routes and the Lua module moved with it, and the Discord redirect is now api/exp_discord_auth/callback. The controller registers its handlers and routes in the constructor and uses the express types, the instance plugin is a closure, and the Lua commands file returns its commands. The get and unlink responses carry the controller url so the in game messages can name the website. The login form asks the new status route whether Discord is configured and shows the error straight away instead of a button that fails. The button is full width like the link button, and a "Not you?" link next to the Discord name replaces the separate switch account button. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e4fda18276
commit
1c713ba0aa
24 files changed
+296
-273
No files matched your search
@@ -0,0 +1,177 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { Alert, Button, Space, Spin, Typography } from "antd";
|
||||
|
||||
declare const webRoot: string;
|
||||
|
||||
const { Link, Paragraph, Text } = Typography;
|
||||
const sessionKey = "exp_discord_auth_session";
|
||||
|
||||
type Accounts = {
|
||||
discord: { id: string, name: string },
|
||||
accounts: string[],
|
||||
max_accounts: number,
|
||||
};
|
||||
|
||||
async function api(method: "GET" | "POST", route: string, session: string) {
|
||||
const response = await fetch(`${webRoot}api/exp_discord_auth/${route}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${session}` },
|
||||
});
|
||||
const json = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(json.error ?? `Bad server response: ${response.status}`);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
/** Take the outcome of the Discord redirect out of the url, so a reload does not reuse it. */
|
||||
function readRedirect() {
|
||||
const params = new URLSearchParams(window.location.hash.slice(1));
|
||||
const session = params.get("exp_discord_auth_session");
|
||||
const error = params.get("exp_discord_auth_error");
|
||||
if (session || error) {
|
||||
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
||||
}
|
||||
if (session) {
|
||||
sessionStorage.setItem(sessionKey, session);
|
||||
}
|
||||
return { session: session ?? sessionStorage.getItem(sessionKey), error };
|
||||
}
|
||||
|
||||
export default function DiscordLoginForm(props: { setToken(token: string): void }) {
|
||||
const [redirect] = useState(readRedirect);
|
||||
const [session, setSession] = useState<string | null>(redirect.session);
|
||||
const [error, setError] = useState<string | null>(redirect.error);
|
||||
const [accounts, setAccounts] = useState<Accounts | null>(null);
|
||||
const [code, setCode] = useState<string | null>(null);
|
||||
const [configured, setConfigured] = useState<boolean | null>(null);
|
||||
const linkedCount = useRef<number | null>(null);
|
||||
|
||||
function forget(message: string | null) {
|
||||
sessionStorage.removeItem(sessionKey);
|
||||
setSession(null);
|
||||
setAccounts(null);
|
||||
setCode(null);
|
||||
linkedCount.current = null;
|
||||
setError(message);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (session || configured !== null) {
|
||||
return;
|
||||
}
|
||||
fetch(`${webRoot}api/exp_discord_auth/status`)
|
||||
.then(response => response.json())
|
||||
.then(json => setConfigured(json.configured))
|
||||
.catch(err => setError(`Failed to load Discord login: ${err.message}`));
|
||||
}, [session, configured]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!session) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
async function load() {
|
||||
try {
|
||||
const json = await api("GET", "accounts", session!) as Accounts;
|
||||
if (!cancelled) {
|
||||
// The code was used once a new account shows up
|
||||
if (linkedCount.current !== null && json.accounts.length > linkedCount.current) {
|
||||
setCode(null);
|
||||
}
|
||||
linkedCount.current = json.accounts.length;
|
||||
setAccounts(json);
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (!cancelled) {
|
||||
forget(err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
// While a code is shown, poll until it is used in game
|
||||
const interval = code ? setInterval(load, 3e3) : undefined;
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [session, code]);
|
||||
|
||||
async function login(name: string) {
|
||||
try {
|
||||
const json = await api("POST", `login?name=${encodeURIComponent(name)}`, session!);
|
||||
sessionStorage.removeItem(sessionKey);
|
||||
props.setToken(json.token);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function getCode() {
|
||||
try {
|
||||
const json = await api("POST", "link_code", session!);
|
||||
setCode(json.code);
|
||||
} catch (err: any) {
|
||||
forget(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
const errorAlert = error && <Alert type="error" message={error} showIcon style={{ marginBottom: 16 }} />;
|
||||
|
||||
if (!session) {
|
||||
if (configured === false) {
|
||||
return <Alert type="error" message="Discord login is not configured on this controller" showIcon />;
|
||||
}
|
||||
return <>
|
||||
{errorAlert}
|
||||
<Paragraph>Log in with a linked Discord account. New accounts can be linked after logging in.</Paragraph>
|
||||
<Button type="primary" block disabled={!configured} href={`${webRoot}api/exp_discord_auth/authorize`}>
|
||||
Log in with Discord
|
||||
</Button>
|
||||
</>;
|
||||
}
|
||||
|
||||
if (!accounts) {
|
||||
return <Spin size="large" />;
|
||||
}
|
||||
|
||||
const canLinkMore = accounts.accounts.length < accounts.max_accounts;
|
||||
return <>
|
||||
{errorAlert}
|
||||
<Paragraph>
|
||||
Logged in to Discord as <Text strong>{accounts.discord.name}</Text>. <Link onClick={() => forget(null)}>Not you?</Link>
|
||||
</Paragraph>
|
||||
|
||||
{accounts.accounts.length
|
||||
? <Space direction="vertical" style={{ width: "100%", marginBottom: 16 }}>
|
||||
{accounts.accounts.map(name => <Button
|
||||
key={name}
|
||||
type="primary"
|
||||
block
|
||||
onClick={() => { login(name); }}
|
||||
>Log in as {name}</Button>)}
|
||||
</Space>
|
||||
: <Paragraph>No Factorio accounts are linked to this Discord account yet.</Paragraph>}
|
||||
|
||||
{code
|
||||
? <Alert
|
||||
type="info"
|
||||
style={{ marginBottom: 16 }}
|
||||
message="Link your Factorio account"
|
||||
description={<>
|
||||
Join any of our servers and type this in the chat:
|
||||
<Paragraph copyable={{ text: `/link-discord ${code}` }} style={{ margin: "8px 0" }}>
|
||||
<Text code style={{ fontSize: 18 }}>/link-discord {code}</Text>
|
||||
</Paragraph>
|
||||
The code is valid for 10 minutes. This page continues once it has been used.
|
||||
</>}
|
||||
/>
|
||||
: canLinkMore && <Paragraph>
|
||||
<Button block onClick={() => { getCode(); }}>
|
||||
{accounts.accounts.length ? "Link another Factorio account" : "Link a Factorio account"}
|
||||
</Button>
|
||||
</Paragraph>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { Alert, Button, Descriptions, Popconfirm } from "antd";
|
||||
|
||||
import {
|
||||
ControlContext, PluginExtensionProps, SectionHeader, notifyErrorHandler, useAccount,
|
||||
} from "@clusterio/web_ui";
|
||||
|
||||
import { DiscordLinkGetRequest, DiscordLinkStartRequest, DiscordUnlinkRequest } from "../../messages.js";
|
||||
|
||||
declare const webRoot: string;
|
||||
|
||||
type Link = { id: string, name: string } | null;
|
||||
|
||||
/** An error from linking on Discord, taken out of the url so a reload does not show it again. */
|
||||
function readError() {
|
||||
const error = new URLSearchParams(window.location.hash.slice(1)).get("exp_discord_auth_error");
|
||||
if (error) {
|
||||
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/** The Discord account a user is linked to, shown on their user page. */
|
||||
export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPage">) {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
const own = account.name.toLowerCase() === props.user.name.toLowerCase();
|
||||
const canGet = own || account.hasPermission("exp_discord_auth.link.get");
|
||||
const canDelete = own || account.hasPermission("exp_discord_auth.link.delete");
|
||||
const [link, setLink] = useState<Link | undefined>(undefined);
|
||||
const [error, setError] = useState(readError);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canGet) {
|
||||
return;
|
||||
}
|
||||
control.send(new DiscordLinkGetRequest(props.user.name))
|
||||
.then(response => setLink(response.link))
|
||||
.catch(notifyErrorHandler("Error loading Discord link"));
|
||||
}, [props.user.name, canGet]);
|
||||
|
||||
if (!canGet || link === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function unlink() {
|
||||
await control.send(new DiscordUnlinkRequest(props.user.name));
|
||||
setLink(null);
|
||||
}
|
||||
|
||||
async function startLink() {
|
||||
const ticket = await control.send(new DiscordLinkStartRequest(props.user.name));
|
||||
window.location.href = `${webRoot}api/exp_discord_auth/authorize?link=${encodeURIComponent(ticket)}`;
|
||||
}
|
||||
|
||||
return <>
|
||||
<SectionHeader title="Discord" />
|
||||
{error && <Alert
|
||||
type="error"
|
||||
message={error}
|
||||
showIcon
|
||||
closable
|
||||
onClose={() => setError(null)}
|
||||
style={{ marginBottom: 16 }}
|
||||
/>}
|
||||
<Descriptions bordered size="small" column={1}>
|
||||
<Descriptions.Item label="Linked account">
|
||||
{link ? <>
|
||||
{link.name}
|
||||
{canDelete && <Popconfirm
|
||||
title={`Unlink ${props.user.name} from ${link.name}?`}
|
||||
onConfirm={() => { unlink().catch(notifyErrorHandler("Error unlinking Discord")); }}
|
||||
>
|
||||
<Button danger size="small" style={{ marginLeft: 8 }}>Unlink</Button>
|
||||
</Popconfirm>}
|
||||
</> : <>
|
||||
Not linked
|
||||
{own && <Button
|
||||
size="small"
|
||||
style={{ marginLeft: 8 }}
|
||||
onClick={() => { startLink().catch(notifyErrorHandler("Error linking Discord")); }}
|
||||
>Link Discord</Button>}
|
||||
</>}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</>;
|
||||
}
|
||||
Reference in new issue
Block a user