mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-27 07:57:13 +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
@@ -1,82 +0,0 @@
|
|||||||
import type { Instance, InstancePluginContext } from "@clusterio/host";
|
|
||||||
import type * as lib from "@clusterio/lib";
|
|
||||||
import * as messages from "./messages.js";
|
|
||||||
|
|
||||||
/** Sent by the lua side when a player uses a link code. */
|
|
||||||
export type IpcLink = {
|
|
||||||
player_name: string,
|
|
||||||
code: string,
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Sent by the lua side when a player unlinks their Discord account, or asks which one they are linked to. */
|
|
||||||
export type IpcPlayer = {
|
|
||||||
player_name: string,
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Bridges the lua side and the controller, the answer is printed to the player once it arrives. */
|
|
||||||
export class InstancePlugin {
|
|
||||||
private constructor(
|
|
||||||
public instance: Instance,
|
|
||||||
public logger: lib.Logger,
|
|
||||||
public name: string,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
static async fromContext(context: InstancePluginContext) {
|
|
||||||
const instance = context.instance;
|
|
||||||
const plugin = new InstancePlugin(instance, context.logger, context.plugin.name);
|
|
||||||
|
|
||||||
instance.server.handle("exp_discord:link", plugin.handleLinkIPC.bind(plugin));
|
|
||||||
instance.server.handle("exp_discord:unlink", plugin.handleUnlinkIPC.bind(plugin));
|
|
||||||
instance.server.handle("exp_discord:get", plugin.handleGetIPC.bind(plugin));
|
|
||||||
return plugin;
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleLinkIPC(event: IpcLink) {
|
|
||||||
try {
|
|
||||||
const discord = await this.instance.sendTo("controller", new messages.DiscordLinkRequest(
|
|
||||||
event.player_name, event.code,
|
|
||||||
));
|
|
||||||
await this.luaSend("receive_linked", { player_name: event.player_name, discord_name: discord!.name });
|
|
||||||
} catch (err: any) {
|
|
||||||
await this.luaSend("receive_error", { player_name: event.player_name, message: err.message });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleUnlinkIPC(event: IpcPlayer) {
|
|
||||||
try {
|
|
||||||
const discord = await this.instance.sendTo("controller", new messages.DiscordUnlinkRequest(event.player_name));
|
|
||||||
await this.luaSend("receive_unlinked", { player_name: event.player_name, discord_name: discord?.name });
|
|
||||||
} catch (err: any) {
|
|
||||||
await this.luaSend("receive_error", { player_name: event.player_name, message: err.message });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleGetIPC(event: IpcPlayer) {
|
|
||||||
try {
|
|
||||||
const discord = await this.instance.sendTo("controller", new messages.DiscordLinkGetRequest(event.player_name));
|
|
||||||
await this.luaSend("receive_get", { player_name: event.player_name, discord_name: discord?.name });
|
|
||||||
} catch (err: any) {
|
|
||||||
await this.luaSend("receive_error", { player_name: event.player_name, message: err.message });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Hand an answer to lua, unless the instance stopped while it was being fetched. */
|
|
||||||
async luaSend(receiver: string, json: any) {
|
|
||||||
if (this.instance.status !== "running") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Discord names can contain anything, so pick a long bracket level the json does not close
|
|
||||||
const text = JSON.stringify(json);
|
|
||||||
let level = "=";
|
|
||||||
while (text.includes(`]${level}]`)) {
|
|
||||||
level += "=";
|
|
||||||
}
|
|
||||||
await this.instance.sendRcon(
|
|
||||||
`/sc exp_discord.${receiver}(helpers.json_to_table[${level}[${text}]${level}])`, true
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function (context: InstancePluginContext) {
|
|
||||||
await InstancePlugin.fromContext(context);
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
|
|
||||||
-- Access the exports from other modules using require("modules/exp_discord")
|
|
||||||
return require("modules/exp_discord/control")
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Without an .npmignore pnpm packs using the repository .gitignore, which leaves out dist/
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# ExpGaming - Discord
|
# ExpGaming - Discord Auth
|
||||||
|
|
||||||
Lets players log in to the web interface with Discord, and links their Factorio accounts to a Discord account. It only uses the OAuth2 `identify` scope, so no bot is needed.
|
Lets players log in to the web interface with Discord, and links their Factorio accounts to a Discord account. It only uses the OAuth2 `identify` scope, so no bot is needed.
|
||||||
|
|
||||||
@@ -6,13 +6,13 @@ Lets players log in to the web interface with Discord, and links their Factorio
|
|||||||
|
|
||||||
1. Create an application in the [Discord developer portal](https://discord.com/developers/applications).
|
1. Create an application in the [Discord developer portal](https://discord.com/developers/applications).
|
||||||
2. Under OAuth2, copy the Client ID and reset the Client Secret to get one.
|
2. Under OAuth2, copy the Client ID and reset the Client Secret to get one.
|
||||||
3. Under OAuth2 → Redirects, add `<controller.public_url>api/exp_discord/callback`. For a controller with `controller.public_url` set to `https://example.com/cluster/` that is `https://example.com/cluster/api/exp_discord/callback`. It must match exactly, including the trailing path and http or https.
|
3. Under OAuth2 → Redirects, add `<controller.public_url>api/exp_discord_auth/callback`. For a controller with `controller.public_url` set to `https://example.com/cluster/` that is `https://example.com/cluster/api/exp_discord_auth/callback`. It must match exactly, including the trailing path and http or https.
|
||||||
4. Set the config on the controller:
|
4. Set the config on the controller:
|
||||||
|
|
||||||
```
|
```
|
||||||
npx clusterioctl controller config set controller.public_url https://example.com/cluster/
|
npx clusterioctl controller config set controller.public_url https://example.com/cluster/
|
||||||
npx clusterioctl controller config set exp_discord.client_id <client id>
|
npx clusterioctl controller config set exp_discord_auth.client_id <client id>
|
||||||
npx clusterioctl controller config set exp_discord.client_secret <client secret>
|
npx clusterioctl controller config set exp_discord_auth.client_secret <client secret>
|
||||||
```
|
```
|
||||||
|
|
||||||
`controller.public_url` has to be set, because the redirect URL is built from it and Discord rejects any URL that isn't registered.
|
`controller.public_url` has to be set, because the redirect URL is built from it and Discord rejects any URL that isn't registered.
|
||||||
@@ -23,9 +23,9 @@ All fields are on the controller.
|
|||||||
|
|
||||||
| Field | Default | Description |
|
| Field | Default | Description |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `exp_discord.client_id` | | Application ID of the Discord application. |
|
| `exp_discord_auth.client_id` | | Application ID of the Discord application. |
|
||||||
| `exp_discord.client_secret` | | OAuth2 client secret of the Discord application. Only readable on the controller. |
|
| `exp_discord_auth.client_secret` | | OAuth2 client secret of the Discord application. Only readable on the controller. |
|
||||||
| `exp_discord.max_accounts` | 3 | How many Factorio accounts one Discord account can link. |
|
| `exp_discord_auth.max_accounts` | 3 | How many Factorio accounts one Discord account can link. |
|
||||||
|
|
||||||
## Linking
|
## Linking
|
||||||
|
|
||||||
@@ -36,8 +36,8 @@ There are two ways to link a Factorio account:
|
|||||||
|
|
||||||
Linking a Factorio account that is already linked to another Discord account moves it. `/link-discord` without a code shows the current link, and `/unlink-discord` removes it. The user page has an Unlink button too.
|
Linking a Factorio account that is already linked to another Discord account moves it. `/link-discord` without a code shows the current link, and `/unlink-discord` removes it. The user page has an Unlink button too.
|
||||||
|
|
||||||
Users can always see and remove their own link. The `exp_discord.link.get` and `exp_discord.link.delete` permissions allow it for other users.
|
Users can always see and remove their own link. The `exp_discord_auth.link.get` and `exp_discord_auth.link.delete` permissions allow it for other users.
|
||||||
|
|
||||||
Once linked, the Discord tab on the login page has a "Log in as" button for each linked account. Banned users can't log in this way.
|
Once linked, the Discord tab on the login page has a "Log in as" button for each linked account. Banned users can't log in this way.
|
||||||
|
|
||||||
Links are stored in `database/exp_discord/accounts.json` on the controller.
|
Links are stored in `database/exp_discord_auth/accounts.json` on the controller.
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Controller, ControllerPluginContext } from "@clusterio/controller";
|
import type { Controller, ControllerPluginContext } from "@clusterio/controller";
|
||||||
|
import type { NextFunction, Request, Response } from "express";
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import * as messages from "./messages.js";
|
import * as messages from "./messages.js";
|
||||||
import * as crypto from "node:crypto";
|
import * as crypto from "node:crypto";
|
||||||
@@ -22,17 +23,6 @@ export type RouteResult =
|
|||||||
| { redirect: string, cookie?: string }
|
| { redirect: string, cookie?: string }
|
||||||
| { status: number, json: unknown };
|
| { status: number, json: unknown };
|
||||||
|
|
||||||
type HttpRequest = {
|
|
||||||
query: Record<string, unknown>,
|
|
||||||
headers: Record<string, string | string[] | undefined>,
|
|
||||||
};
|
|
||||||
type HttpResponse = {
|
|
||||||
status(code: number): HttpResponse,
|
|
||||||
json(body: unknown): unknown,
|
|
||||||
redirect(url: string): void,
|
|
||||||
setHeader(name: string, value: string): unknown,
|
|
||||||
};
|
|
||||||
|
|
||||||
function readCookie(header: string | string[] | undefined, name: string) {
|
function readCookie(header: string | string[] | undefined, name: string) {
|
||||||
for (const part of String(header ?? "").split(";")) {
|
for (const part of String(header ?? "").split(";")) {
|
||||||
const [key, ...value] = part.trim().split("=");
|
const [key, ...value] = part.trim().split("=");
|
||||||
@@ -60,14 +50,46 @@ export class ControllerPlugin {
|
|||||||
linkTickets = new Map<string, WebLink>();
|
linkTickets = new Map<string, WebLink>();
|
||||||
/** Links waiting for the Discord callback, by OAuth state */
|
/** Links waiting for the Discord callback, by OAuth state */
|
||||||
pendingLinks = new Map<string, WebLink>();
|
pendingLinks = new Map<string, WebLink>();
|
||||||
cleanupInterval?: ReturnType<typeof setInterval>;
|
cleanupInterval = setInterval(() => this.removeExpired(), 60e3).unref();
|
||||||
|
|
||||||
private constructor(
|
private constructor(
|
||||||
public controller: Controller,
|
public controller: Controller,
|
||||||
public logger: lib.Logger,
|
public logger: lib.Logger,
|
||||||
public name: string,
|
public name: string,
|
||||||
public accounts: lib.SubscribableDatastore<messages.DiscordAccountRecord>,
|
public accounts: lib.SubscribableDatastore<messages.DiscordAccountRecord>,
|
||||||
) {}
|
) {
|
||||||
|
controller.handle(messages.DiscordLinkRequest, this.handleLinkRequest.bind(this));
|
||||||
|
controller.handle(messages.DiscordUnlinkRequest, this.handleUnlinkRequest.bind(this));
|
||||||
|
controller.handle(messages.DiscordLinkGetRequest, this.handleLinkGetRequest.bind(this));
|
||||||
|
controller.handle(messages.DiscordLinkStartRequest, this.handleLinkStartRequest.bind(this));
|
||||||
|
|
||||||
|
const route = (handler: (req: Request) => Promise<RouteResult>) => (
|
||||||
|
(req: Request, res: Response, next: NextFunction) => {
|
||||||
|
handler(req).then(result => {
|
||||||
|
if ("redirect" in result) {
|
||||||
|
if (result.cookie) {
|
||||||
|
res.setHeader("Set-Cookie", result.cookie);
|
||||||
|
}
|
||||||
|
res.redirect(result.redirect);
|
||||||
|
} else {
|
||||||
|
res.status(result.status).json(result.json);
|
||||||
|
}
|
||||||
|
}).catch(next);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const app = controller.app;
|
||||||
|
app.get("/api/exp_discord_auth/status", route(async () => this.status()));
|
||||||
|
app.get("/api/exp_discord_auth/authorize", route(async req => this.authorize(req.query.link)));
|
||||||
|
app.get("/api/exp_discord_auth/callback", route(async req => this.callback(
|
||||||
|
req.query, readCookie(req.headers.cookie, "exp_discord_auth_state"),
|
||||||
|
)));
|
||||||
|
app.get("/api/exp_discord_auth/accounts", route(async req => this.listAccounts(this.sessionId(req))));
|
||||||
|
app.post("/api/exp_discord_auth/login", route(async req => this.login(this.sessionId(req), req.query.name)));
|
||||||
|
app.post("/api/exp_discord_auth/link_code", route(async req => this.linkCode(this.sessionId(req))));
|
||||||
|
|
||||||
|
controller.hooks.save.attach(name, this.onSave.bind(this));
|
||||||
|
controller.hooks.shutdown.attach(name, this.onShutdown.bind(this));
|
||||||
|
}
|
||||||
|
|
||||||
static async fromContext(context: ControllerPluginContext) {
|
static async fromContext(context: ControllerPluginContext) {
|
||||||
const controller = context.controller;
|
const controller = context.controller;
|
||||||
@@ -75,25 +97,12 @@ export class ControllerPlugin {
|
|||||||
|
|
||||||
const accounts = new lib.SubscribableDatastore(
|
const accounts = new lib.SubscribableDatastore(
|
||||||
...await new lib.JsonIdDatastoreProvider(
|
...await new lib.JsonIdDatastoreProvider(
|
||||||
path.join(databaseDirectory, "exp_discord", "accounts.json"),
|
path.join(databaseDirectory, "exp_discord_auth", "accounts.json"),
|
||||||
messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord),
|
messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord),
|
||||||
).bootstrap()
|
).bootstrap()
|
||||||
);
|
);
|
||||||
|
|
||||||
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, accounts);
|
return new ControllerPlugin(controller, context.logger, context.plugin.name, accounts);
|
||||||
|
|
||||||
controller.handle(messages.DiscordLinkRequest, plugin.handleLinkRequest.bind(plugin));
|
|
||||||
controller.handle(messages.DiscordUnlinkRequest, plugin.handleUnlinkRequest.bind(plugin));
|
|
||||||
controller.handle(messages.DiscordLinkGetRequest, plugin.handleLinkGetRequest.bind(plugin));
|
|
||||||
controller.handle(messages.DiscordLinkStartRequest, plugin.handleLinkStartRequest.bind(plugin));
|
|
||||||
|
|
||||||
plugin.addRoutes();
|
|
||||||
plugin.cleanupInterval = setInterval(() => plugin.removeExpired(), 60e3);
|
|
||||||
plugin.cleanupInterval.unref();
|
|
||||||
|
|
||||||
controller.hooks.save.attach(plugin.name, plugin.onSave.bind(plugin));
|
|
||||||
controller.hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin));
|
|
||||||
return plugin;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async onSave() {
|
async onSave() {
|
||||||
@@ -124,45 +133,19 @@ export class ControllerPlugin {
|
|||||||
Http routes
|
Http routes
|
||||||
*/
|
*/
|
||||||
|
|
||||||
addRoutes() {
|
sessionId(req: Request) {
|
||||||
const app = this.controller.app;
|
|
||||||
const route = (handler: (req: HttpRequest) => Promise<RouteResult>) => (
|
|
||||||
(req: HttpRequest, res: HttpResponse, next: (err: unknown) => void) => {
|
|
||||||
handler(req).then(result => {
|
|
||||||
if ("redirect" in result) {
|
|
||||||
if (result.cookie) {
|
|
||||||
res.setHeader("Set-Cookie", result.cookie);
|
|
||||||
}
|
|
||||||
res.redirect(result.redirect);
|
|
||||||
} else {
|
|
||||||
res.status(result.status).json(result.json);
|
|
||||||
}
|
|
||||||
}).catch(next);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
app.get("/api/exp_discord/authorize", route(async req => this.authorize(req.query.link)));
|
|
||||||
app.get("/api/exp_discord/callback", route(async req => this.callback(
|
|
||||||
req.query, readCookie(req.headers.cookie, "exp_discord_state"),
|
|
||||||
)));
|
|
||||||
app.get("/api/exp_discord/accounts", route(async req => this.listAccounts(this.sessionId(req))));
|
|
||||||
app.post("/api/exp_discord/login", route(async req => this.login(this.sessionId(req), req.query.name)));
|
|
||||||
app.post("/api/exp_discord/link_code", route(async req => this.linkCode(this.sessionId(req))));
|
|
||||||
}
|
|
||||||
|
|
||||||
sessionId(req: HttpRequest) {
|
|
||||||
const header = String(req.headers.authorization ?? "");
|
const header = String(req.headers.authorization ?? "");
|
||||||
return header.startsWith("Bearer ") ? header.slice(7) : "";
|
return header.startsWith("Bearer ") ? header.slice(7) : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
redirectUri() {
|
redirectUri() {
|
||||||
return new URL("api/exp_discord/callback", this.controller.getControllerUrl()).href;
|
return new URL("api/exp_discord_auth/callback", this.controller.getControllerUrl()).href;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Back to the web ui, with the outcome in the fragment so it never reaches a server log. */
|
/** Back to the web ui, with the outcome in the fragment so it never reaches a server log. */
|
||||||
webRedirect(key: "session" | "error", value: string, page = ""): RouteResult {
|
webRedirect(key: "session" | "error", value: string, page = ""): RouteResult {
|
||||||
const url = new URL(page, this.controller.getControllerUrl());
|
const url = new URL(page, this.controller.getControllerUrl());
|
||||||
url.hash = `exp_discord_${key}=${encodeURIComponent(value)}`;
|
url.hash = `exp_discord_auth_${key}=${encodeURIComponent(value)}`;
|
||||||
return { redirect: url.href };
|
return { redirect: url.href };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,6 +153,18 @@ export class ControllerPlugin {
|
|||||||
return `users/${encodeURIComponent(playerName)}/view`;
|
return `users/${encodeURIComponent(playerName)}/view`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
isConfigured() {
|
||||||
|
return Boolean(
|
||||||
|
this.controller.config.get("exp_discord_auth.client_id")
|
||||||
|
&& this.controller.config.get("exp_discord_auth.client_secret")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lets the login form say Discord is not set up before anyone presses the button. */
|
||||||
|
async status(): Promise<RouteResult> {
|
||||||
|
return { status: 200, json: { configured: this.isConfigured() } };
|
||||||
|
}
|
||||||
|
|
||||||
async authorize(linkTicket?: unknown): Promise<RouteResult> {
|
async authorize(linkTicket?: unknown): Promise<RouteResult> {
|
||||||
let link: WebLink | undefined;
|
let link: WebLink | undefined;
|
||||||
if (linkTicket !== undefined) {
|
if (linkTicket !== undefined) {
|
||||||
@@ -181,8 +176,7 @@ export class ControllerPlugin {
|
|||||||
}
|
}
|
||||||
const page = link ? this.userPage(link.playerName) : "";
|
const page = link ? this.userPage(link.playerName) : "";
|
||||||
|
|
||||||
const clientId = this.controller.config.get("exp_discord.client_id");
|
if (!this.isConfigured()) {
|
||||||
if (!clientId || !this.controller.config.get("exp_discord.client_secret")) {
|
|
||||||
return this.webRedirect("error", "Discord login is not configured on this controller", page);
|
return this.webRedirect("error", "Discord login is not configured on this controller", page);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,7 +187,7 @@ export class ControllerPlugin {
|
|||||||
const url = new URL("https://discord.com/oauth2/authorize");
|
const url = new URL("https://discord.com/oauth2/authorize");
|
||||||
url.search = new URLSearchParams({
|
url.search = new URLSearchParams({
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
client_id: clientId,
|
client_id: this.controller.config.get("exp_discord_auth.client_id")!,
|
||||||
scope: "identify",
|
scope: "identify",
|
||||||
state,
|
state,
|
||||||
redirect_uri: this.redirectUri(),
|
redirect_uri: this.redirectUri(),
|
||||||
@@ -205,7 +199,7 @@ export class ControllerPlugin {
|
|||||||
const secure = callbackUrl.protocol === "https:" ? "; Secure" : "";
|
const secure = callbackUrl.protocol === "https:" ? "; Secure" : "";
|
||||||
return {
|
return {
|
||||||
redirect: url.href,
|
redirect: url.href,
|
||||||
cookie: `exp_discord_state=${state}; Path=${callbackUrl.pathname}; Max-Age=${stateTimeoutS}; HttpOnly; SameSite=Lax${secure}`,
|
cookie: `exp_discord_auth_state=${state}; Path=${callbackUrl.pathname}; Max-Age=${stateTimeoutS}; HttpOnly; SameSite=Lax${secure}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,8 +258,8 @@ export class ControllerPlugin {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
client_id: this.controller.config.get("exp_discord.client_id") ?? "",
|
client_id: this.controller.config.get("exp_discord_auth.client_id") ?? "",
|
||||||
client_secret: this.controller.config.get("exp_discord.client_secret") ?? "",
|
client_secret: this.controller.config.get("exp_discord_auth.client_secret") ?? "",
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code,
|
code,
|
||||||
redirect_uri: this.redirectUri(),
|
redirect_uri: this.redirectUri(),
|
||||||
@@ -304,7 +298,7 @@ export class ControllerPlugin {
|
|||||||
json: {
|
json: {
|
||||||
discord: { id: session.id, name: session.name },
|
discord: { id: session.id, name: session.name },
|
||||||
accounts: this.accounts.get(session.id)?.factorioNames ?? [],
|
accounts: this.accounts.get(session.id)?.factorioNames ?? [],
|
||||||
max_accounts: this.controller.config.get("exp_discord.max_accounts"),
|
max_accounts: this.controller.config.get("exp_discord_auth.max_accounts"),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -393,7 +387,9 @@ export class ControllerPlugin {
|
|||||||
const entry = this.codes.get(code);
|
const entry = this.codes.get(code);
|
||||||
const session = entry ? this.sessions.get(entry.sessionId) : undefined;
|
const session = entry ? this.sessions.get(entry.sessionId) : undefined;
|
||||||
if (!entry || !session || entry.expiresMs < Date.now()) {
|
if (!entry || !session || entry.expiresMs < Date.now()) {
|
||||||
throw new lib.RequestError("This code is invalid or has expired, get a new one from the website");
|
throw new lib.RequestError(
|
||||||
|
`This code is invalid or has expired, get a new one from ${this.controller.getControllerUrl()}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const linked = this.linkAccount(session, request.playerName);
|
const linked = this.linkAccount(session, request.playerName);
|
||||||
@@ -407,7 +403,7 @@ export class ControllerPlugin {
|
|||||||
const name = playerName.toLowerCase();
|
const name = playerName.toLowerCase();
|
||||||
const existing = this.accounts.get(discordUser.id);
|
const existing = this.accounts.get(discordUser.id);
|
||||||
const alreadyLinked = existing?.factorioNames.some(linked => linked.toLowerCase() === name);
|
const alreadyLinked = existing?.factorioNames.some(linked => linked.toLowerCase() === name);
|
||||||
const maxAccounts = this.controller.config.get("exp_discord.max_accounts");
|
const maxAccounts = this.controller.config.get("exp_discord_auth.max_accounts");
|
||||||
if (!alreadyLinked && (existing?.factorioNames.length ?? 0) >= maxAccounts) {
|
if (!alreadyLinked && (existing?.factorioNames.length ?? 0) >= maxAccounts) {
|
||||||
throw new lib.RequestError(
|
throw new lib.RequestError(
|
||||||
`${discordUser.name} already has ${maxAccounts} Factorio accounts linked, unlink one first`
|
`${discordUser.name} already has ${maxAccounts} Factorio accounts linked, unlink one first`
|
||||||
@@ -426,10 +422,10 @@ export class ControllerPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleUnlinkRequest(request: messages.DiscordUnlinkRequest) {
|
async handleUnlinkRequest(request: messages.DiscordUnlinkRequest) {
|
||||||
return this.removeLink(request.playerName);
|
return { link: this.removeLink(request.playerName), url: this.controller.getControllerUrl() };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A ticket for /api/exp_discord/authorize?link= which links the Discord account to the user. */
|
/** A ticket for /api/exp_discord_auth/authorize?link= which links the Discord account to the user. */
|
||||||
async handleLinkStartRequest(request: messages.DiscordLinkStartRequest) {
|
async handleLinkStartRequest(request: messages.DiscordLinkStartRequest) {
|
||||||
const ticket = crypto.randomBytes(16).toString("base64url");
|
const ticket = crypto.randomBytes(16).toString("base64url");
|
||||||
this.linkTickets.set(ticket, { playerName: request.playerName, expiresMs: Date.now() + 60e3 });
|
this.linkTickets.set(ticket, { playerName: request.playerName, expiresMs: Date.now() + 60e3 });
|
||||||
@@ -438,10 +434,11 @@ export class ControllerPlugin {
|
|||||||
|
|
||||||
async handleLinkGetRequest(request: messages.DiscordLinkGetRequest) {
|
async handleLinkGetRequest(request: messages.DiscordLinkGetRequest) {
|
||||||
const account = this.findAccount(request.playerName);
|
const account = this.findAccount(request.playerName);
|
||||||
return account ? { id: account.id, name: account.name } : null;
|
return {
|
||||||
|
link: account ? { id: account.id, name: account.name } : null,
|
||||||
|
url: this.controller.getControllerUrl(),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function (context: ControllerPluginContext) {
|
export default ControllerPlugin.fromContext.bind(ControllerPlugin);
|
||||||
await ControllerPlugin.fromContext(context);
|
|
||||||
}
|
|
||||||
@@ -3,19 +3,19 @@ import * as messages from "./messages.js";
|
|||||||
|
|
||||||
declare module "@clusterio/lib" {
|
declare module "@clusterio/lib" {
|
||||||
export interface ControllerConfigFields {
|
export interface ControllerConfigFields {
|
||||||
"exp_discord.client_id": string | null;
|
"exp_discord_auth.client_id": string | null;
|
||||||
"exp_discord.client_secret": string | null;
|
"exp_discord_auth.client_secret": string | null;
|
||||||
"exp_discord.max_accounts": number;
|
"exp_discord_auth.max_accounts": number;
|
||||||
}
|
}
|
||||||
export interface Permissions {
|
export interface Permissions {
|
||||||
"exp_discord.link.get": never;
|
"exp_discord_auth.link.get": never;
|
||||||
"exp_discord.link.delete": never;
|
"exp_discord_auth.link.delete": never;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const plugin: lib.PluginDeclaration = {
|
export const plugin: lib.PluginDeclaration = {
|
||||||
name: "exp_discord",
|
name: "exp_discord_auth",
|
||||||
title: "ExpGaming - Discord",
|
title: "ExpGaming - Discord Auth",
|
||||||
description: "Clusterio plugin linking Factorio accounts to Discord accounts and logging in to the web interface with Discord",
|
description: "Clusterio plugin linking Factorio accounts to Discord accounts and logging in to the web interface with Discord",
|
||||||
|
|
||||||
features: [
|
features: [
|
||||||
@@ -32,13 +32,13 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
|
|
||||||
permissions: [
|
permissions: [
|
||||||
{
|
{
|
||||||
name: "exp_discord.link.get",
|
name: "exp_discord_auth.link.get",
|
||||||
title: "Get Discord Links",
|
title: "Get Discord Links",
|
||||||
description: "See which Discord account any user is linked to, users can always see their own.",
|
description: "See which Discord account any user is linked to, users can always see their own.",
|
||||||
grantByDefault: false,
|
grantByDefault: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "exp_discord.link.delete",
|
name: "exp_discord_auth.link.delete",
|
||||||
title: "Remove Discord Links",
|
title: "Remove Discord Links",
|
||||||
description: "Unlink any user from their Discord account, users can always unlink themselves.",
|
description: "Unlink any user from their Discord account, users can always unlink themselves.",
|
||||||
grantByDefault: false,
|
grantByDefault: false,
|
||||||
@@ -49,20 +49,20 @@ export const plugin: lib.PluginDeclaration = {
|
|||||||
|
|
||||||
controllerEntrypoint: "./dist/node/controller.js",
|
controllerEntrypoint: "./dist/node/controller.js",
|
||||||
controllerConfigFields: {
|
controllerConfigFields: {
|
||||||
"exp_discord.client_id": {
|
"exp_discord_auth.client_id": {
|
||||||
title: "Client ID",
|
title: "Client ID",
|
||||||
description: "Application ID of the Discord application used for logging in.",
|
description: "Application ID of the Discord application used for logging in.",
|
||||||
type: "string",
|
type: "string",
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
"exp_discord.client_secret": {
|
"exp_discord_auth.client_secret": {
|
||||||
title: "Client Secret",
|
title: "Client Secret",
|
||||||
description: "OAuth2 client secret of the Discord application used for logging in.",
|
description: "OAuth2 client secret of the Discord application used for logging in.",
|
||||||
type: "string",
|
type: "string",
|
||||||
credential: ["controller"],
|
credential: ["controller"],
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
"exp_discord.max_accounts": {
|
"exp_discord_auth.max_accounts": {
|
||||||
title: "Max Accounts",
|
title: "Max Accounts",
|
||||||
description: "Number of Factorio accounts which can be linked to one Discord account.",
|
description: "Number of Factorio accounts which can be linked to one Discord account.",
|
||||||
type: "number",
|
type: "number",
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { InstancePluginContext } from "@clusterio/host";
|
||||||
|
import * as messages from "./messages.js";
|
||||||
|
|
||||||
|
/** Sent by the lua side when a player uses a link code. */
|
||||||
|
export type IpcLink = {
|
||||||
|
player_name: string,
|
||||||
|
code: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Sent by the lua side when a player unlinks their Discord account, or asks which one they are linked to. */
|
||||||
|
export type IpcPlayer = {
|
||||||
|
player_name: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Bridges the lua side and the controller, the answer is printed to the player once it arrives. */
|
||||||
|
export default async function (context: InstancePluginContext) {
|
||||||
|
const { instance } = context;
|
||||||
|
|
||||||
|
/** Hand an answer to lua, unless the instance stopped while it was being fetched. */
|
||||||
|
async function luaSend(receiver: string, json: any) {
|
||||||
|
if (instance.status !== "running") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Discord names can contain anything, so pick a long bracket level the json does not close
|
||||||
|
const text = JSON.stringify(json);
|
||||||
|
let level = "=";
|
||||||
|
while (text.includes(`]${level}]`)) {
|
||||||
|
level += "=";
|
||||||
|
}
|
||||||
|
await instance.sendRcon(
|
||||||
|
`/sc exp_discord_auth.${receiver}(helpers.json_to_table[${level}[${text}]${level}])`, true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
instance.server.handle("exp_discord_auth:link", async (event: IpcLink) => {
|
||||||
|
try {
|
||||||
|
const discord = await instance.sendTo("controller", new messages.DiscordLinkRequest(
|
||||||
|
event.player_name, event.code,
|
||||||
|
));
|
||||||
|
await luaSend("receive_linked", { player_name: event.player_name, discord_name: discord!.name });
|
||||||
|
} catch (err: any) {
|
||||||
|
await luaSend("receive_error", { player_name: event.player_name, message: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.server.handle("exp_discord_auth:unlink", async (event: IpcPlayer) => {
|
||||||
|
try {
|
||||||
|
const status = await instance.sendTo("controller", new messages.DiscordUnlinkRequest(event.player_name));
|
||||||
|
await luaSend("receive_unlinked", {
|
||||||
|
player_name: event.player_name, discord_name: status.link?.name, url: status.url,
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
await luaSend("receive_error", { player_name: event.player_name, message: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.server.handle("exp_discord_auth:get", async (event: IpcPlayer) => {
|
||||||
|
try {
|
||||||
|
const status = await instance.sendTo("controller", new messages.DiscordLinkGetRequest(event.player_name));
|
||||||
|
await luaSend("receive_get", {
|
||||||
|
player_name: event.player_name, discord_name: status.link?.name, url: status.url,
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
await luaSend("receive_error", { player_name: event.player_name, message: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -72,13 +72,19 @@ function selfOnly(user: lib.IUser, message: lib.MessageRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const LinkResponse = lib.plainJson(Type.Union([
|
const Link = Type.Union([
|
||||||
Type.Null(),
|
Type.Null(),
|
||||||
Type.Object({
|
Type.Object({
|
||||||
id: Type.String(),
|
id: Type.String(),
|
||||||
name: Type.String(),
|
name: Type.String(),
|
||||||
}),
|
}),
|
||||||
]));
|
]);
|
||||||
|
const LinkResponse = lib.plainJson(Link);
|
||||||
|
/** The website is included so the player can be told where to link their account. */
|
||||||
|
const LinkStatusResponse = lib.plainJson(Type.Object({
|
||||||
|
link: Link,
|
||||||
|
url: Type.String(),
|
||||||
|
}));
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Link requests
|
Link requests
|
||||||
@@ -87,7 +93,7 @@ const LinkResponse = lib.plainJson(Type.Union([
|
|||||||
/** Link a player to the Discord account which generated the code, sent when the player uses the code in game. */
|
/** Link a player to the Discord account which generated the code, sent when the player uses the code in game. */
|
||||||
export class DiscordLinkRequest {
|
export class DiscordLinkRequest {
|
||||||
declare ["constructor"]: typeof DiscordLinkRequest;
|
declare ["constructor"]: typeof DiscordLinkRequest;
|
||||||
static plugin = "exp_discord" as const;
|
static plugin = "exp_discord_auth" as const;
|
||||||
static type = "request" as const;
|
static type = "request" as const;
|
||||||
static src = "instance" as const;
|
static src = "instance" as const;
|
||||||
static dst = "controller" as const;
|
static dst = "controller" as const;
|
||||||
@@ -112,15 +118,15 @@ export class DiscordLinkRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove the link of a player, responds with the account it was linked to. */
|
/** Remove the link of a player, responds with the account it was linked to and the website url. */
|
||||||
export class DiscordUnlinkRequest {
|
export class DiscordUnlinkRequest {
|
||||||
declare ["constructor"]: typeof DiscordUnlinkRequest;
|
declare ["constructor"]: typeof DiscordUnlinkRequest;
|
||||||
static plugin = "exp_discord" as const;
|
static plugin = "exp_discord_auth" as const;
|
||||||
static type = "request" as const;
|
static type = "request" as const;
|
||||||
static src = ["control", "instance"] as const;
|
static src = ["control", "instance"] as const;
|
||||||
static dst = "controller" as const;
|
static dst = "controller" as const;
|
||||||
static permission = selfOrPermission("exp_discord.link.delete");
|
static permission = selfOrPermission("exp_discord_auth.link.delete");
|
||||||
static Response = LinkResponse;
|
static Response = LinkStatusResponse;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public playerName: string,
|
public playerName: string,
|
||||||
@@ -139,15 +145,15 @@ export class DiscordUnlinkRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Get the Discord account a player is linked to. */
|
/** Get the Discord account a player is linked to and the website url. */
|
||||||
export class DiscordLinkGetRequest {
|
export class DiscordLinkGetRequest {
|
||||||
declare ["constructor"]: typeof DiscordLinkGetRequest;
|
declare ["constructor"]: typeof DiscordLinkGetRequest;
|
||||||
static plugin = "exp_discord" as const;
|
static plugin = "exp_discord_auth" as const;
|
||||||
static type = "request" as const;
|
static type = "request" as const;
|
||||||
static src = ["control", "instance"] as const;
|
static src = ["control", "instance"] as const;
|
||||||
static dst = "controller" as const;
|
static dst = "controller" as const;
|
||||||
static permission = selfOrPermission("exp_discord.link.get");
|
static permission = selfOrPermission("exp_discord_auth.link.get");
|
||||||
static Response = LinkResponse;
|
static Response = LinkStatusResponse;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public playerName: string,
|
public playerName: string,
|
||||||
@@ -169,7 +175,7 @@ export class DiscordLinkGetRequest {
|
|||||||
/** Start linking the Discord account from the user page, responds with a ticket for the authorize route. */
|
/** Start linking the Discord account from the user page, responds with a ticket for the authorize route. */
|
||||||
export class DiscordLinkStartRequest {
|
export class DiscordLinkStartRequest {
|
||||||
declare ["constructor"]: typeof DiscordLinkStartRequest;
|
declare ["constructor"]: typeof DiscordLinkStartRequest;
|
||||||
static plugin = "exp_discord" as const;
|
static plugin = "exp_discord_auth" as const;
|
||||||
static type = "request" as const;
|
static type = "request" as const;
|
||||||
static src = "control" as const;
|
static src = "control" as const;
|
||||||
static dst = "controller" as const;
|
static dst = "controller" as const;
|
||||||
@@ -1,30 +1,34 @@
|
|||||||
--[[-- ExpDiscord - Commands
|
--[[-- ExpDiscordAuth - Commands
|
||||||
Commands which link and unlink the player's Discord account
|
Commands which link and unlink the player's Discord account
|
||||||
]]
|
]]
|
||||||
|
|
||||||
local Commands = require("modules/exp_commands")
|
local Commands = require("modules/exp_commands")
|
||||||
|
|
||||||
local Discord = require("modules/exp_discord")
|
local Discord = require("modules/exp_discord_auth")
|
||||||
|
|
||||||
|
--- @class ExpDiscordAuth.commands
|
||||||
|
local commands = {}
|
||||||
|
|
||||||
--- Links your account to the Discord account which made the code, printed once the controller answers
|
--- Links your account to the Discord account which made the code, printed once the controller answers
|
||||||
Commands.new("link-discord", { "exp-discord_commands.description-link" })
|
commands.link_discord = Commands.new("link-discord", { "exp-discord-auth_commands.description-link" })
|
||||||
:optional("code", { "exp-discord_commands.arg-code" }, Commands.types.string)
|
:optional("code", { "exp-discord-auth_commands.arg-code" }, Commands.types.string)
|
||||||
:add_aliases{ "link" }
|
:add_aliases{ "link" }
|
||||||
:register(function(player, code)
|
:register(function(player, code)
|
||||||
--- @cast code string?
|
--- @cast code string?
|
||||||
if code then
|
if code then
|
||||||
Discord.link(player, code)
|
Discord.link(player, code)
|
||||||
else
|
else
|
||||||
Discord.get_link(player)
|
Discord.get_linked(player)
|
||||||
end
|
end
|
||||||
end)
|
end)
|
||||||
|
|
||||||
--- Removes the link to your Discord account, printed once the controller answers
|
--- Removes the link to your Discord account, printed once the controller answers
|
||||||
Commands.new("unlink-discord", { "exp-discord_commands.description-unlink" })
|
commands.unlink_discord = Commands.new("unlink-discord", { "exp-discord-auth_commands.description-unlink" })
|
||||||
:add_aliases{ "unlink" }
|
:add_aliases{ "unlink" }
|
||||||
:register(function(player)
|
:register(function(player)
|
||||||
Discord.unlink(player)
|
Discord.unlink(player)
|
||||||
end)
|
end)
|
||||||
|
|
||||||
-- Access the exports from other modules using require("modules/exp_discord")
|
return {
|
||||||
return require("modules/exp_discord/control")
|
commands = commands,
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
--[[-- ExpDiscord
|
--[[-- ExpDiscordAuth
|
||||||
Links Factorio accounts to Discord accounts, the links are kept on the controller.
|
Links Factorio accounts to Discord accounts, the links are kept on the controller.
|
||||||
|
|
||||||
A player logs in with Discord on the web interface, which gives them a code.
|
A player logs in with Discord on the web interface, which gives them a code.
|
||||||
@@ -10,28 +10,28 @@ printed to the player once it arrives, if they are still online.
|
|||||||
local clusterio_api = require("modules/clusterio/api")
|
local clusterio_api = require("modules/clusterio/api")
|
||||||
local ExpUtil = require("modules/exp_util")
|
local ExpUtil = require("modules/exp_util")
|
||||||
|
|
||||||
--- @class ExpDiscord
|
--- @class ExpDiscordAuth
|
||||||
local ExpDiscord = {}
|
local ExpDiscordAuth = {}
|
||||||
|
|
||||||
local error_settings = { color = ExpUtil.color.orange_red, sound_path = "utility/wire_pickup" }
|
local error_settings = { color = ExpUtil.color.orange_red, sound_path = "utility/wire_pickup" }
|
||||||
|
|
||||||
--- Link the player to the Discord account which made the code
|
--- Link the player to the Discord account which made the code
|
||||||
--- @param player LuaPlayer
|
--- @param player LuaPlayer
|
||||||
--- @param code string
|
--- @param code string
|
||||||
function ExpDiscord.link(player, code)
|
function ExpDiscordAuth.link(player, code)
|
||||||
clusterio_api.send_json("exp_discord:link", { player_name = player.name, code = code })
|
clusterio_api.send_json("exp_discord_auth:link", { player_name = player.name, code = code })
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Remove the link between the player and their Discord account
|
--- Remove the link between the player and their Discord account
|
||||||
--- @param player LuaPlayer
|
--- @param player LuaPlayer
|
||||||
function ExpDiscord.unlink(player)
|
function ExpDiscordAuth.unlink(player)
|
||||||
clusterio_api.send_json("exp_discord:unlink", { player_name = player.name })
|
clusterio_api.send_json("exp_discord_auth:unlink", { player_name = player.name })
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Print the Discord account the player is linked to
|
--- Print the Discord account the player is linked to
|
||||||
--- @param player LuaPlayer
|
--- @param player LuaPlayer
|
||||||
function ExpDiscord.get_link(player)
|
function ExpDiscordAuth.get_linked(player)
|
||||||
clusterio_api.send_json("exp_discord:get", { player_name = player.name })
|
clusterio_api.send_json("exp_discord_auth:get", { player_name = player.name })
|
||||||
end
|
end
|
||||||
|
|
||||||
--- A player who can still be printed to, nil once they have left
|
--- A player who can still be printed to, nil once they have left
|
||||||
@@ -47,42 +47,42 @@ end
|
|||||||
|
|
||||||
--- The controller linked the player
|
--- The controller linked the player
|
||||||
--- @param payload { player_name: string, discord_name: string }
|
--- @param payload { player_name: string, discord_name: string }
|
||||||
function ExpDiscord.receive_linked(payload)
|
function ExpDiscordAuth.receive_linked(payload)
|
||||||
local player = get_online_player(payload.player_name)
|
local player = get_online_player(payload.player_name)
|
||||||
if not player then return end
|
if not player then return end
|
||||||
player.print{ "exp-discord.linked", payload.discord_name }
|
player.print{ "exp-discord-auth.linked", payload.discord_name }
|
||||||
end
|
end
|
||||||
|
|
||||||
--- The controller removed the link, discord_name is nil if there was none
|
--- The controller removed the link, discord_name is nil if there was none
|
||||||
--- @param payload { player_name: string, discord_name: string? }
|
--- @param payload { player_name: string, discord_name: string?, url: string }
|
||||||
function ExpDiscord.receive_unlinked(payload)
|
function ExpDiscordAuth.receive_unlinked(payload)
|
||||||
local player = get_online_player(payload.player_name)
|
local player = get_online_player(payload.player_name)
|
||||||
if not player then return end
|
if not player then return end
|
||||||
if payload.discord_name then
|
if payload.discord_name then
|
||||||
player.print{ "exp-discord.unlinked", payload.discord_name }
|
player.print{ "exp-discord-auth.unlinked", payload.discord_name }
|
||||||
else
|
else
|
||||||
player.print({ "exp-discord.not-linked" }, error_settings)
|
player.print({ "exp-discord-auth.not-linked", payload.url }, error_settings)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
--- The controller answered which account the player is linked to
|
--- The controller answered which account the player is linked to
|
||||||
--- @param payload { player_name: string, discord_name: string? }
|
--- @param payload { player_name: string, discord_name: string?, url: string }
|
||||||
function ExpDiscord.receive_get(payload)
|
function ExpDiscordAuth.receive_get(payload)
|
||||||
local player = get_online_player(payload.player_name)
|
local player = get_online_player(payload.player_name)
|
||||||
if not player then return end
|
if not player then return end
|
||||||
if payload.discord_name then
|
if payload.discord_name then
|
||||||
player.print{ "exp-discord.linked-to", payload.discord_name }
|
player.print{ "exp-discord-auth.linked-to", payload.discord_name }
|
||||||
else
|
else
|
||||||
player.print{ "exp-discord.not-linked" }
|
player.print{ "exp-discord-auth.not-linked", payload.url }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
--- The controller refused a request
|
--- The controller refused a request
|
||||||
--- @param payload { player_name: string, message: string }
|
--- @param payload { player_name: string, message: string }
|
||||||
function ExpDiscord.receive_error(payload)
|
function ExpDiscordAuth.receive_error(payload)
|
||||||
local player = get_online_player(payload.player_name)
|
local player = get_online_player(payload.player_name)
|
||||||
if not player then return end
|
if not player then return end
|
||||||
player.print(payload.message, error_settings)
|
player.print(payload.message, error_settings)
|
||||||
end
|
end
|
||||||
|
|
||||||
return ExpDiscord
|
return ExpDiscordAuth
|
||||||
@@ -6,5 +6,5 @@ Therefore, we advise that this should be the only file in your module to expose
|
|||||||
|
|
||||||
--- @diagnostic disable: global-in-non-module
|
--- @diagnostic disable: global-in-non-module
|
||||||
|
|
||||||
-- Access using `/sc exp_discord.foo()`
|
-- Access using `/sc exp_discord_auth.foo()`
|
||||||
exp_discord = require("modules/exp_discord/control")
|
exp_discord_auth = require("modules/exp_discord_auth/control")
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
[exp-discord]
|
[exp-discord-auth]
|
||||||
linked=Your account is now linked to the Discord account __1__.
|
linked=Your account is now linked to the Discord account __1__.
|
||||||
linked-to=Your account is linked to the Discord account __1__. Use /unlink-discord to remove it.
|
linked-to=Your account is linked to the Discord account __1__. Use /unlink-discord to remove it.
|
||||||
unlinked=Your account is no longer linked to the Discord account __1__.
|
unlinked=Your account is no longer linked to the Discord account __1__.
|
||||||
not-linked=Your account is not linked to a Discord account. Log in with Discord on the website to get a code, then use /link-discord <code>.
|
not-linked=Your account is not linked to a Discord account. Log in with Discord at __1__ to get a code, then use /link-discord <code>.
|
||||||
|
|
||||||
[exp-discord_commands]
|
[exp-discord-auth_commands]
|
||||||
description-link=Links your account to Discord using the code from the website, or shows the account you are linked to.
|
description-link=Links your account to Discord using the code from the website, or shows the account you are linked to.
|
||||||
description-unlink=Removes the link between your account and Discord.
|
description-unlink=Removes the link between your account and Discord.
|
||||||
arg-code=Code shown on the website after logging in with Discord.
|
arg-code=Code shown on the website after logging in with Discord.
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "exp_discord",
|
"name": "exp_discord_auth",
|
||||||
"load": [
|
"load": [
|
||||||
],
|
],
|
||||||
"require": [
|
"require": [
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
|
||||||
|
-- Access the exports from other modules using require("modules/exp_discord_auth")
|
||||||
|
return require("modules/exp_discord_auth/control")
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "@expcluster/discord",
|
"name": "@expcluster/discord-auth",
|
||||||
"version": "7.0.0",
|
"version": "7.0.0",
|
||||||
"description": "Clusterio plugin linking Factorio accounts to Discord accounts and logging in to the web interface with Discord",
|
"description": "Clusterio plugin linking Factorio accounts to Discord accounts and logging in to the web interface with Discord",
|
||||||
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
|
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
"coverage": "tap --coverage-report=text test/*.test.js"
|
"coverage": "tap --coverage-report=text test/*.test.js"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=22"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@clusterio/controller": "workspace:^",
|
"@clusterio/controller": "workspace:^",
|
||||||
@@ -26,6 +26,7 @@
|
|||||||
"@clusterio/host": "workspace:^",
|
"@clusterio/host": "workspace:^",
|
||||||
"@clusterio/lib": "workspace:^",
|
"@clusterio/lib": "workspace:^",
|
||||||
"@clusterio/web_ui": "workspace:^",
|
"@clusterio/web_ui": "workspace:^",
|
||||||
|
"@types/express": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"@types/react": "catalog:",
|
"@types/react": "catalog:",
|
||||||
"antd": "catalog:",
|
"antd": "catalog:",
|
||||||
@@ -26,8 +26,8 @@ async function startPlugin(t2, { config = {} } = {}) {
|
|||||||
// testdir() empties the folder, so a reload passes the directory in
|
// testdir() empties the folder, so a reload passes the directory in
|
||||||
"controller.database_directory": config["controller.database_directory"] ?? t2.testdir(),
|
"controller.database_directory": config["controller.database_directory"] ?? t2.testdir(),
|
||||||
"controller.public_url": "https://example.com/cluster/",
|
"controller.public_url": "https://example.com/cluster/",
|
||||||
"exp_discord.client_id": "123",
|
"exp_discord_auth.client_id": "123",
|
||||||
"exp_discord.client_secret": "secret",
|
"exp_discord_auth.client_secret": "secret",
|
||||||
"controller.auth_secret": Buffer.from("test secret").toString("base64"),
|
"controller.auth_secret": Buffer.from("test secret").toString("base64"),
|
||||||
...config,
|
...config,
|
||||||
});
|
});
|
||||||
@@ -36,7 +36,7 @@ async function startPlugin(t2, { config = {} } = {}) {
|
|||||||
controller.users.createUser(name);
|
controller.users.createUser(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord" }, controller, logger });
|
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord_auth" }, controller, logger });
|
||||||
t2.teardown(() => clearInterval(plugin.cleanupInterval));
|
t2.teardown(() => clearInterval(plugin.cleanupInterval));
|
||||||
return { plugin, controller };
|
return { plugin, controller };
|
||||||
}
|
}
|
||||||
@@ -57,9 +57,9 @@ async function link(plugin, session, playerName) {
|
|||||||
t.test("entrypoint", async t2 => {
|
t.test("entrypoint", async t2 => {
|
||||||
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
|
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
|
||||||
const controller = new Controller(logger, [], controllerConfig);
|
const controller = new Controller(logger, [], controllerConfig);
|
||||||
await entrypoint({ controller, logger, plugin: { name: "exp_discord" }, metrics: undefined });
|
await entrypoint({ controller, logger, plugin: { name: "exp_discord_auth" }, metrics: undefined });
|
||||||
for (const hook of ["save", "shutdown"]) {
|
for (const hook of ["save", "shutdown"]) {
|
||||||
t2.ok([...controller.hooks[hook].attached].includes("exp_discord"), `attached to ${hook}`);
|
t2.ok([...controller.hooks[hook].attached].includes("exp_discord_auth"), `attached to ${hook}`);
|
||||||
}
|
}
|
||||||
await controller.hooks.shutdown.invoke();
|
await controller.hooks.shutdown.invoke();
|
||||||
});
|
});
|
||||||
@@ -71,16 +71,23 @@ t.test("oauth", t2 => {
|
|||||||
const url = new URL(result.redirect);
|
const url = new URL(result.redirect);
|
||||||
t3.equal(url.origin + url.pathname, "https://discord.com/oauth2/authorize");
|
t3.equal(url.origin + url.pathname, "https://discord.com/oauth2/authorize");
|
||||||
t3.equal(url.searchParams.get("client_id"), "123");
|
t3.equal(url.searchParams.get("client_id"), "123");
|
||||||
t3.equal(url.searchParams.get("redirect_uri"), "https://example.com/cluster/api/exp_discord/callback");
|
t3.equal(url.searchParams.get("redirect_uri"), "https://example.com/cluster/api/exp_discord_auth/callback");
|
||||||
const state = url.searchParams.get("state");
|
const state = url.searchParams.get("state");
|
||||||
t3.match(result.cookie, `exp_discord_state=${state}; Path=/cluster/api/exp_discord/callback`);
|
t3.match(result.cookie, `exp_discord_auth_state=${state}; Path=/cluster/api/exp_discord_auth/callback`);
|
||||||
t3.match(result.cookie, "Secure");
|
t3.match(result.cookie, "Secure");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
t2.test(".status() tells the login form whether Discord is configured", async t3 => {
|
||||||
|
const { plugin } = await startPlugin(t3);
|
||||||
|
t3.same(await plugin.status(), { status: 200, json: { configured: true } });
|
||||||
|
const { plugin: unconfigured } = await startPlugin(t3, { config: { "exp_discord_auth.client_id": null } });
|
||||||
|
t3.same(await unconfigured.status(), { status: 200, json: { configured: false } });
|
||||||
|
});
|
||||||
|
|
||||||
t2.test(".authorize() without credentials goes back with an error", async t3 => {
|
t2.test(".authorize() without credentials goes back with an error", async t3 => {
|
||||||
const { plugin } = await startPlugin(t3, { config: { "exp_discord.client_secret": null } });
|
const { plugin } = await startPlugin(t3, { config: { "exp_discord_auth.client_secret": null } });
|
||||||
const result = await plugin.authorize();
|
const result = await plugin.authorize();
|
||||||
t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/#exp_discord_error=/);
|
t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/#exp_discord_auth_error=/);
|
||||||
});
|
});
|
||||||
|
|
||||||
t2.test(".callback() rejects a state which does not match the cookie", async t3 => {
|
t2.test(".callback() rejects a state which does not match the cookie", async t3 => {
|
||||||
@@ -88,7 +95,7 @@ t.test("oauth", t2 => {
|
|||||||
plugin.fetchDiscordUser = async () => t3.fail("should not fetch");
|
plugin.fetchDiscordUser = async () => t3.fail("should not fetch");
|
||||||
for (const cookie of [undefined, "other"]) {
|
for (const cookie of [undefined, "other"]) {
|
||||||
const result = await plugin.callback({ code: "c", state: "s" }, cookie);
|
const result = await plugin.callback({ code: "c", state: "s" }, cookie);
|
||||||
t3.match(result.redirect, "#exp_discord_error=");
|
t3.match(result.redirect, "#exp_discord_auth_error=");
|
||||||
}
|
}
|
||||||
t3.equal(plugin.sessions.size, 0);
|
t3.equal(plugin.sessions.size, 0);
|
||||||
});
|
});
|
||||||
@@ -97,7 +104,7 @@ t.test("oauth", t2 => {
|
|||||||
const { plugin } = await startPlugin(t3);
|
const { plugin } = await startPlugin(t3);
|
||||||
plugin.fetchDiscordUser = async () => { throw new Error("401"); };
|
plugin.fetchDiscordUser = async () => { throw new Error("401"); };
|
||||||
const result = await plugin.callback({ code: "c", state: "s" }, "s");
|
const result = await plugin.callback({ code: "c", state: "s" }, "s");
|
||||||
t3.match(result.redirect, "#exp_discord_error=");
|
t3.match(result.redirect, "#exp_discord_auth_error=");
|
||||||
});
|
});
|
||||||
|
|
||||||
t2.test(".callback() starts a session", async t3 => {
|
t2.test(".callback() starts a session", async t3 => {
|
||||||
@@ -137,7 +144,8 @@ t.test("linking", t2 => {
|
|||||||
const { json } = await plugin.linkCode(session);
|
const { json } = await plugin.linkCode(session);
|
||||||
await plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player1", json.code));
|
await plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player1", json.code));
|
||||||
await t3.rejects(
|
await t3.rejects(
|
||||||
plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player2", json.code)), /invalid or has expired/,
|
plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player2", json.code)),
|
||||||
|
/invalid or has expired, get a new one from https:\/\/example\.com\/cluster\//,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -156,7 +164,7 @@ t.test("linking", t2 => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
t2.test("several accounts up to the limit", async t3 => {
|
t2.test("several accounts up to the limit", async t3 => {
|
||||||
const { plugin } = await startPlugin(t3, { config: { "exp_discord.max_accounts": 2 } });
|
const { plugin } = await startPlugin(t3, { config: { "exp_discord_auth.max_accounts": 2 } });
|
||||||
const session = await discordLogin(plugin, alice);
|
const session = await discordLogin(plugin, alice);
|
||||||
await link(plugin, session, "Player1");
|
await link(plugin, session, "Player1");
|
||||||
await link(plugin, session, "Player2");
|
await link(plugin, session, "Player2");
|
||||||
@@ -189,10 +197,13 @@ t.test("linking", t2 => {
|
|||||||
t2.test("unlink and get", async t3 => {
|
t2.test("unlink and get", async t3 => {
|
||||||
const { plugin } = await startPlugin(t3);
|
const { plugin } = await startPlugin(t3);
|
||||||
await link(plugin, await discordLogin(plugin, alice), "Player1");
|
await link(plugin, await discordLogin(plugin, alice), "Player1");
|
||||||
t3.same(await plugin.handleLinkGetRequest(new messages.DiscordLinkGetRequest("player1")), alice);
|
const url = "https://example.com/cluster/";
|
||||||
t3.same(await plugin.handleUnlinkRequest(new messages.DiscordUnlinkRequest("Player1")), alice);
|
const get = name => plugin.handleLinkGetRequest(new messages.DiscordLinkGetRequest(name));
|
||||||
t3.equal(await plugin.handleLinkGetRequest(new messages.DiscordLinkGetRequest("Player1")), null);
|
const unlink = name => plugin.handleUnlinkRequest(new messages.DiscordUnlinkRequest(name));
|
||||||
t3.equal(await plugin.handleUnlinkRequest(new messages.DiscordUnlinkRequest("Player1")), null);
|
t3.same(await get("player1"), { link: alice, url });
|
||||||
|
t3.same(await unlink("Player1"), { link: alice, url });
|
||||||
|
t3.same(await get("Player1"), { link: null, url });
|
||||||
|
t3.same(await unlink("Player1"), { link: null, url });
|
||||||
});
|
});
|
||||||
|
|
||||||
t2.test("links are saved and loaded", async t3 => {
|
t2.test("links are saved and loaded", async t3 => {
|
||||||
@@ -242,21 +253,21 @@ t.test("linking from the user page", t2 => {
|
|||||||
const ticket = await plugin.handleLinkStartRequest(new messages.DiscordLinkStartRequest("Player1"));
|
const ticket = await plugin.handleLinkStartRequest(new messages.DiscordLinkStartRequest("Player1"));
|
||||||
await plugin.authorize(ticket);
|
await plugin.authorize(ticket);
|
||||||
const result = await plugin.authorize(ticket);
|
const result = await plugin.authorize(ticket);
|
||||||
t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/users#exp_discord_error=Discord%20link%20expired/);
|
t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/users#exp_discord_auth_error=Discord%20link/);
|
||||||
});
|
});
|
||||||
|
|
||||||
t2.test("errors go back to the user page", async t3 => {
|
t2.test("errors go back to the user page", async t3 => {
|
||||||
const { plugin } = await startPlugin(t3, { config: { "exp_discord.max_accounts": 1 } });
|
const { plugin } = await startPlugin(t3, { config: { "exp_discord_auth.max_accounts": 1 } });
|
||||||
await link(plugin, await discordLogin(plugin, alice), "Player2");
|
await link(plugin, await discordLogin(plugin, alice), "Player2");
|
||||||
|
|
||||||
let params = await start(plugin, "Player1");
|
let params = await start(plugin, "Player1");
|
||||||
let result = await plugin.callback({ error: "access_denied", state: params.get("state") }, params.get("state"));
|
let result = await plugin.callback({ error: "access_denied", state: params.get("state") }, params.get("state"));
|
||||||
t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_error=Discord%20login%20was%20cancelled$/);
|
t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_auth_error=Discord%20login%20was%20cancelled$/);
|
||||||
|
|
||||||
params = await start(plugin, "Player1");
|
params = await start(plugin, "Player1");
|
||||||
plugin.fetchDiscordUser = async () => alice;
|
plugin.fetchDiscordUser = async () => alice;
|
||||||
result = await plugin.callback({ code: "c", state: params.get("state") }, params.get("state"));
|
result = await plugin.callback({ code: "c", state: params.get("state") }, params.get("state"));
|
||||||
t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_error=.*already%20has%201/);
|
t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_auth_error=.*already%20has%201/);
|
||||||
t3.same(plugin.accounts.get(alice.id).factorioNames, ["Player2"]);
|
t3.same(plugin.accounts.get(alice.id).factorioNames, ["Player2"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -265,7 +276,7 @@ t.test("linking from the user page", t2 => {
|
|||||||
const params = await start(plugin, "Player1");
|
const params = await start(plugin, "Player1");
|
||||||
plugin.fetchDiscordUser = async () => t3.fail("should not fetch");
|
plugin.fetchDiscordUser = async () => t3.fail("should not fetch");
|
||||||
const result = await plugin.callback({ code: "c", state: params.get("state") }, undefined);
|
const result = await plugin.callback({ code: "c", state: params.get("state") }, undefined);
|
||||||
t3.match(result.redirect, "/users/Player1/view#exp_discord_error=");
|
t3.match(result.redirect, "/users/Player1/view#exp_discord_auth_error=");
|
||||||
t3.notOk(plugin.accounts.has(alice.id));
|
t3.notOk(plugin.accounts.has(alice.id));
|
||||||
});
|
});
|
||||||
t2.end();
|
t2.end();
|
||||||
@@ -286,7 +297,9 @@ t.test("permissions", t2 => {
|
|||||||
const permission = messages.DiscordLinkStartRequest.permission;
|
const permission = messages.DiscordLinkStartRequest.permission;
|
||||||
t3.doesNotThrow(() => permission(user("Alice"), request("alice")), "own account");
|
t3.doesNotThrow(() => permission(user("Alice"), request("alice")), "own account");
|
||||||
t3.throws(
|
t3.throws(
|
||||||
() => permission(user("Alice", ["exp_discord.link.get", "exp_discord.link.delete"]), request("Bob")),
|
() => permission(
|
||||||
|
user("Alice", ["exp_discord_auth.link.get", "exp_discord_auth.link.delete"]), request("Bob"),
|
||||||
|
),
|
||||||
"never someone else's",
|
"never someone else's",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -294,8 +307,8 @@ t.test("permissions", t2 => {
|
|||||||
for (const Request of [messages.DiscordLinkGetRequest, messages.DiscordUnlinkRequest]) {
|
for (const Request of [messages.DiscordLinkGetRequest, messages.DiscordUnlinkRequest]) {
|
||||||
t2.test(Request.name, async t3 => {
|
t2.test(Request.name, async t3 => {
|
||||||
const permission = Request === messages.DiscordUnlinkRequest
|
const permission = Request === messages.DiscordUnlinkRequest
|
||||||
? "exp_discord.link.delete"
|
? "exp_discord_auth.link.delete"
|
||||||
: "exp_discord.link.get";
|
: "exp_discord_auth.link.get";
|
||||||
t3.doesNotThrow(() => Request.permission(user("Alice"), request("alice")), "own link");
|
t3.doesNotThrow(() => Request.permission(user("Alice"), request("alice")), "own link");
|
||||||
t3.throws(() => Request.permission(user("Alice"), request("Bob")), "someone else's");
|
t3.throws(() => Request.permission(user("Alice"), request("Bob")), "someone else's");
|
||||||
t3.doesNotThrow(() => Request.permission(user("Alice", [permission]), request("Bob")), "with permission");
|
t3.doesNotThrow(() => Request.permission(user("Alice", [permission]), request("Bob")), "with permission");
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+26
-10
@@ -3,8 +3,8 @@ import { Alert, Button, Space, Spin, Typography } from "antd";
|
|||||||
|
|
||||||
declare const webRoot: string;
|
declare const webRoot: string;
|
||||||
|
|
||||||
const { Paragraph, Text } = Typography;
|
const { Link, Paragraph, Text } = Typography;
|
||||||
const sessionKey = "exp_discord_session";
|
const sessionKey = "exp_discord_auth_session";
|
||||||
|
|
||||||
type Accounts = {
|
type Accounts = {
|
||||||
discord: { id: string, name: string },
|
discord: { id: string, name: string },
|
||||||
@@ -13,7 +13,7 @@ type Accounts = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
async function api(method: "GET" | "POST", route: string, session: string) {
|
async function api(method: "GET" | "POST", route: string, session: string) {
|
||||||
const response = await fetch(`${webRoot}api/exp_discord/${route}`, {
|
const response = await fetch(`${webRoot}api/exp_discord_auth/${route}`, {
|
||||||
method,
|
method,
|
||||||
headers: { Authorization: `Bearer ${session}` },
|
headers: { Authorization: `Bearer ${session}` },
|
||||||
});
|
});
|
||||||
@@ -27,8 +27,8 @@ async function api(method: "GET" | "POST", route: string, session: string) {
|
|||||||
/** Take the outcome of the Discord redirect out of the url, so a reload does not reuse it. */
|
/** Take the outcome of the Discord redirect out of the url, so a reload does not reuse it. */
|
||||||
function readRedirect() {
|
function readRedirect() {
|
||||||
const params = new URLSearchParams(window.location.hash.slice(1));
|
const params = new URLSearchParams(window.location.hash.slice(1));
|
||||||
const session = params.get("exp_discord_session");
|
const session = params.get("exp_discord_auth_session");
|
||||||
const error = params.get("exp_discord_error");
|
const error = params.get("exp_discord_auth_error");
|
||||||
if (session || error) {
|
if (session || error) {
|
||||||
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
||||||
}
|
}
|
||||||
@@ -44,6 +44,7 @@ export default function DiscordLoginForm(props: { setToken(token: string): void
|
|||||||
const [error, setError] = useState<string | null>(redirect.error);
|
const [error, setError] = useState<string | null>(redirect.error);
|
||||||
const [accounts, setAccounts] = useState<Accounts | null>(null);
|
const [accounts, setAccounts] = useState<Accounts | null>(null);
|
||||||
const [code, setCode] = useState<string | null>(null);
|
const [code, setCode] = useState<string | null>(null);
|
||||||
|
const [configured, setConfigured] = useState<boolean | null>(null);
|
||||||
const linkedCount = useRef<number | null>(null);
|
const linkedCount = useRef<number | null>(null);
|
||||||
|
|
||||||
function forget(message: string | null) {
|
function forget(message: string | null) {
|
||||||
@@ -55,6 +56,16 @@ export default function DiscordLoginForm(props: { setToken(token: string): void
|
|||||||
setError(message);
|
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(() => {
|
useEffect(() => {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
return undefined;
|
return undefined;
|
||||||
@@ -110,10 +121,15 @@ export default function DiscordLoginForm(props: { setToken(token: string): void
|
|||||||
const errorAlert = error && <Alert type="error" message={error} showIcon style={{ marginBottom: 16 }} />;
|
const errorAlert = error && <Alert type="error" message={error} showIcon style={{ marginBottom: 16 }} />;
|
||||||
|
|
||||||
if (!session) {
|
if (!session) {
|
||||||
|
if (configured === false) {
|
||||||
|
return <Alert type="error" message="Discord login is not configured on this controller" showIcon />;
|
||||||
|
}
|
||||||
return <>
|
return <>
|
||||||
{errorAlert}
|
{errorAlert}
|
||||||
<Paragraph>Log in with your Discord account. Your Factorio account needs to be linked to it first, which you can do after logging in.</Paragraph>
|
<Paragraph>Log in with a linked Discord account. New accounts can be linked after logging in.</Paragraph>
|
||||||
<Button type="primary" href={`${webRoot}api/exp_discord/authorize`}>Log in with Discord</Button>
|
<Button type="primary" block disabled={!configured} href={`${webRoot}api/exp_discord_auth/authorize`}>
|
||||||
|
Log in with Discord
|
||||||
|
</Button>
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +140,9 @@ export default function DiscordLoginForm(props: { setToken(token: string): void
|
|||||||
const canLinkMore = accounts.accounts.length < accounts.max_accounts;
|
const canLinkMore = accounts.accounts.length < accounts.max_accounts;
|
||||||
return <>
|
return <>
|
||||||
{errorAlert}
|
{errorAlert}
|
||||||
<Paragraph>Logged in to Discord as <Text strong>{accounts.discord.name}</Text>.</Paragraph>
|
<Paragraph>
|
||||||
|
Logged in to Discord as <Text strong>{accounts.discord.name}</Text>. <Link onClick={() => forget(null)}>Not you?</Link>
|
||||||
|
</Paragraph>
|
||||||
|
|
||||||
{accounts.accounts.length
|
{accounts.accounts.length
|
||||||
? <Space direction="vertical" style={{ width: "100%", marginBottom: 16 }}>
|
? <Space direction="vertical" style={{ width: "100%", marginBottom: 16 }}>
|
||||||
@@ -155,7 +173,5 @@ export default function DiscordLoginForm(props: { setToken(token: string): void
|
|||||||
{accounts.accounts.length ? "Link another Factorio account" : "Link a Factorio account"}
|
{accounts.accounts.length ? "Link another Factorio account" : "Link a Factorio account"}
|
||||||
</Button>
|
</Button>
|
||||||
</Paragraph>}
|
</Paragraph>}
|
||||||
|
|
||||||
<Button type="link" onClick={() => forget(null)}>Use a different Discord account</Button>
|
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
+5
-5
@@ -13,7 +13,7 @@ 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. */
|
/** An error from linking on Discord, taken out of the url so a reload does not show it again. */
|
||||||
function readError() {
|
function readError() {
|
||||||
const error = new URLSearchParams(window.location.hash.slice(1)).get("exp_discord_error");
|
const error = new URLSearchParams(window.location.hash.slice(1)).get("exp_discord_auth_error");
|
||||||
if (error) {
|
if (error) {
|
||||||
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
||||||
}
|
}
|
||||||
@@ -25,8 +25,8 @@ export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPag
|
|||||||
const control = useContext(ControlContext);
|
const control = useContext(ControlContext);
|
||||||
const account = useAccount();
|
const account = useAccount();
|
||||||
const own = account.name.toLowerCase() === props.user.name.toLowerCase();
|
const own = account.name.toLowerCase() === props.user.name.toLowerCase();
|
||||||
const canGet = own || account.hasPermission("exp_discord.link.get");
|
const canGet = own || account.hasPermission("exp_discord_auth.link.get");
|
||||||
const canDelete = own || account.hasPermission("exp_discord.link.delete");
|
const canDelete = own || account.hasPermission("exp_discord_auth.link.delete");
|
||||||
const [link, setLink] = useState<Link | undefined>(undefined);
|
const [link, setLink] = useState<Link | undefined>(undefined);
|
||||||
const [error, setError] = useState(readError);
|
const [error, setError] = useState(readError);
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPag
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
control.send(new DiscordLinkGetRequest(props.user.name))
|
control.send(new DiscordLinkGetRequest(props.user.name))
|
||||||
.then(setLink)
|
.then(response => setLink(response.link))
|
||||||
.catch(notifyErrorHandler("Error loading Discord link"));
|
.catch(notifyErrorHandler("Error loading Discord link"));
|
||||||
}, [props.user.name, canGet]);
|
}, [props.user.name, canGet]);
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPag
|
|||||||
|
|
||||||
async function startLink() {
|
async function startLink() {
|
||||||
const ticket = await control.send(new DiscordLinkStartRequest(props.user.name));
|
const ticket = await control.send(new DiscordLinkStartRequest(props.user.name));
|
||||||
window.location.href = `${webRoot}api/exp_discord/authorize?link=${encodeURIComponent(ticket)}`;
|
window.location.href = `${webRoot}api/exp_discord_auth/authorize?link=${encodeURIComponent(ticket)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <>
|
return <>
|
||||||
@@ -5,15 +5,15 @@ import DiscordLoginForm from "./components/DiscordLoginForm";
|
|||||||
import UserDiscordLink from "./components/UserDiscordLink";
|
import UserDiscordLink from "./components/UserDiscordLink";
|
||||||
|
|
||||||
export default function registerPlugin(context: WebPluginContext) {
|
export default function registerPlugin(context: WebPluginContext) {
|
||||||
context.control.hooks.loginForms.attach("exp_discord", () => [
|
context.control.hooks.loginForms.attach("exp_discord_auth", () => [
|
||||||
{
|
{
|
||||||
name: "exp_discord",
|
name: "exp_discord_auth",
|
||||||
title: "Discord",
|
title: "Discord",
|
||||||
Component: DiscordLoginForm,
|
Component: DiscordLoginForm,
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
context.control.hooks.extensionComponents.attach("exp_discord", () => ({
|
context.control.hooks.extensionComponents.attach("exp_discord_auth", () => ({
|
||||||
UserViewPage: UserDiscordLink,
|
UserViewPage: UserDiscordLink,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -13,8 +13,8 @@ module.exports = (env = {}) => merge(common(env), {
|
|||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
new webpack.container.ModuleFederationPlugin({
|
new webpack.container.ModuleFederationPlugin({
|
||||||
name: "exp_discord",
|
name: "exp_discord_auth",
|
||||||
library: { type: "window", name: "plugin_exp_discord" },
|
library: { type: "window", name: "plugin_exp_discord_auth" },
|
||||||
exposes: {
|
exposes: {
|
||||||
"./": "./index.ts",
|
"./": "./index.ts",
|
||||||
"./package.json": "./package.json",
|
"./package.json": "./package.json",
|
||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
"references": [
|
"references": [
|
||||||
{ "path": "./exp_auto_restart/" },
|
{ "path": "./exp_auto_restart/" },
|
||||||
{ "path": "./exp_commands/" },
|
{ "path": "./exp_commands/" },
|
||||||
{ "path": "./exp_discord/" },
|
{ "path": "./exp_discord_auth/" },
|
||||||
{ "path": "./exp_groups/" },
|
{ "path": "./exp_groups/" },
|
||||||
{ "path": "./exp_gui/" },
|
{ "path": "./exp_gui/" },
|
||||||
{ "path": "./exp_legacy/" },
|
{ "path": "./exp_legacy/" },
|
||||||
|
|||||||
Reference in new issue
Block a user