-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthServiceImpl.ts
81 lines (69 loc) · 2.55 KB
/
AuthServiceImpl.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
// SPDX-FileCopyrightText: 2023-2025 Open Pioneer project (https://github.com/open-pioneer)
// SPDX-License-Identifier: Apache-2.0
import {
ManualPromise,
Resource,
createAbortError,
createManualPromise,
destroyResource,
createLogger
} from "@open-pioneer/core";
import type { AuthPlugin, AuthService, AuthState, LoginBehavior, SessionInfo } from "./api";
import type { Service, ServiceOptions } from "@open-pioneer/runtime";
import { syncWatch } from "@conterra/reactivity-core";
const LOG = createLogger("authentication:AuthService");
export class AuthServiceImpl implements AuthService, Service {
#plugin: AuthPlugin;
#whenUserInfo: ManualPromise<SessionInfo | undefined> | undefined;
#watchPluginStateHandle: Resource | undefined;
constructor(serviceOptions: ServiceOptions<{ plugin: AuthPlugin }>) {
this.#plugin = serviceOptions.references.plugin;
this.#watchPluginStateHandle = syncWatch(
() => [this.#plugin.getAuthState()],
([state]) => {
this.#onPluginStateChanged(state);
},
{
immediate: false
}
);
LOG.debug(
`Constructed with initial auth state '${this.getAuthState().kind}'`,
this.getAuthState()
);
}
destroy(): void {
this.#whenUserInfo?.reject(createAbortError());
this.#whenUserInfo = undefined;
this.#watchPluginStateHandle = destroyResource(this.#watchPluginStateHandle);
}
getAuthState(): AuthState {
return this.#plugin.getAuthState();
}
getSessionInfo(): Promise<SessionInfo | undefined> {
if (this.getAuthState().kind !== "pending") {
return Promise.resolve(getSessionInfo(this.getAuthState()));
}
if (!this.#whenUserInfo) {
this.#whenUserInfo = createManualPromise();
}
return this.#whenUserInfo.promise;
}
getLoginBehavior(): LoginBehavior {
return this.#plugin.getLoginBehavior();
}
logout(): void {
LOG.debug("Triggering logout");
this.#plugin.logout();
}
#onPluginStateChanged(newState: AuthState) {
if (newState.kind !== "pending" && this.#whenUserInfo) {
this.#whenUserInfo.resolve(getSessionInfo(newState));
this.#whenUserInfo = undefined;
}
LOG.debug(`Auth state changed to '${newState.kind}'`, newState);
}
}
function getSessionInfo(state: AuthState): SessionInfo | undefined {
return state.kind === "authenticated" ? state.sessionInfo : undefined;
}