Skip to content

Instantly share code, notes, and snippets.

@ChillFish8
Last active September 3, 2023 16:56
Show Gist options
  • Save ChillFish8/98c0edc915804b07ff5f7e4f8c516738 to your computer and use it in GitHub Desktop.
Save ChillFish8/98c0edc915804b07ff5f7e4f8c516738 to your computer and use it in GitHub Desktop.
Foo
import {Jumper} from "svelte-loading-spinners";
import {DISCORD_LOGIN_URI} from "$lib/api/config";
import {onMount} from "svelte";
import {ALLOWED_ORIGIN, flags} from "../../lib/api/config.js";
import {extractUserData, requestUserAccess} from "../../lib/api/auth.js";
import {accessToken, currentUser} from "../../lib/stores/auth.js";
import {goto} from "$app/navigation";
import Primary from "../../lib/compontents/buttons/Primary.svelte";
import Secondary from "../../lib/compontents/buttons/Secondary.svelte";
import {writable} from "svelte/store";
import Avatar from "../../lib/compontents/icons/CurrentUserAvatar.svelte";
const DEFAULT = 0;
const PENDING = 1 << 0;
const FORBIDDEN = 1 << 1;
const SUCCESS = 1 << 2;
const ACCESS_REQUESTED = 1 << 3;
let state = writable(DEFAULT);
let temporaryUserState = writable(undefined);
let pendingLoginPromise = null;
onMount(() => {
if (typeof $currentUser !== "undefined") {
goto("/");
return;
}
if (typeof window == "undefined") {
return
}
pendingLoginPromise = new Promise((resolve) => {
function handleMessage(event) {
// Do we trust the sender of this message?
if (event.origin !== ALLOWED_ORIGIN) {
return
}
resolve(event.data);
window.removeEventListener("message", handleMessage);
}
window.addEventListener("message", handleMessage);
});
});
async function onLoginDiscord() {
state.set(PENDING);
let params = `
directories=no,
titlebar=no,
toolbar=no,
location=no,
status=no,
menubar=no,
scrollbars=no,
resizable=no,
width=500,
height=850
`;
let window = open(DISCORD_LOGIN_URI, 'Discord Login', params);
const handle = setInterval(() => {
window.postMessage("check");
}, 500);
let response = null;
if (pendingLoginPromise !== null) {
response = await pendingLoginPromise;
}
clearTimeout(handle);
window.close();
try {
const data = extractUserData(response);
temporaryUserState.set(data.user);
if ((data.permissions & flags.USER) === 0)
state.set(FORBIDDEN);
if ($state === FORBIDDEN)
return;
accessToken.set(response);
} catch {
accessToken.set(undefined);
state.set(FORBIDDEN);
return;
}
setTimeout(() => {
goto("/");
}, 2000);
state.set(SUCCESS | PENDING);
}
async function requestAccess() {
state.set($state | PENDING);
if (typeof temporaryUserState !== "undefined") {
await requestUserAccess(($temporaryUserState).id);
}
state.set(ACCESS_REQUESTED | PENDING);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment