77 lines
2.1 KiB
TypeScript
77 lines
2.1 KiB
TypeScript
import axios, { AxiosResponse } from "axios";
|
|
import { BaseEntity, Column, Entity, PrimaryColumn } from "typeorm";
|
|
import { API_URL } from "../config/Constants";
|
|
import { DiscordCache } from "./DiscordCache";
|
|
import { StateToken } from "./StateToken";
|
|
|
|
@Entity({ name: "discord_tokens" })
|
|
export class DiscordToken extends BaseEntity {
|
|
@PrimaryColumn("uuid")
|
|
id: string;
|
|
|
|
@Column({ unique: true })
|
|
authToken: string;
|
|
|
|
@Column()
|
|
expiring: Date;
|
|
|
|
constructor(id: string, token: string) {
|
|
super();
|
|
this.id = id;
|
|
this.authToken = token;
|
|
this.expiring = new Date();
|
|
this.expiring.setDate(this.expiring.getDate() + 7);
|
|
}
|
|
|
|
/**
|
|
*
|
|
* queryData uses the discord token information to get the Discord details
|
|
* for the user. If the data is not cached, it will be cached. Otherwise, it
|
|
* returns the cached data. The data is queried from the Discord api.
|
|
*
|
|
*/
|
|
async queryData(): Promise<DiscordCache> {
|
|
// If the cache exists, return it
|
|
const cache = await DiscordCache.findOne({
|
|
where: { authToken: this.authToken },
|
|
});
|
|
if (cache) {
|
|
return cache;
|
|
}
|
|
|
|
// Query the information from the Discord API
|
|
let res: AxiosResponse<any>;
|
|
try {
|
|
res = await axios.get(`${API_URL}/users/@me`, { // https://discord.com/api/v9/users/@me
|
|
headers: { Authorization: `Bearer ${this.authToken}` },
|
|
validateStatus: (status) => status < 500,
|
|
});
|
|
} catch (err) {
|
|
console.error("Unexpected discord response", this, err.response);
|
|
return Promise.reject({
|
|
reason: "An internal error has occurred.",
|
|
status: 500,
|
|
});
|
|
}
|
|
|
|
// Error 4xx means invalid token information.
|
|
if (res.status != 200) {
|
|
console.error("Unexpected result from discord:", this.authToken, res.data);
|
|
return Promise.reject({
|
|
reason: "Invalid authorization code. Please logout and try again.",
|
|
status: 400,
|
|
});
|
|
}
|
|
|
|
let discordCache = new DiscordCache(
|
|
this.id,
|
|
res.data.id,
|
|
res.data.username,
|
|
res.data.discriminator,
|
|
res.data.avatar
|
|
);
|
|
discordCache.save();
|
|
return discordCache;
|
|
}
|
|
}
|