discord-authorize
Version:
A node module for easy authentication with Discord
195 lines • 7.89 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Scopes = exports.DiscordAuthorization = void 0;
const axios_1 = __importDefault(require("axios"));
const url_1 = require("url");
const types_1 = require("../types");
Object.defineProperty(exports, "Scopes", { enumerable: true, get: function () { return types_1.Scopes; } });
const rest_1 = require("../rest");
const getType_1 = __importDefault(require("../util/getType"));
const errors_1 = require("../errors");
/**
* Represents an instance of Discord OAuth2 authorization flow.
*/
class DiscordAuthorization {
/**
* Creates an instance of DiscordAuthorization.
* @param {OAuth2Options} options - Options for OAuth2 authorization.
*/
constructor(options) {
this.accessToken = null;
this.baseURL = "https://discord.com/api/v10";
this.refreshToken = null;
this.clientToken = null;
if ((0, getType_1.default)(options.clientId) !== "snowflake") {
throw new TypeError(`Expected type of client id to be 'snowflake' but got '${(0, getType_1.default)(options.clientId)}' instead.`);
}
if ((0, getType_1.default)(options.clientSecret) !== "string") {
throw new TypeError(`Expected type of client secret to be 'string' but got '${(0, getType_1.default)(options.clientSecret)}' instead.`);
}
if ((0, getType_1.default)(options.redirectUri) !== "string") {
throw new TypeError(`Expected type of redirect uri to be 'string' but got '${(0, getType_1.default)(options.redirectUri)}' instead.`);
}
if (options.clientToken !== undefined &&
(0, getType_1.default)(options.clientToken) !== "string") {
throw new TypeError(`Expected type of client token to be 'string' but got '${(0, getType_1.default)(options.clientToken)}' instead.`);
}
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.redirectUri = options.redirectUri;
this.clientToken = options.clientToken ?? null;
}
/**
* Generates an OAuth2 authorization link for Discord.
* @param {{ scopes: Scopes[] }} param0 - Authorization scopes array.
* @param {string} [state="1bac472"] - Authorization state
* @returns {string} - OAuth2 authorization link.
*/
generateOauth2Link({ scopes }, state = "1bac472") {
const url = (0, rest_1.generateLink)({ scopes: scopes }, state, this.clientId, this.redirectUri);
return url;
}
/**
* Exchanges an authorization code for access and refresh tokens.
* @param {string} code - Authorization code.
* @returns {Promise<object>} - Tokens object containing access and refresh tokens.
* @throws {Error} - If the exchange process fails.
*/
async exchangeCodeForTokens(code) {
const { accessToken, refreshToken } = await (0, rest_1.getTokens)(code, this.clientId, this.clientSecret, this.redirectUri);
return {
accessToken: accessToken,
refreshToken: refreshToken,
};
}
/**
* Sets the access token.
* @param {string} token - The access token to set.
*/
setAccessToken(token) {
this.accessToken = token;
}
/**
* Sets the refresh token.
* @param {string} token - The refresh token to set.
*/
setRefreshToken(token) {
this.refreshToken = token;
}
/**
* Revokes the existinga ccess token
*/
async refreshAccessToken() {
if (!this.accessToken || !this.refreshToken) {
throw new Error("Access token and refresh token are required to revoke the token.");
}
const params = new url_1.URLSearchParams();
params.append("client_id", this.clientId);
params.append("client_secret", this.clientSecret);
params.append("token", this.refreshToken);
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
await axios_1.default.post("https://discord.com/api/oauth2/token/revoke", params.toString(), config);
this.accessToken = null;
this.refreshToken = null;
}
/**
* Retrieves information about the authorized user.
* @returns {Promise<UserInfo>} - User information.
* @throws {Error} - If fetching user information fails.
*/
async getMyInfo() {
const info = await (0, rest_1.getInfo)(this.accessToken);
return info;
}
/**
* Retrieves connections of the authorized user.
* @returns {Promise<ConnectionType[]>} - User connections information.
* @throws {Error} - If fetching user connections fails.
*/
async getMyConnections() {
const info = await (0, rest_1.getConnections)(this.accessToken);
return info;
}
/**
* Retrives joined guilds of the authorized user.
* @returns {Promise<Guild[]>} - User guilds information
*/
async getGuilds() {
const info = await (0, rest_1.getGuilds)(this.accessToken);
return info;
}
/**
* Get info of the bot.
*/
getApplication() {
throw new Error("Use discord.js or eris or any other module for it.");
}
/**
* Joins a guild with the specified options.
* @param {GuildJoinOptions} options - The options for joining the guild.
* @returns {Promise<any>} A promise that resolves with the response data upon successful joining.
* @throws {Error} If an error occurs during the join process.
*/
async joinGuild(options) {
try {
const endpoint = `/guilds/${options.guildId}/members/${options.userId}`;
const rolesToAdd = options.roles || [];
const response = await axios_1.default.put(`${this.baseURL}${endpoint}`, { roles: rolesToAdd, access_token: this.accessToken }, {
headers: {
Authorization: `Bot ${this.clientToken}`,
"Content-Type": "application/json",
},
});
return response?.data;
}
catch (err) {
if (err?.response.data &&
err?.response.data.message &&
err?.response.status &&
err?.response.data.code === 0) {
throw new errors_1.DiscordAPIError(err?.response.data.message, err?.response.data);
}
else if (err?.response.data &&
err?.response.data.message &&
err?.response.status &&
err?.response.data.code !== 0) {
const sEM = errors_1.statusCodedErrorMessages[err?.response.data.code];
throw new errors_1.DiscordAPIError(sEM, err?.response.data);
}
else {
throw new Error(err?.response.data.message);
}
}
}
async getMyInfoFromGuild(guildId) {
const r = await (0, rest_1.getProfileInGuilds)(guildId, this.accessToken);
return r;
}
/**
* Retrieves the username of the authorized user.
* @returns {Promise<string>} - User's username.
* @throws {Error} - If fetching the username fails.
*/
async getMyUsername() {
const r = await (0, rest_1.username)(this.accessToken);
return r;
}
/**
* Retrieves the email of the authorized user.
* @returns {Promise<string>} - User's email.
* @throws {Error} - If fetching the email fails.
*/
async getMyEmail() {
const r = await (0, rest_1.email)(this.accessToken);
return String(r);
}
}
exports.DiscordAuthorization = DiscordAuthorization;
//# sourceMappingURL=authenticator.js.map