/
communicationUserCredential.ts
76 lines (68 loc) · 2.66 KB
/
communicationUserCredential.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AbortSignalLike, AccessToken } from "@azure/core-http";
import { parseToken } from "./tokenParser";
import { StaticTokenCredential } from "./staticTokenCredential";
import { AutoRefreshUserCredential, RefreshOptions } from "./autoRefreshUserCredential";
export type UserCredential = Pick<AzureCommunicationUserCredential, "getToken" | "dispose">;
/**
* The Azure Communication Services User token credential.
*/
export interface CommunicationUserCredential {
/**
* Gets an `AccessToken` for the user. Throws if already disposed.
* @param abortSignal An implementation of `AbortSignalLike` to cancel the operation.
*/
getToken(abortSignal?: AbortSignalLike): Promise<AccessToken>;
/**
* Disposes the CommunicationUserCredential and cancels any internal auto-refresh operation.
*/
dispose(): void;
}
/**
* The CommunicationUserCredential implementation with support for proactive token refresh.
*/
export class AzureCommunicationUserCredential implements CommunicationUserCredential {
private readonly userCredential: UserCredential;
private disposed = false;
/**
* Creates an instance of CommunicationUserCredential with a static token and no proactive refreshing.
* @param token A user access token issued by Communication Services.
*/
constructor(token: string);
/**
* Creates an instance of CommunicationUserCredential with a lambda to get a token and options
* to configure proactive refreshing.
* @param refreshOptions Options to configure refresh and opt-in to proactive refreshing.
*/
constructor(refreshOptions: RefreshOptions);
constructor(tokenOrRefreshOptions: string | RefreshOptions) {
if (typeof tokenOrRefreshOptions === "string") {
this.userCredential = new StaticTokenCredential(parseToken(tokenOrRefreshOptions));
} else {
this.userCredential = new AutoRefreshUserCredential(tokenOrRefreshOptions);
}
}
/**
* Gets an `AccessToken` for the user. Throws if already disposed.
* @param abortSignal An implementation of `AbortSignalLike` to cancel the operation.
*/
public async getToken(abortSignal?: AbortSignalLike): Promise<AccessToken> {
this.throwIfDisposed();
const token = await this.userCredential.getToken(abortSignal);
this.throwIfDisposed();
return token;
}
/**
* Disposes the CommunicationUserCredential and cancels any internal auto-refresh operation.
*/
public dispose(): void {
this.disposed = true;
this.userCredential.dispose();
}
private throwIfDisposed(): void {
if (this.disposed) {
throw new Error("User credential is disposed");
}
}
}