Compare commits

..

16 commits

33 changed files with 910 additions and 96 deletions

214
LICENSE
View file

@ -1,21 +1,201 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2021 Jozef Steinhübl
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 Jozef Steinhübl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,6 @@
PRO=<production>
DISCORD_CLIENT_ID=<client id>
DISCORD_CLIENT_SECRET=<client secret>
DISCORD_BOT_TOKEN=<bot token>
DISCORD_REDIRECT_URI=<domain>/auth/callback/discord

View file

@ -19,3 +19,6 @@ pnpm-debug.log*
# macOS-specific files
.DS_Store
.dev.vars
.wrangler/

View file

@ -1,25 +1,29 @@
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));
// https://astro.build/config
export default defineConfig({
site: CONFIG.origin,
integrations: [sitemap(), tailwind(), auth()],
output: "server",
adapter: cloudflare(),
vite: {
resolve: {
alias: {
"~": path.resolve(__dirname, "./src"),
},
},
},
site: CONFIG.origin,
integrations: [sitemap(), tailwind(), preact()],
output: "server",
adapter: cloudflare(),
security: {
checkOrigin: true,
},
vite: {
resolve: {
alias: {
"~": path.resolve(__dirname, "./src"),
},
},
},
});

View file

@ -1,23 +1,50 @@
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({
providers: [
Discord({
clientId: import.meta.env.DISCORD_CLIENT_ID,
clientSecret: import.meta.env.DISCORD_CLIENT_SECRET,
}),
],
callbacks: {
session({ session, token }) {
if (session.user && token?.sub) {
session.user.id = token.sub;
}
return session;
},
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
},
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",
}),
],
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;
}
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;
},
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
},
});

Binary file not shown.

View file

@ -0,0 +1,18 @@
-- 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)
);

View file

@ -10,15 +10,18 @@
},
"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",
"@auth/core": "^0.32.0",
"@lucia-auth/adapter-sqlite": "^3.0.2",
"@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",
"auth-astro": "^4.1.2",
"lucia": "^3.2.0",
"preact": "^10.23.1",
"tailwindcss": "^3.3.1"
},
"devDependencies": {

View file

@ -0,0 +1,7 @@
---
const { class: className } = Astro.props;
---
<div class={`container mx-auto px-4 ${className ?? ""}`}>
<slot />
</div>

View file

@ -0,0 +1,40 @@
<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
>

After

Width:  |  Height:  |  Size: 2.2 KiB

View file

@ -0,0 +1,25 @@
---
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>

View file

@ -0,0 +1,19 @@
---
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>

View file

@ -0,0 +1,34 @@
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>
);
}

View file

@ -0,0 +1,31 @@
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} />);
}
}

View file

@ -0,0 +1,9 @@
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>
);
}

View file

@ -1 +1,36 @@
/// <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;
}
}

View file

@ -0,0 +1,54 @@
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;
}

View file

@ -0,0 +1,63 @@
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;
}

View file

@ -0,0 +1,6 @@
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;
}

View file

@ -0,0 +1,40 @@
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();
});

View file

@ -0,0 +1,16 @@
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);
};

View file

@ -0,0 +1,100 @@
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;
}

View file

@ -1,13 +0,0 @@
---
import Layout from "~/layouts/Layout.astro";
---
<Layout>
<script>
const { signIn } = await import("auth-astro/client");
signIn("discord", {
redirect: false,
callbackUrl: "/dashboard",
});
</script>
</Layout>

View file

@ -0,0 +1,20 @@
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());
}

View file

@ -1,14 +0,0 @@
---
import Layout from "~/layouts/Layout.astro";
---
<Layout>
<script>
const { signOut } = await import("auth-astro/client");
signOut({
// @ts-expect-error
redirect: false,
callbackUrl: "/",
});
</script>
</Layout>

View file

@ -0,0 +1,20 @@
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("/");
}

View file

@ -0,0 +1,36 @@
---
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>

View file

@ -1,8 +1,22 @@
---
import { getSession } from "auth-astro/server";
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";
const session = await getSession(Astro.request);
console.log(session);
if (!Astro.locals.user) {
return Astro.redirect("/auth/login");
}
---
{session ? <p>Welcome {session.user?.name}</p> : <p>Not logged in</p>}
<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>

View file

@ -2,8 +2,11 @@
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>
@ -32,15 +35,22 @@ import { Image } from "astro:assets";
<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-[#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"
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"
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-[#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"
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"
target="_blank"
>
<Computer />

View file

@ -1,15 +1,18 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
theme: {
extend: {
colors: {
dark: "#111111",
},
fontFamily: {
body: ["Montserrat", "sans-serif"],
},
},
},
plugins: [],
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
theme: {
extend: {
colors: {
dark: "#111111",
"dark-100": "#1A1A1A",
blue: "#5865F2",
gold: "#FFA500",
},
fontFamily: {
body: ["Montserrat", "sans-serif"],
},
},
},
plugins: [],
};

View file

@ -1,11 +1,12 @@
{
"extends": "astro/tsconfigs/base",
"extends": "astro/tsconfigs/strictest",
"compilerOptions": {
"strictNullChecks": true,
"allowJs": true,
"baseUrl": ".",
"paths": {
"~/*": ["src/*"]
}
},
"types": ["./src/env.d.ts"]
}
}

11
apps/website/worker-configuration.d.ts vendored Normal file
View file

@ -0,0 +1,11 @@
// 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;
}

View file

@ -0,0 +1,6 @@
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"