This repository has been archived on 2026-02-28. You can view files and clone it, but cannot push or open issues or pull requests.
Puyodead1 0db1fa5f0b
Refreshable connections, refactoring, access-token endpoint
- Aded /users/@me/connections/:connection_name/:connection_id/access-token
- Replaced `access_token` property on ConnectedAccount with `token_data` object for refreshing tokens
- Made a common interface for connection things like ComonOAuthTokenResponse
- Added `RefreshableConnection` class
- Added token refresh to Spotify connection (disabled)
2023-03-18 19:27:39 -04:00

91 lines
2.2 KiB
TypeScript

import crypto from "crypto";
import { ConnectedAccount } from "../entities";
import { ConnectedAccountSchema, ConnectionCallbackSchema } from "../schemas";
import { DiscordApiErrors } from "../util";
/**
* A connection that can be used to connect to an external service.
*/
export default abstract class Connection {
id: string;
settings: { enabled: boolean };
states: Map<string, string> = new Map();
abstract init(): void;
/**
* Generates an authorization url for the connection.
* @param args
*/
abstract getAuthorizationUrl(userId: string): string;
/**
* Processes the callback
* @param args Callback arguments
*/
abstract handleCallback(
params: ConnectionCallbackSchema,
): Promise<ConnectedAccount | null>;
/**
* Gets a user id from state
* @param state the state to get the user id from
* @returns the user id associated with the state
*/
getUserId(state: string): string {
if (!this.states.has(state)) throw DiscordApiErrors.INVALID_OAUTH_STATE;
return this.states.get(state) as string;
}
/**
* Generates a state
* @param user_id The user id to generate a state for.
* @returns a new state
*/
createState(userId: string): string {
const state = crypto.randomBytes(16).toString("hex");
this.states.set(state, userId);
return state;
}
/**
* Takes a state and checks if it is valid, and deletes it.
* @param state The state to check.
*/
validateState(state: string): void {
if (!this.states.has(state)) throw DiscordApiErrors.INVALID_OAUTH_STATE;
this.states.delete(state);
}
/**
* Creates a Connected Account in the database.
* @param data connected account data
* @returns the new connected account
*/
async createConnection(
data: ConnectedAccountSchema,
): Promise<ConnectedAccount> {
const ca = ConnectedAccount.create({ ...data });
await ca.save();
return ca;
}
/**
* Checks if a user has an exist connected account for the given extenal id.
* @param userId the user id
* @param externalId the connection id to find
* @returns
*/
async hasConnection(userId: string, externalId: string): Promise<boolean> {
const existing = await ConnectedAccount.findOne({
where: {
user_id: userId,
external_id: externalId,
},
});
return !!existing;
}
}