UNPKG

@sapphire/plugin-api

Version:

Plugin for @sapphire/framework to expose a REST API

69 lines (67 loc) 2.45 kB
import { __name, __publicField } from '../../chunk-S573YWRP.mjs'; import { OAuth2Routes } from 'discord.js'; import { stringify } from 'querystring'; import { fetch } from 'undici'; import { Route } from '../../lib/structures/Route.mjs'; import { HttpCodes } from '../../lib/structures/http/HttpCodes.mjs'; var _PluginRoute = class _PluginRoute extends Route { constructor(context) { super(context, { route: "oauth/callback", methods: ["POST"] }); __publicField(this, "redirectUri"); const { server } = this.container; this.enabled = server.auth !== null; this.redirectUri = server.auth?.redirect; } async run(request, response) { const body = await request.readBodyJson(); if (typeof body?.code !== "string") { return response.badRequest(); } const value = await this.fetchAuth(body); if (value === null) { return response.status(HttpCodes.InternalServerError).json({ error: "Failed to fetch the token." }); } const now = Date.now(); const auth = this.container.server.auth; const data = await auth.fetchData(value.access_token); if (!data.user) { return response.status(HttpCodes.InternalServerError).json({ error: "Failed to fetch the user." }); } const token = auth.encrypt({ id: data.user.id, expires: now + value.expires_in * 1e3, refresh: value.refresh_token, token: value.access_token }); response.cookies.add(auth.cookie, token, { maxAge: value.expires_in }); return response.json(data); } async fetchAuth(body) { const { id, secret } = this.container.server.auth; const data = { /* eslint-disable @typescript-eslint/naming-convention */ client_id: id, client_secret: secret, code: body.code, grant_type: "authorization_code", redirect_uri: this.redirectUri ?? body.redirectUri /* eslint-enable @typescript-eslint/naming-convention */ }; const result = await fetch(OAuth2Routes.tokenURL, { method: "POST", body: stringify(data), headers: { "content-type": "application/x-www-form-urlencoded" } }); const json = await result.json(); if (result.ok) return json; this.container.logger.error(json); return null; } }; __name(_PluginRoute, "PluginRoute"); var PluginRoute = _PluginRoute; export { PluginRoute }; //# sourceMappingURL=callback.post.mjs.map //# sourceMappingURL=callback.post.mjs.map