Updated the discord.ts controller

This commit is contained in:
Mathias Wagner 2023-11-08 12:42:23 +01:00
parent c9f9b030a5
commit d86a155772
Signed by: Mathias
GPG Key ID: B8DC354B0A1F5B44

View File

@ -1,4 +1,5 @@
import DiscordOauth2 from 'discord-oauth2'; import DiscordOauth2 from 'discord-oauth2';
const oauth = new DiscordOauth2(); const oauth = new DiscordOauth2();
/** /**
@ -14,6 +15,33 @@ export const createTokenByCode = (code: string) => oauth.tokenRequest({
code code
}); });
/**
* Generate a new access token from the refresh token
* @param refreshToken The token to refresh the access token
*/
export const generateToken = (refreshToken: string) => oauth.tokenRequest({
grantType: "refresh_token",
scope: "identify guilds",
clientId: process.env.DC_CLIENT,
clientSecret: process.env.DC_SECRET,
redirectUri: process.env.DC_REDIRECT_URI,
refreshToken
});
/**
* Gets the guilds from the access token.
* This function also automatically renews the access token if it expires
* @param refreshDate The date of when to renew the provided access token
* @param refreshToken The token to refresh the access token
* @param accessToken The token to access the discord api
*/
export const getGuilds = async (refreshDate: Date, refreshToken: string, accessToken: string) => {
let token = accessToken;
if (refreshDate.getDate() > Date.now())
token = (await generateToken(refreshToken)).access_token;
return await oauth.getUserGuilds(token);
}
/** /**
* Gets user information from the discord api * Gets user information from the discord api
* @param token The access token of the user * @param token The access token of the user