@sapphire/plugin-api
Version:
Plugin for @sapphire/framework to expose a REST API
74 lines (71 loc) • 2.85 kB
JavaScript
;
var discord_js = require('discord.js');
var querystring = require('querystring');
var undici = require('undici');
var Route_cjs = require('../../lib/structures/Route.cjs');
var HttpCodes_cjs = require('../../lib/structures/http/HttpCodes.cjs');
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
var _PluginRoute = class _PluginRoute extends Route_cjs.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_cjs.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_cjs.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 undici.fetch(discord_js.OAuth2Routes.tokenURL, {
method: "POST",
body: querystring.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;
exports.PluginRoute = PluginRoute;
//# sourceMappingURL=callback.post.cjs.map
//# sourceMappingURL=callback.post.cjs.map