aboutsummaryrefslogtreecommitdiff
path: root/src/discord.ts
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2021-05-27 16:56:50 -0500
committerGitHub <noreply@github.com>2021-05-27 16:56:50 -0500
commitc9097dc2d0749fa63fd731423bc87a5452f0444d (patch)
tree50afe6b99cf3ed6bd7369e804316c05c7407b5ca /src/discord.ts
parenta3662fb5888bd031b27cc81028ba86b0271eb442 (diff)
downloadskyblock-api-c9097dc2d0749fa63fd731423bc87a5452f0444d.tar.gz
skyblock-api-c9097dc2d0749fa63fd731423bc87a5452f0444d.tar.bz2
skyblock-api-c9097dc2d0749fa63fd731423bc87a5452f0444d.zip
Profile customization (#45)
* add basic discord auth * add uuid dependency * add lastUpdated to sessions * add route to get session from id * add accounts collection * update build * add gm rank * add `customization` url parameter * add customization parameter to /player/:user * add route to get info from discord id * remove a console.log * Update database.js * Update package.json * fix tests
Diffstat (limited to 'src/discord.ts')
-rw-r--r--src/discord.ts64
1 files changed, 64 insertions, 0 deletions
diff --git a/src/discord.ts b/src/discord.ts
new file mode 100644
index 0000000..41f4c6e
--- /dev/null
+++ b/src/discord.ts
@@ -0,0 +1,64 @@
+import fetch from 'node-fetch'
+import { Agent } from 'https'
+
+const DISCORD_CLIENT_ID = '656634948148527107'
+
+const httpsAgent = new Agent({
+ keepAlive: true
+})
+
+export interface TokenResponse {
+ access_token: string
+ expires_in: number
+ refresh_token: string
+ scope: string
+ token_type: string
+}
+
+export interface DiscordUser {
+ id: string
+ username: string
+ avatar: string
+ discriminator: string
+ public_flags: number
+ flags: number
+ locale: string
+ mfa_enabled: boolean
+}
+
+export async function exchangeCode(redirectUri: string, code: string): Promise<TokenResponse> {
+ const API_ENDPOINT = 'https://discord.com/api/v6'
+ const CLIENT_SECRET = process.env.discord_client_secret
+ const data = {
+ 'client_id': DISCORD_CLIENT_ID,
+ 'client_secret': CLIENT_SECRET,
+ 'grant_type': 'authorization_code',
+ 'code': code,
+ 'redirect_uri': redirectUri,
+ 'scope': 'identify'
+ }
+ console.log(new URLSearchParams(data).toString())
+ const fetchResponse = await fetch(
+ API_ENDPOINT + '/oauth2/token',
+ {
+ method: 'POST',
+ agent: () => httpsAgent,
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams(data).toString()
+ }
+ )
+ return await fetchResponse.json()
+}
+
+
+export async function getUser(accessToken: string): Promise<DiscordUser> {
+ const API_ENDPOINT = 'https://discord.com/api/v6'
+ const response = await fetch(
+ API_ENDPOINT + '/users/@me',
+ {
+ headers: {'Authorization': 'Bearer ' + accessToken},
+ agent: () => httpsAgent,
+ }
+ )
+ return response.json()
+}