mirror of
https://github.com/xHyroM/roles-bot.git
synced 2024-11-10 03:08:06 +01:00
Compare commits
No commits in common. "e285c47e011e40c1eaf3a80f2de8c4b14e831d6f" and "4a0388a2ba46718e0d797492302d73c57c9899b6" have entirely different histories.
e285c47e01
...
4a0388a2ba
32 changed files with 79 additions and 713 deletions
|
@ -1,6 +0,0 @@
|
|||
PRO=<production>
|
||||
|
||||
DISCORD_CLIENT_ID=<client id>
|
||||
DISCORD_CLIENT_SECRET=<client secret>
|
||||
DISCORD_BOT_TOKEN=<bot token>
|
||||
DISCORD_REDIRECT_URI=<domain>/auth/callback/discord
|
3
apps/website/.gitignore
vendored
3
apps/website/.gitignore
vendored
|
@ -19,6 +19,3 @@ pnpm-debug.log*
|
|||
|
||||
# macOS-specific files
|
||||
.DS_Store
|
||||
|
||||
.dev.vars
|
||||
.wrangler/
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { defineConfig } from "astro/config";
|
||||
import preact from "@astrojs/preact";
|
||||
import sitemap from "@astrojs/sitemap";
|
||||
import tailwind from "@astrojs/tailwind";
|
||||
import cloudflare from "@astrojs/cloudflare";
|
||||
|
||||
import auth from "auth-astro";
|
||||
import { CONFIG } from "./src/config";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
@ -13,12 +12,9 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
site: CONFIG.origin,
|
||||
integrations: [sitemap(), tailwind(), preact()],
|
||||
integrations: [sitemap(), tailwind(), auth()],
|
||||
output: "server",
|
||||
adapter: cloudflare(),
|
||||
security: {
|
||||
checkOrigin: true,
|
||||
},
|
||||
vite: {
|
||||
resolve: {
|
||||
alias: {
|
||||
|
|
|
@ -1,45 +1,18 @@
|
|||
import Discord from "@auth/core/providers/discord";
|
||||
import { defineConfig } from "auth-astro";
|
||||
import type { User } from "~/env";
|
||||
|
||||
import dotenv from "dotenv";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const { env } = process;
|
||||
|
||||
export default defineConfig({
|
||||
secret: env.AUTH_SECRET,
|
||||
providers: [
|
||||
Discord({
|
||||
clientId: env.DISCORD_CLIENT_ID,
|
||||
clientSecret: env.DISCORD_CLIENT_SECRET,
|
||||
authorization:
|
||||
"https://discord.com/api/oauth2/authorize?scope=guilds+identify+email",
|
||||
clientId: import.meta.env.DISCORD_CLIENT_ID,
|
||||
clientSecret: import.meta.env.DISCORD_CLIENT_SECRET,
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, account, profile }) {
|
||||
if (account && profile) {
|
||||
token.accessToken = account.access_token;
|
||||
token.id = profile.id;
|
||||
|
||||
token.name = profile.username as string;
|
||||
token.global_name = profile.global_name;
|
||||
session({ session, token }) {
|
||||
if (session.user && token?.sub) {
|
||||
session.user.id = token.sub;
|
||||
}
|
||||
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (session.user) {
|
||||
session.user.id = token.id as string;
|
||||
(session.user as unknown as User).global_name =
|
||||
token.global_name as string;
|
||||
|
||||
(session.user as unknown as User).discordAccessToken =
|
||||
token.accessToken as string;
|
||||
}
|
||||
|
||||
return session;
|
||||
},
|
||||
},
|
||||
|
|
Binary file not shown.
|
@ -1,18 +0,0 @@
|
|||
-- Migration number: 0001 2024-08-03T15:43:57.349Z
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
discord_id TEXT NOT NULL UNIQUE,
|
||||
username TEXT NOT NULL,
|
||||
avatar TEXT NOT NULL,
|
||||
access_token TEXT NOT NULL,
|
||||
access_token_expiration NUMBER NOT NULL,
|
||||
refresh_token TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS session (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
expires_at INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES user (id)
|
||||
);
|
|
@ -10,18 +10,15 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "^11.0.1",
|
||||
"@astrojs/preact": "^3.5.1",
|
||||
"@astrojs/prefetch": "^0.2.1",
|
||||
"@astrojs/sitemap": "^3.1.6",
|
||||
"@astrojs/tailwind": "^5.1.0",
|
||||
"@lucia-auth/adapter-sqlite": "^3.0.2",
|
||||
"@auth/core": "^0.32.0",
|
||||
"@tailwindcss/typography": "^0.5.9",
|
||||
"arctic": "^1.9.2",
|
||||
"astro": "^4.11.5",
|
||||
"astro-google-fonts-optimizer": "^0.2.2",
|
||||
"astro-icon": "^0.8.0",
|
||||
"lucia": "^3.2.0",
|
||||
"preact": "^10.23.1",
|
||||
"auth-astro": "^4.1.2",
|
||||
"tailwindcss": "^3.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
---
|
||||
const { class: className } = Astro.props;
|
||||
---
|
||||
|
||||
<div class={`container mx-auto px-4 ${className ?? ""}`}>
|
||||
<slot />
|
||||
</div>
|
|
@ -1,40 +0,0 @@
|
|||
<svg viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6"
|
||||
><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g
|
||||
id="SVGRepo_tracerCarrier"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"
|
||||
><path
|
||||
fill="#CCD6DD"
|
||||
d="M3 16v-2h30v2zm0 7v-2h30v2zm0 7v-2h30v2zM3 9V7h30v2z"></path><path
|
||||
fill="#D5AB88"
|
||||
d="M35 33V1a1 1 0 0 0-1-1h-1a1 1 0 0 0-1 1H4a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1v32h34zM4 4h28v29H4V4z"
|
||||
></path><path
|
||||
fill="#3B94D9"
|
||||
d="M19 5.5A1.5 1.5 0 0 0 17.5 7a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0v2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0V7A1.5 1.5 0 0 0 19 5.5z"
|
||||
></path><path
|
||||
fill="#BE1931"
|
||||
d="M19 12.5a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0v2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0v-2a1.5 1.5 0 0 0-1.5-1.5z"
|
||||
></path><path
|
||||
fill="#5C913B"
|
||||
d="M19 19.5a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0v2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0v-2a1.5 1.5 0 0 0-1.5-1.5z"
|
||||
></path><path
|
||||
fill="#FFAC33"
|
||||
d="M19 26.5a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0a1.5 1.5 0 1 0-3 0v2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0 3 0v-2a1.5 1.5 0 0 0-1.5-1.5z"
|
||||
></path><path
|
||||
fill="#3B94D9"
|
||||
d="M29 10.5A1.5 1.5 0 0 1 27.5 9V7a1.5 1.5 0 1 1 3 0v2a1.5 1.5 0 0 1-1.5 1.5z"
|
||||
></path><path
|
||||
fill="#BE1931"
|
||||
d="M29 17.5a1.5 1.5 0 0 1-1.5-1.5v-2a1.5 1.5 0 1 1 3 0v2a1.5 1.5 0 0 1-1.5 1.5z"
|
||||
></path><path
|
||||
fill="#5C913B"
|
||||
d="M29 24.5a1.5 1.5 0 0 1-1.5-1.5v-2a1.5 1.5 0 0 1 3 0v2a1.5 1.5 0 0 1-1.5 1.5z"
|
||||
></path><path
|
||||
fill="#FFAC33"
|
||||
d="M29 31.5a1.5 1.5 0 0 1-1.5-1.5v-2a1.5 1.5 0 0 1 3 0v2a1.5 1.5 0 0 1-1.5 1.5z"
|
||||
></path><path
|
||||
fill="#BF6952"
|
||||
d="M35 33H1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1h34a1 1 0 0 0 1-1v-1a1 1 0 0 0-1-1z"
|
||||
></path></g
|
||||
></svg
|
||||
>
|
Before Width: | Height: | Size: 2.2 KiB |
|
@ -1,25 +0,0 @@
|
|||
---
|
||||
import { Image } from "astro:assets";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
const { id, name, icon } = Astro.props;
|
||||
---
|
||||
|
||||
<div class="flex items-center justify-center">
|
||||
<Image
|
||||
src={`https://cdn.discordapp.com/icons/${id}/${icon}.webp`}
|
||||
class="mr-5 rounded-full"
|
||||
alt="icon"
|
||||
width={64}
|
||||
height={64}
|
||||
/>
|
||||
|
||||
<h1 class="break-all py-12 text-5xl font-extrabold text-white">
|
||||
{name}
|
||||
</h1>
|
||||
</div>
|
|
@ -1,19 +0,0 @@
|
|||
---
|
||||
import { Image } from "astro:assets";
|
||||
|
||||
const user = Astro.locals.user;
|
||||
---
|
||||
|
||||
<div class="flex items-center justify-center">
|
||||
<Image
|
||||
src={`https://cdn.discordapp.com/avatars/${user.discordId}/${user.avatar}.webp`}
|
||||
class="mr-5 rounded-full"
|
||||
alt="icon"
|
||||
width={64}
|
||||
height={64}
|
||||
/>
|
||||
|
||||
<h1 class="break-all py-12 text-5xl font-extrabold text-white">
|
||||
@{user.username}
|
||||
</h1>
|
||||
</div>
|
|
@ -1,34 +0,0 @@
|
|||
import type { Guild } from "~/env";
|
||||
|
||||
interface Props {
|
||||
guild: Guild;
|
||||
mutual: boolean;
|
||||
}
|
||||
|
||||
export default function Guild({ guild, mutual }: Props) {
|
||||
return (
|
||||
<a
|
||||
class={`flex min-h-max w-80 cursor-pointer justify-between rounded-md border-[1px] border-neutral-800 bg-dark-100 p-6 md:w-96 ${
|
||||
!mutual && "brightness-50"
|
||||
}`}
|
||||
href={
|
||||
mutual
|
||||
? `/dashboard/guilds/${guild.id}`
|
||||
: `https://discord.com/oauth2/authorize?client_id=923267906941370368&scope=bot+applications.commands&guild_id=${guild.id}`
|
||||
}
|
||||
target={mutual ? "_self" : "_blank"}
|
||||
>
|
||||
<div class="flex flex-row items-center">
|
||||
<img
|
||||
src={`https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.webp`}
|
||||
class="mr-5 rounded-full"
|
||||
alt="icon"
|
||||
width="64"
|
||||
height="64"
|
||||
/>
|
||||
|
||||
<h2 class="w-fit break-all text-3xl font-bold">{guild.name}</h2>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
import { Component } from "preact";
|
||||
import Guild from "./Guild";
|
||||
import LoadingGuild from "./LoadingGuild";
|
||||
import type { MutualeGuild } from "~/env";
|
||||
|
||||
interface State {
|
||||
guilds: MutualeGuild[] | null;
|
||||
}
|
||||
|
||||
export default class GuildSelector extends Component<{}, State> {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
guilds: null,
|
||||
};
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
const response = await fetch("/api/user/guilds");
|
||||
const data = await response.json();
|
||||
this.setState({ guilds: data });
|
||||
}
|
||||
|
||||
render() {
|
||||
const { guilds } = this.state;
|
||||
if (!guilds) return [...Array(15)].map(() => <LoadingGuild />);
|
||||
|
||||
return guilds.map((g) => <Guild guild={g.guild} mutual={g.mutual} />);
|
||||
}
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
export default function LoadingGuild() {
|
||||
return (
|
||||
<div className="flex min-h-max w-80 items-center justify-center rounded-md border border-neutral-800 bg-dark-100 p-6 md:w-96">
|
||||
<div className="flex flex-row">
|
||||
<div className="h-6 w-52 animate-pulse rounded-md bg-neutral-700 shadow-md"></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
35
apps/website/src/env.d.ts
vendored
35
apps/website/src/env.d.ts
vendored
|
@ -1,36 +1 @@
|
|||
/// <reference types="astro/client" />
|
||||
|
||||
type D1Database = import("@cloudflare/workers-types").D1Database;
|
||||
type ENV = {
|
||||
GITHUB_APP_NAME: string;
|
||||
DISCORD_CLIENT_ID: string;
|
||||
DISCORD_CLIENT_SECRET: string;
|
||||
DISCORD_BOT_TOKEN: string;
|
||||
DISCORD_REDIRECT_URI: string;
|
||||
DB: D1Database;
|
||||
};
|
||||
|
||||
export interface Guild {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: string;
|
||||
permissions: string;
|
||||
owner: boolean;
|
||||
}
|
||||
|
||||
export interface MutualeGuild {
|
||||
mutual: boolean;
|
||||
guild: Guild;
|
||||
}
|
||||
|
||||
type Runtime = import("@astrojs/cloudflare").Runtime<ENV>;
|
||||
|
||||
// https://github.com/withastro/astro/issues/7394#issuecomment-1975657601
|
||||
declare namespace App {
|
||||
interface Locals extends Runtime {
|
||||
discord: import("arctic").Discord;
|
||||
lucia: import("lucia").Lucia;
|
||||
session: import("lucia").Session | null;
|
||||
user: import("lucia").User | null;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,54 +0,0 @@
|
|||
import { Lucia } from "lucia";
|
||||
import { D1Adapter } from "@lucia-auth/adapter-sqlite";
|
||||
import { Discord } from "arctic";
|
||||
|
||||
export function initializeLucia(D1: D1Database) {
|
||||
const adapter = new D1Adapter(D1, {
|
||||
user: "user",
|
||||
session: "session",
|
||||
});
|
||||
return new Lucia(adapter, {
|
||||
sessionCookie: {
|
||||
attributes: {
|
||||
// set to `true` when using HTTPS
|
||||
secure: import.meta.env.PROD,
|
||||
},
|
||||
},
|
||||
getUserAttributes: (attributes) => {
|
||||
return {
|
||||
discordId: attributes.discord_id,
|
||||
username: attributes.username,
|
||||
avatar: attributes.avatar,
|
||||
sensitive: {
|
||||
accessToken: attributes.access_token,
|
||||
refreshToken: attributes.refresh_token,
|
||||
accessTokenExpiresAt: attributes.access_token_expiration,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function initializeDiscord(
|
||||
discordClientId: string,
|
||||
discordClientSecret: string,
|
||||
redirectUri: string
|
||||
) {
|
||||
return new Discord(discordClientId, discordClientSecret, redirectUri);
|
||||
}
|
||||
|
||||
declare module "lucia" {
|
||||
interface Register {
|
||||
Lucia: ReturnType<typeof initializeLucia>;
|
||||
DatabaseUserAttributes: DatabaseUserAttributes;
|
||||
}
|
||||
}
|
||||
|
||||
interface DatabaseUserAttributes {
|
||||
discord_id: number;
|
||||
username: string;
|
||||
avatar: string;
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
access_token_expiration: number;
|
||||
}
|
|
@ -1,63 +0,0 @@
|
|||
import type { Guild, MutualeGuild } from "~/env";
|
||||
import { isUserEligible } from "./user";
|
||||
|
||||
export async function getGuild(
|
||||
user,
|
||||
guildId: string,
|
||||
env
|
||||
): Promise<Guild | undefined> {
|
||||
const guilds = await getUserGuilds(user);
|
||||
const guild = guilds.find((g) => g.id === guildId);
|
||||
|
||||
if (!guild || !(await isMutualGuild(guild, env))) return undefined;
|
||||
|
||||
return guild;
|
||||
}
|
||||
|
||||
export async function getUserGuilds(user): Promise<Guild[]> {
|
||||
const discordApiGuildsResponse = await fetch(
|
||||
"https://discord.com/api/v10/users/@me/guilds",
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${user.sensitive.accessToken as string}`,
|
||||
"Cache-Control": "max-age=300",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return (await discordApiGuildsResponse.json()) as Guild[];
|
||||
}
|
||||
|
||||
export async function filterUserGuilds(
|
||||
guilds: Guild[],
|
||||
env
|
||||
): Promise<MutualeGuild[]> {
|
||||
const filtered = guilds
|
||||
.filter(isUserEligible)
|
||||
.sort((a, b) => Number(b.owner) - Number(a.owner));
|
||||
|
||||
const result: MutualeGuild[] = [];
|
||||
|
||||
for (const guild of filtered) {
|
||||
const mutual = await isMutualGuild(guild, env);
|
||||
|
||||
result.push({ mutual, guild });
|
||||
}
|
||||
|
||||
result.sort((a, b) => Number(b.mutual) - Number(a.mutual));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function isMutualGuild(guild: Guild, env): Promise<boolean> {
|
||||
const res = await fetch(
|
||||
`https://discord.com/api/v10/guilds/${guild.id}/members/${env.DISCORD_CLIENT_ID}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bot ${env.DISCORD_BOT_TOKEN}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return res.ok;
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
import type { Guild } from "~/env";
|
||||
|
||||
// Checks if user has AMDINISTRATOR permissions in the guild
|
||||
export function isUserEligible(guild: Guild): boolean {
|
||||
return (BigInt(guild.permissions) & 0x8n) == 0x8n;
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
import { initializeLucia, initializeDiscord } from "./lib/auth";
|
||||
import { defineMiddleware } from "astro:middleware";
|
||||
|
||||
export const onRequest = defineMiddleware(async (context, next) => {
|
||||
const lucia = initializeLucia(context.locals.runtime.env.DB);
|
||||
context.locals.lucia = lucia;
|
||||
const discord = initializeDiscord(
|
||||
context.locals.runtime.env.DISCORD_CLIENT_ID,
|
||||
context.locals.runtime.env.DISCORD_CLIENT_SECRET,
|
||||
context.locals.runtime.env.DISCORD_REDIRECT_URI
|
||||
);
|
||||
context.locals.discord = discord;
|
||||
const sessionId = context.cookies.get(lucia.sessionCookieName)?.value ?? null;
|
||||
if (!sessionId) {
|
||||
context.locals.user = null;
|
||||
context.locals.session = null;
|
||||
return next();
|
||||
}
|
||||
|
||||
const { session, user } = await lucia.validateSession(sessionId);
|
||||
if (session && session.fresh) {
|
||||
const sessionCookie = lucia.createSessionCookie(session.id);
|
||||
context.cookies.set(
|
||||
sessionCookie.name,
|
||||
sessionCookie.value,
|
||||
sessionCookie.attributes
|
||||
);
|
||||
}
|
||||
if (!session) {
|
||||
const sessionCookie = lucia.createBlankSessionCookie();
|
||||
context.cookies.set(
|
||||
sessionCookie.name,
|
||||
sessionCookie.value,
|
||||
sessionCookie.attributes
|
||||
);
|
||||
}
|
||||
context.locals.session = session;
|
||||
context.locals.user = user;
|
||||
return next();
|
||||
});
|
|
@ -1,16 +0,0 @@
|
|||
import type { APIRoute } from "astro";
|
||||
import { filterUserGuilds, getUserGuilds } from "~/lib/guilds";
|
||||
|
||||
export const GET: APIRoute = async ({ locals }) => {
|
||||
const user = locals.user;
|
||||
if (!user) {
|
||||
return new Response(null, {
|
||||
status: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const guilds = await getUserGuilds(user);
|
||||
const res = await filterUserGuilds(guilds, locals.runtime.env);
|
||||
|
||||
return Response.json(res);
|
||||
};
|
|
@ -1,100 +0,0 @@
|
|||
import { OAuth2RequestError } from "arctic";
|
||||
import type { APIContext } from "astro";
|
||||
import { generateIdFromEntropySize } from "lucia";
|
||||
|
||||
type UserRow = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
export async function GET(context: APIContext): Promise<Response> {
|
||||
const code = context.url.searchParams.get("code");
|
||||
const state = context.url.searchParams.get("state");
|
||||
const storedState = context.cookies.get("discord_oauth_state")?.value ?? null;
|
||||
if (!code || !state || !storedState || state !== storedState) {
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const tokens = await context.locals.discord.validateAuthorizationCode(code);
|
||||
const disocrdUserResponse = await fetch(
|
||||
"https://discord.com/api/users/@me",
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens.accessToken}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const discordUser: DiscordUser = await disocrdUserResponse.json();
|
||||
|
||||
const existingUser = await context.locals.runtime.env.DB.prepare(
|
||||
"SELECT * FROM user WHERE discord_id = ?1"
|
||||
)
|
||||
.bind(discordUser.id)
|
||||
.first<UserRow>();
|
||||
|
||||
if (existingUser) {
|
||||
const session = await context.locals.lucia.createSession(
|
||||
existingUser.id,
|
||||
{}
|
||||
);
|
||||
|
||||
const sessionCookie = context.locals.lucia.createSessionCookie(
|
||||
session.id
|
||||
);
|
||||
|
||||
context.cookies.set(
|
||||
sessionCookie.name,
|
||||
sessionCookie.value,
|
||||
sessionCookie.attributes
|
||||
);
|
||||
return context.redirect("/dashboard");
|
||||
}
|
||||
|
||||
const userId = generateIdFromEntropySize(10); // 16 characters long
|
||||
|
||||
await context.locals.runtime.env.DB.prepare(
|
||||
"INSERT INTO user (id, discord_id, username, avatar, access_token, access_token_expiration, refresh_token) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"
|
||||
)
|
||||
.bind(
|
||||
userId,
|
||||
discordUser.id,
|
||||
discordUser.username,
|
||||
discordUser.avatar,
|
||||
tokens.accessToken,
|
||||
tokens.accessTokenExpiresAt.getTime(),
|
||||
tokens.refreshToken
|
||||
)
|
||||
.run();
|
||||
|
||||
const session = await context.locals.lucia.createSession(userId, {});
|
||||
const sessionCookie = context.locals.lucia.createSessionCookie(session.id);
|
||||
context.cookies.set(
|
||||
sessionCookie.name,
|
||||
sessionCookie.value,
|
||||
sessionCookie.attributes
|
||||
);
|
||||
return context.redirect("/dashboard");
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
|
||||
// the specific error message depends on the provider
|
||||
if (e instanceof OAuth2RequestError) {
|
||||
// invalid code
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
return new Response(null, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
interface DiscordUser {
|
||||
id: string;
|
||||
username: string;
|
||||
avatar: string;
|
||||
}
|
13
apps/website/src/pages/auth/login.astro
Normal file
13
apps/website/src/pages/auth/login.astro
Normal file
|
@ -0,0 +1,13 @@
|
|||
---
|
||||
import Layout from "~/layouts/Layout.astro";
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<script>
|
||||
const { signIn } = await import("auth-astro/client");
|
||||
signIn("discord", {
|
||||
redirect: false,
|
||||
callbackUrl: "/dashboard",
|
||||
});
|
||||
</script>
|
||||
</Layout>
|
|
@ -1,20 +0,0 @@
|
|||
import { generateState } from "arctic";
|
||||
|
||||
import type { APIContext } from "astro";
|
||||
|
||||
export async function GET(context: APIContext): Promise<Response> {
|
||||
const state = generateState();
|
||||
const url = await context.locals.discord.createAuthorizationURL(state, {
|
||||
scopes: ["identify", "guilds"],
|
||||
});
|
||||
|
||||
context.cookies.set("discord_oauth_state", state, {
|
||||
path: "/",
|
||||
secure: import.meta.env.PROD,
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 10,
|
||||
sameSite: "lax",
|
||||
});
|
||||
|
||||
return context.redirect(url.toString());
|
||||
}
|
14
apps/website/src/pages/auth/logout.astro
Normal file
14
apps/website/src/pages/auth/logout.astro
Normal file
|
@ -0,0 +1,14 @@
|
|||
---
|
||||
import Layout from "~/layouts/Layout.astro";
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<script>
|
||||
const { signOut } = await import("auth-astro/client");
|
||||
signOut({
|
||||
// @ts-expect-error
|
||||
redirect: false,
|
||||
callbackUrl: "/",
|
||||
});
|
||||
</script>
|
||||
</Layout>
|
|
@ -1,20 +0,0 @@
|
|||
import type { APIContext } from "astro";
|
||||
|
||||
export async function GET(context: APIContext): Promise<Response> {
|
||||
if (!context.locals.session) {
|
||||
return new Response(null, {
|
||||
status: 401,
|
||||
});
|
||||
}
|
||||
|
||||
await context.locals.lucia.invalidateSession(context.locals.session.id);
|
||||
|
||||
const sessionCookie = context.locals.lucia.createBlankSessionCookie();
|
||||
context.cookies.set(
|
||||
sessionCookie.name,
|
||||
sessionCookie.value,
|
||||
sessionCookie.attributes
|
||||
);
|
||||
|
||||
return context.redirect("/");
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
---
|
||||
import GuildInfo from "~/components/dashboard/GuildInfo.astro";
|
||||
import UserInfo from "~/components/dashboard/UserInfo.astro";
|
||||
import Layout from "~/layouts/Layout.astro";
|
||||
import { getGuild } from "~/lib/guilds";
|
||||
import { isUserEligible } from "~/lib/user";
|
||||
|
||||
const { id } = Astro.params;
|
||||
|
||||
const user = Astro.locals.user;
|
||||
if (!user || !id) {
|
||||
return Astro.redirect("/auth/login");
|
||||
}
|
||||
|
||||
const guild = await getGuild(user, id, Astro.locals.runtime.env);
|
||||
if (!guild) {
|
||||
return Astro.redirect("/dashboard");
|
||||
}
|
||||
|
||||
const eligible = isUserEligible(guild);
|
||||
if (!eligible) {
|
||||
return Astro.redirect("/dashboard");
|
||||
}
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<div class="flex flex-col items-center justify-center md:flex-row">
|
||||
<UserInfo />
|
||||
|
||||
<p class="px-6 text-5xl text-white">on</p>
|
||||
|
||||
<GuildInfo id={guild.id} name={guild.name} icon={guild.icon} />
|
||||
</div>
|
||||
|
||||
You can manage guild {guild.name} with id {guild.id}
|
||||
</Layout>
|
|
@ -1,22 +1,8 @@
|
|||
---
|
||||
import Layout from "~/layouts/Layout.astro";
|
||||
import Container from "~/components/Container.astro";
|
||||
import GuildSelector from "~/components/preact/GuildSelector";
|
||||
import UserInfo from "~/components/dashboard/UserInfo.astro";
|
||||
import { getSession } from "auth-astro/server";
|
||||
|
||||
if (!Astro.locals.user) {
|
||||
return Astro.redirect("/auth/login");
|
||||
}
|
||||
const session = await getSession(Astro.request);
|
||||
console.log(session);
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<UserInfo />
|
||||
|
||||
<Container class="pb-4">
|
||||
<main
|
||||
class="flex flex-wrap items-center justify-center gap-12 pb-4 text-white"
|
||||
>
|
||||
<GuildSelector client:load />
|
||||
</main>
|
||||
</Container>
|
||||
</Layout>
|
||||
{session ? <p>Welcome {session.user?.name}</p> : <p>Not logged in</p>}
|
||||
|
|
|
@ -2,11 +2,8 @@
|
|||
import Layout from "~/layouts/Layout.astro";
|
||||
import Invite from "~/components/Invite.astro";
|
||||
import Computer from "~/components/Computer.astro";
|
||||
import Settings from "~/components/Settings.astro";
|
||||
import Logo from "~/assets/logo.png";
|
||||
import { Image } from "astro:assets";
|
||||
|
||||
export const prerender = true;
|
||||
---
|
||||
|
||||
<Layout>
|
||||
|
@ -35,22 +32,15 @@ export const prerender = true;
|
|||
<div class="mt-6 flex flex-col gap-6 md:flex-row">
|
||||
<a
|
||||
href="https://discord.com/api/oauth2/authorize?client_id=923267906941370368&permissions=268435456&scope=bot%20applications.commands"
|
||||
class="broder-1 duration-400 flex items-center justify-center gap-x-3 rounded-lg border border-blue bg-blue/25 px-10 py-3 text-lg font-semibold text-white shadow-2xl shadow-blue/25 transition-colors ease-out hover:bg-blue/40 hover:shadow-blue/30"
|
||||
class="broder-1 duration-400 flex items-center justify-center gap-x-3 rounded-lg border border-[#5865F2] bg-[#5865F2]/25 px-10 py-3 text-lg font-semibold text-white shadow-2xl shadow-[#5865F2]/25 transition-colors ease-out hover:bg-[#5865F2]/40 hover:shadow-[#5865F2]/30"
|
||||
target="_blank"
|
||||
>
|
||||
<Invite />
|
||||
Add to Discord</a
|
||||
>
|
||||
<a
|
||||
href="/dashboard"
|
||||
class="broder-1 duration-400 flex items-center justify-center gap-x-3 rounded-lg border border-gold bg-gold/25 px-10 py-3 text-lg font-semibold text-white shadow-2xl shadow-gold/25 transition-colors ease-out hover:bg-gold/40 hover:shadow-gold/30"
|
||||
>
|
||||
<Settings />
|
||||
Dashboard</a
|
||||
>
|
||||
<a
|
||||
href="https://github.com/xHyroM/roles-bot"
|
||||
class="broder-1 duration-400 flex items-center justify-center gap-x-3 rounded-lg border border-gray-50 bg-gray-50/25 px-10 py-3 text-lg font-semibold text-white shadow-2xl shadow-gray-50/25 transition-colors ease-out hover:bg-gray-50/40 hover:shadow-gray-50/30"
|
||||
class="broder-1 duration-400 flex items-center justify-center gap-x-3 rounded-lg border border-[#FFA500] bg-[#FFA500]/25 px-10 py-3 text-lg font-semibold text-white shadow-2xl shadow-[#FFA500]/25 transition-colors ease-out hover:bg-[#FFA500]/40 hover:shadow-[#FFA500]/30"
|
||||
target="_blank"
|
||||
>
|
||||
<Computer />
|
||||
|
|
|
@ -5,9 +5,6 @@ module.exports = {
|
|||
extend: {
|
||||
colors: {
|
||||
dark: "#111111",
|
||||
"dark-100": "#1A1A1A",
|
||||
blue: "#5865F2",
|
||||
gold: "#FFA500",
|
||||
},
|
||||
fontFamily: {
|
||||
body: ["Montserrat", "sans-serif"],
|
||||
|
|
|
@ -1,12 +1,11 @@
|
|||
{
|
||||
"extends": "astro/tsconfigs/strictest",
|
||||
"extends": "astro/tsconfigs/base",
|
||||
"compilerOptions": {
|
||||
"strictNullChecks": true,
|
||||
"allowJs": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"~/*": ["src/*"]
|
||||
},
|
||||
"types": ["./src/env.d.ts"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
11
apps/website/worker-configuration.d.ts
vendored
11
apps/website/worker-configuration.d.ts
vendored
|
@ -1,11 +0,0 @@
|
|||
// Generated by Wrangler on Sat Aug 03 2024 17:34:42 GMT+0200 (Central European Summer Time)
|
||||
// by running `wrangler types`
|
||||
|
||||
interface Env {
|
||||
PRO: string;
|
||||
DISCORD_CLIENT_ID: string;
|
||||
DISCORD_CLIENT_SECRET: string;
|
||||
DISCORD_BOT_TOKEN: string;
|
||||
DISCORD_REDIRECT_URI: string;
|
||||
DB: D1Database;
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
name = "roles-bot"
|
||||
|
||||
[[d1_databases]]
|
||||
binding = "DB" # i.e. available in your Worker on env.DB
|
||||
database_name = "roles-bot-dashboard"
|
||||
database_id = "fdc6f902-9142-44bf-9be9-b38d351ffd27"
|
Loading…
Reference in a new issue