Auth via gateway

This commit is contained in:
Kalle 2023-09-24 14:25:11 +03:00
parent 0371bfcd12
commit c12d8f3e65
2 changed files with 41 additions and 16 deletions

View File

@ -7,6 +7,8 @@ SESSION_SECRET=secret
// Auth https://discord.com/developers
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
AUTH_GATEWAY_URL=
AUTH_GATEWAY_SECRET=
// Patreon integration https://www.patreon.com/portal/registration/register-clients
PATREON_ACCESS_TOKEN=

View File

@ -57,24 +57,20 @@ export class DiscordStrategy extends OAuth2Strategy<
"Authorization",
`Bearer ${accessToken}`,
];
const discordResponses = await Promise.all([
fetch("https://discord.com/api/users/@me", {
headers: [authHeader],
}),
fetch("https://discord.com/api/users/@me/connections", {
headers: [authHeader],
}),
]);
const [user, connections] = discordUserDetailsSchema.parse(
await Promise.all(
discordResponses.map((res) => {
if (!res.ok) throw new Error("Call to Discord API failed");
const discordResponses = this.authGatewayEnabled()
? await this.fetchProfileViaGateway(accessToken)
: await Promise.all([
fetch("https://discord.com/api/users/@me", {
headers: [authHeader],
}).then(this.jsonIfOk),
fetch("https://discord.com/api/users/@me/connections", {
headers: [authHeader],
}).then(this.jsonIfOk),
]);
return res.json();
}),
),
);
const [user, connections] =
discordUserDetailsSchema.parse(discordResponses);
const userFromDb = db.users.upsert({
discordAvatar: user.avatar ?? null,
@ -92,6 +88,33 @@ export class DiscordStrategy extends OAuth2Strategy<
this.scope = "identify connections";
}
private authGatewayEnabled() {
return Boolean(
process.env["AUTH_GATEWAY_URL"] && process.env["AUTH_GATEWAY_SECRET"],
);
}
private async fetchProfileViaGateway(token: string) {
const url = `${process.env["AUTH_GATEWAY_URL"]}?token=${token}`;
const options: RequestInit = {
method: "GET",
headers: { "X-Require-Whisk-Auth": process.env["AUTH_GATEWAY_SECRET"]! },
};
return fetch(url, options).then(this.jsonIfOk);
}
private jsonIfOk(res: Response) {
if (!res.ok) {
throw new Error(
`Auth related call failed with status code ${res.status}`,
);
}
return res.json();
}
private parseConnections(
connections: z.infer<typeof partialDiscordConnectionsSchema>,
) {