add withSession, cacheLayer, and userAgent to discordFetch

This commit is contained in:
41666 2020-12-14 14:43:22 -05:00
parent 12d8e99513
commit a85c4d5ddd
3 changed files with 59 additions and 33 deletions

View file

@ -1,31 +1,17 @@
import { SessionData } from 'roleypoly/common/types';
import { getSessionID, respond } from '../utils/api-tools';
import { Sessions } from '../utils/kv';
import { respond, withSession } from '../utils/api-tools';
const NotAuthenticated = (extra?: string) =>
respond(
{
err: extra || 'not authenticated',
},
{ status: 403 }
);
export const GetSession = async (request: Request): Promise<Response> => {
const sessionID = getSessionID(request);
if (!sessionID) {
return NotAuthenticated('missing auth header');
}
console.log(sessionID);
const sessionData = await Sessions.get<SessionData>(sessionID.id);
if (!sessionData) {
return NotAuthenticated('session not found');
}
const { tokens, ...withoutTokens } = sessionData;
export const GetSession = withSession(
(session?: SessionData) => (): Response => {
const { user, guilds, sessionID } = session || {};
return respond({
...withoutTokens,
user,
guilds,
sessionID,
});
};
},
{
mustAuthenticate: true,
}
);

View file

@ -15,7 +15,7 @@ router.add('GET', 'bot-join', BotJoin);
router.add('GET', 'login-bounce', LoginBounce);
router.add('GET', 'login-callback', LoginCallback);
router.add('GET', 'get-session', GetSession);
<<<<<<< HEAD
router.add('GET', 'get-slug', GetSlug);
router.add('GET', 'x-headers', (request) => {
const headers: { [x: string]: string } = {};
@ -25,9 +25,6 @@ router.add('GET', 'x-headers', (request) => {
return new Response(JSON.stringify(headers));
});
=======
router.add('GET', 'get-slug', GetSlug);
>>>>>>> init to fetch guild slug
addEventListener('fetch', (event: FetchEvent) => {
event.respondWith(router.handle(event.request));

View file

@ -1,9 +1,10 @@
import { UserGuildPermissions } from '../../common/types';
import { SessionData, UserGuildPermissions } from '../../common/types';
import {
evaluatePermission,
permissions as Permissions,
} from '../../common/utils/hasPermission';
import { WrappedKVNamespace } from './kv';
import { Handler } from '../router';
import { Sessions, WrappedKVNamespace } from './kv';
export const formData = (obj: Record<string, any>): string => {
return Object.keys(obj)
@ -63,6 +64,8 @@ export const discordFetch = async <T>(
const response = await fetch('https://discord.com/api/v8' + url, {
headers: {
authorization: `${authType} ${auth}`,
'user-agent':
'DiscordBot (https://github.com/roleypoly/roleypoly, git-main) (+https://roleypoly.com)',
},
});
@ -92,3 +95,43 @@ export const cacheLayer = <Identity, Data>(
return fallbackValue;
};
const NotAuthenticated = (extra?: string) =>
respond(
{
err: extra || 'not authenticated',
},
{ status: 403 }
);
type WithSessionOpts = {
mustAuthenticate?: boolean;
};
export const withSession = (
wrappedHandler: (session?: SessionData) => Handler,
{ mustAuthenticate }: WithSessionOpts = {}
): Handler => async (request: Request): Promise<Response> => {
const sessionID = getSessionID(request);
if (!sessionID) {
if (mustAuthenticate) {
return NotAuthenticated('missing authentication');
} else {
return await wrappedHandler(undefined)(request);
}
}
const session = await Sessions.get<SessionData>(sessionID.id);
if (!session) {
if (mustAuthenticate) {
return NotAuthenticated('authentication expired or not found');
} else {
return await wrappedHandler(undefined)(request);
}
}
return await wrappedHandler(session)(request);
};
export const mustBeAuthenticated = (handler: Handler) =>
withSession(() => handler, { mustAuthenticate: true });