generated from nhcarrigan/template
6bf1ac5e7d
## Summary - Grants the Elysian Discord role to players on login/registration and persists an `inGuild` flag on the Player record - Connects to the Discord Gateway via WebSocket to keep `inGuild` in sync as players join or leave the server - Shows a dismissible "Join our community" modal to players who are not yet in the guild - Hardens `inGuild` exposure through the load endpoint and game context - Moves all non-secret Discord IDs (guild, role, client, redirect URI) out of env vars and into hardcoded constants; removes them from `prod.env` ## Test plan - [ ] Lint, build, and test pipeline passes (100% coverage maintained) - [ ] New player auth grants Elysian role and sets `inGuild: true` - [ ] Existing player auth re-attempts role grant and updates `inGuild` - [ ] Join community modal appears for players not in the guild - [ ] Modal does not reappear within the same browser session after dismissal - [ ] Gateway correctly sets `inGuild: true/false` on member add/remove events ✨ This issue was created with help from Hikari~ 🌸 Reviewed-on: #134 Co-authored-by: Hikari <hikari@nhcarrigan.com> Co-committed-by: Hikari <hikari@nhcarrigan.com>
150 lines
5.2 KiB
TypeScript
150 lines
5.2 KiB
TypeScript
/**
|
|
* @file Authentication routes for Discord OAuth.
|
|
* @copyright nhcarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*/
|
|
/* eslint-disable max-lines-per-function -- Auth callback requires many steps */
|
|
/* eslint-disable max-statements -- Auth callback requires many statements */
|
|
import { Hono } from "hono";
|
|
import { initialGameState } from "../data/initialState.js";
|
|
import { prisma } from "../db/client.js";
|
|
import {
|
|
buildOAuthUrl,
|
|
exchangeCode,
|
|
fetchDiscordUser,
|
|
} from "../services/discord.js";
|
|
import { signToken } from "../services/jwt.js";
|
|
import { logger } from "../services/logger.js";
|
|
import { grantElysianRole } from "../services/webhook.js";
|
|
import type { Player } from "@elysium/types";
|
|
|
|
const authRouter = new Hono();
|
|
|
|
authRouter.get("/url", (context) => {
|
|
try {
|
|
const url = buildOAuthUrl();
|
|
return context.json({ url });
|
|
} catch {
|
|
return context.json({ error: "Failed to build OAuth URL" }, 500);
|
|
}
|
|
});
|
|
|
|
authRouter.get("/callback", async(context) => {
|
|
const code = context.req.query("code");
|
|
|
|
if (code === undefined || code === "") {
|
|
return context.json({ error: "Missing code parameter" }, 400);
|
|
}
|
|
|
|
try {
|
|
const tokenData = await exchangeCode(code);
|
|
const discordUser = await fetchDiscordUser(tokenData.access_token);
|
|
|
|
const existing = await prisma.player.findUnique({
|
|
where: { discordId: discordUser.id },
|
|
});
|
|
|
|
const now = Date.now();
|
|
|
|
if (!existing) {
|
|
const player = await prisma.player.create({
|
|
data: {
|
|
avatar: discordUser.avatar,
|
|
characterName: discordUser.username,
|
|
createdAt: now,
|
|
discordId: discordUser.id,
|
|
discriminator: discordUser.discriminator,
|
|
lastSavedAt: now,
|
|
totalClicks: 0,
|
|
totalGoldEarned: 0,
|
|
username: discordUser.username,
|
|
},
|
|
});
|
|
|
|
const playerShape: Player = {
|
|
avatar: player.avatar ?? null,
|
|
characterName: player.characterName,
|
|
createdAt: player.createdAt,
|
|
discordId: player.discordId,
|
|
discriminator: player.discriminator,
|
|
lastSavedAt: player.lastSavedAt,
|
|
lifetimeAchievementsUnlocked: player.lifetimeAchievementsUnlocked,
|
|
lifetimeAdventurersRecruited: player.lifetimeAdventurersRecruited,
|
|
lifetimeBossesDefeated: player.lifetimeBossesDefeated,
|
|
lifetimeClicks: player.lifetimeClicks,
|
|
lifetimeGoldEarned: player.lifetimeGoldEarned,
|
|
lifetimeQuestsCompleted: player.lifetimeQuestsCompleted,
|
|
totalClicks: player.totalClicks,
|
|
totalGoldEarned: player.totalGoldEarned,
|
|
username: player.username,
|
|
};
|
|
|
|
const freshState = initialGameState(
|
|
playerShape,
|
|
playerShape.characterName,
|
|
);
|
|
await prisma.gameState.create({
|
|
data: {
|
|
discordId: player.discordId,
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires never type */
|
|
state: freshState as unknown as never,
|
|
updatedAt: now,
|
|
},
|
|
});
|
|
|
|
const inGuild = await grantElysianRole(player.discordId);
|
|
await prisma.player.update({
|
|
data: { inGuild },
|
|
where: { discordId: player.discordId },
|
|
});
|
|
|
|
const jwtToken = signToken(player.discordId);
|
|
void logger.log("info", `New player registered: ${player.discordId}`);
|
|
void logger.metric("user_registered", 1, { discordId: player.discordId });
|
|
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
const clientUrl = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
|
return context.redirect(
|
|
`${clientUrl}/auth/callback?token=${jwtToken}&isNew=true`,
|
|
);
|
|
}
|
|
|
|
const inGuild = await grantElysianRole(discordUser.id);
|
|
const updated = await prisma.player.update({
|
|
data: {
|
|
avatar: discordUser.avatar,
|
|
discriminator: discordUser.discriminator,
|
|
inGuild: inGuild,
|
|
username: discordUser.username,
|
|
},
|
|
where: { discordId: discordUser.id },
|
|
});
|
|
|
|
const jwtToken = signToken(updated.discordId);
|
|
void logger.log("info", `Player logged in: ${updated.discordId}`);
|
|
void logger.metric("user_login", 1, { discordId: updated.discordId });
|
|
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
const clientUrl = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
|
return context.redirect(
|
|
`${clientUrl}/auth/callback?token=${jwtToken}&isNew=false`,
|
|
);
|
|
} catch (error) {
|
|
void logger.error(
|
|
"auth_callback",
|
|
error instanceof Error
|
|
? error
|
|
: new Error(String(error)),
|
|
);
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
const clientUrl = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
|
return context.redirect(`${clientUrl}/auth/callback?error=auth_failed`);
|
|
}
|
|
});
|
|
|
|
export { authRouter };
|