This repository has been archived by the owner on Jun 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
accessToken.ts
81 lines (72 loc) · 1.84 KB
/
accessToken.ts
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
import type { Auth } from "../client";
import type { Data } from "./types";
import type { Credentials } from "./api/creds";
import { post } from "./api/creds";
import { camelCaseKeys } from "./util";
export interface Token {
access: string;
expiration: number;
refresh?: string;
}
export interface TokenResponse {
accessToken: string;
tokenType: string;
expiresIn: number;
refreshToken?: string;
scope: string;
}
function rawToToken(raw: Data): Token {
const tkns: TokenResponse = camelCaseKeys(raw);
return {
access: tkns.accessToken,
expiration: Date.now() + tkns.expiresIn * 1000,
refresh: tkns.refreshToken,
};
}
export async function updateAccessToken(
userAgent: string,
token: Token | null,
creds: Credentials,
auth?: Auth
): Promise<Token> {
const expiration = token?.expiration ?? 0;
if (expiration > Date.now()) return token!;
// Token is expired or missing, time to (re)generate!
let grant: Data = {};
if (auth) {
if (token?.refresh != null) {
grant.grant_type = "refresh_token";
grant.refresh_token = token.refresh;
} else if ("refreshToken" in auth) {
grant.grant_type = "refresh_token";
grant.refresh_token = auth.refreshToken;
} else {
grant.grant_type = "password";
grant.username = auth.username;
grant.password = auth.password;
}
} else {
grant.grant_type = "client_credentials";
}
const raw: Data = await post(
creds,
userAgent,
"api/v1/access_token",
grant,
{}
);
return rawToToken(raw);
}
export async function tokenFromCode(
code: string,
creds: Credentials,
userAgent: string,
redirectUri: string
): Promise<Token> {
const raw: Data = await post(creds, userAgent, "api/v1/access_token", {
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
});
return rawToToken(raw);
}