summary refs log tree commit diff
path: root/src/util/connections/Connection.ts
blob: 8b60b0d2be2f4d0ba0201cfc7a83079cc3698618 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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;
	}
}