2024-01-15 00:46:24 +03:00
|
|
|
/*
|
|
|
|
* Vencord, a Discord client mod
|
|
|
|
* Copyright (c) 2023 Vendicated and contributors
|
|
|
|
* SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
*/
|
|
|
|
|
|
|
|
import { DataStore } from "@api/index";
|
|
|
|
import { Logger } from "@utils/Logger";
|
|
|
|
import { openModal } from "@utils/modal";
|
|
|
|
import { findByPropsLazy } from "@webpack";
|
|
|
|
import { showToast, Toasts, UserStore } from "@webpack/common";
|
|
|
|
|
|
|
|
import { ReviewDBAuth } from "./entities";
|
|
|
|
|
|
|
|
const DATA_STORE_KEY = "rdb-auth";
|
|
|
|
|
2024-01-15 17:36:24 +01:00
|
|
|
const { OAuth2AuthorizeModal } = findByPropsLazy("OAuth2AuthorizeModal");
|
2024-01-15 00:46:24 +03:00
|
|
|
|
|
|
|
export let Auth: ReviewDBAuth = {};
|
|
|
|
|
|
|
|
export async function initAuth() {
|
|
|
|
Auth = await getAuth() ?? {};
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getAuth(): Promise<ReviewDBAuth | undefined> {
|
|
|
|
const auth = await DataStore.get(DATA_STORE_KEY);
|
|
|
|
return auth?.[UserStore.getCurrentUser()?.id];
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getToken() {
|
|
|
|
const auth = await getAuth();
|
|
|
|
return auth?.token;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function updateAuth(newAuth: ReviewDBAuth) {
|
|
|
|
return DataStore.update(DATA_STORE_KEY, auth => {
|
|
|
|
auth ??= {};
|
|
|
|
Auth = auth[UserStore.getCurrentUser().id] ??= {};
|
|
|
|
|
|
|
|
if (newAuth.token) Auth.token = newAuth.token;
|
|
|
|
if (newAuth.user) Auth.user = newAuth.user;
|
|
|
|
|
|
|
|
return auth;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function authorize(callback?: any) {
|
|
|
|
openModal(props =>
|
2024-01-15 17:36:24 +01:00
|
|
|
<OAuth2AuthorizeModal
|
2024-01-15 00:46:24 +03:00
|
|
|
{...props}
|
|
|
|
scopes={["identify"]}
|
|
|
|
responseType="code"
|
|
|
|
redirectUri="https://manti.vendicated.dev/api/reviewdb/auth"
|
|
|
|
permissions={0n}
|
|
|
|
clientId="915703782174752809"
|
|
|
|
cancelCompletesFlow={false}
|
|
|
|
callback={async (response: any) => {
|
|
|
|
try {
|
|
|
|
const url = new URL(response.location);
|
|
|
|
url.searchParams.append("clientMod", "vencord");
|
|
|
|
const res = await fetch(url, {
|
2024-02-20 21:13:25 +03:00
|
|
|
headers: { Accept: "application/json" }
|
2024-01-15 00:46:24 +03:00
|
|
|
});
|
2024-01-22 03:18:48 +03:00
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
const { message } = await res.json();
|
|
|
|
showToast(message || "An error occured while authorizing", Toasts.Type.FAILURE);
|
|
|
|
return;
|
2024-01-15 00:46:24 +03:00
|
|
|
}
|
2024-01-22 03:18:48 +03:00
|
|
|
|
|
|
|
const { token } = await res.json();
|
|
|
|
updateAuth({ token });
|
|
|
|
showToast("Successfully logged in!", Toasts.Type.SUCCESS);
|
|
|
|
callback?.();
|
2024-01-15 00:46:24 +03:00
|
|
|
} catch (e) {
|
|
|
|
new Logger("ReviewDB").error("Failed to authorize", e);
|
|
|
|
}
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|