granite.web.authentication 0.0.0-stage → 1.0.0-release.1795807978031

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/Authentication/AuthenticationContext.d.ts +16 -0
  2. package/Authentication/AuthenticationContext.js +12 -0
  3. package/Authentication/AuthenticationManager.d.ts +32 -0
  4. package/Authentication/AuthenticationManager.js +169 -0
  5. package/Authentication/AuthenticationProvider.d.ts +7 -0
  6. package/Authentication/AuthenticationProvider.js +28 -0
  7. package/Authentication/Authorities.d.ts +3 -0
  8. package/Authentication/Authorities.js +10 -0
  9. package/Authentication/FrontEndSessionService.d.ts +16 -0
  10. package/Authentication/FrontEndSessionService.js +110 -0
  11. package/Authentication/IAuthenticationState.d.ts +12 -0
  12. package/Authentication/IAuthenticationState.js +6 -0
  13. package/Authentication/ISessionService.d.ts +28 -0
  14. package/Authentication/ISessionService.js +5 -0
  15. package/Authentication/RequireAuthentication.d.ts +6 -0
  16. package/Authentication/RequireAuthentication.js +13 -0
  17. package/Authentication/RuntimeConfig.d.ts +16 -0
  18. package/Authentication/RuntimeConfig.js +31 -0
  19. package/Authentication/createAuthentication.d.ts +18 -0
  20. package/Authentication/createAuthentication.js +22 -0
  21. package/Authentication/index.d.ts +17 -0
  22. package/Authentication/index.js +9 -0
  23. package/Http/Cookies.d.ts +1 -0
  24. package/Http/Cookies.js +12 -0
  25. package/Http/CsrfFetch.d.ts +10 -0
  26. package/Http/CsrfFetch.js +41 -0
  27. package/Http/SessionFetch.d.ts +10 -0
  28. package/Http/SessionFetch.js +23 -0
  29. package/Http/index.d.ts +5 -0
  30. package/Http/index.js +3 -0
  31. package/Login/ChangePasswordDialog.d.ts +6 -0
  32. package/Login/ChangePasswordDialog.js +54 -0
  33. package/Login/LoginCallbackView.d.ts +2 -0
  34. package/Login/LoginCallbackView.js +31 -0
  35. package/Login/LoginForm.d.ts +6 -0
  36. package/Login/LoginForm.js +50 -0
  37. package/Login/LoginView.d.ts +2 -0
  38. package/Login/LoginView.js +13 -0
  39. package/Login/ReauthenticationDialog.d.ts +2 -0
  40. package/Login/ReauthenticationDialog.js +9 -0
  41. package/Login/UserMenu.d.ts +13 -0
  42. package/Login/UserMenu.js +37 -0
  43. package/Login/index.d.ts +9 -0
  44. package/Login/index.js +6 -0
  45. package/index.d.ts +2 -0
  46. package/index.js +2 -0
  47. package/package.json +18 -4
  48. package/README.md +0 -3
@@ -0,0 +1,16 @@
1
+ import type { FetchFunction } from "../Http/CsrfFetch";
2
+ import type { IAuthenticationState } from "./IAuthenticationState";
3
+ import type { IChangePasswordResult, ILoginMethods } from "./ISessionService";
4
+ export interface IAuthenticationContext {
5
+ state: IAuthenticationState;
6
+ login: (userName: string, password: string) => Promise<void>;
7
+ startOktaLogin: (returnTo: string) => Promise<void>;
8
+ completeOktaLogin: (code: string, state: string) => Promise<string>;
9
+ logout: () => Promise<boolean>;
10
+ getLoginMethods: () => Promise<ILoginMethods>;
11
+ changePassword: (currentPassword: string, newPassword: string) => Promise<IChangePasswordResult>;
12
+ cancelReauthentication: () => void;
13
+ createFrontEndClient: <C>(create: (serviceUrl: string, fetchFunction: FetchFunction) => C, service: string) => C;
14
+ }
15
+ export declare const AuthenticationContext: import("react").Context<IAuthenticationContext | null>;
16
+ export declare function useAuthentication(): IAuthenticationContext;
@@ -0,0 +1,12 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ import { createContext, useContext } from "react";
5
+ export const AuthenticationContext = createContext(null);
6
+ export function useAuthentication() {
7
+ const context = useContext(AuthenticationContext);
8
+ if (!context)
9
+ throw new Error("useAuthentication must be used within an AuthenticationProvider");
10
+ return context;
11
+ }
12
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,32 @@
1
+ import type { IAuthenticationState } from "./IAuthenticationState";
2
+ import type { IChangePasswordResult, ILoginMethods, ISessionService } from "./ISessionService";
3
+ export type AuthenticationListener = (state: IAuthenticationState) => void;
4
+ export interface INavigator {
5
+ assign(url: string): void;
6
+ }
7
+ export declare const browserNavigator: INavigator;
8
+ export declare class AuthenticationManager {
9
+ private readonly service;
10
+ private readonly navigator;
11
+ private readonly listeners;
12
+ private state;
13
+ private prompt;
14
+ constructor(service: ISessionService, navigator?: INavigator);
15
+ getState(): IAuthenticationState;
16
+ subscribe(listener: AuthenticationListener): () => void;
17
+ getLoginMethods(): Promise<ILoginMethods>;
18
+ changePassword(currentPassword: string, newPassword: string): Promise<IChangePasswordResult>;
19
+ restore(): Promise<void>;
20
+ login(userName: string, password: string): Promise<void>;
21
+ startOktaLogin(returnTo: string): Promise<void>;
22
+ completeOktaLogin(code: string, state: string): Promise<string>;
23
+ logout(): Promise<boolean>;
24
+ handleUnauthorized(): Promise<boolean>;
25
+ cancelReauthentication(): void;
26
+ private apply;
27
+ private accept;
28
+ private requireAuthenticated;
29
+ private settle;
30
+ private recordError;
31
+ private setState;
32
+ }
@@ -0,0 +1,169 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ import { ANONYMOUS, RESTORING } from "./IAuthenticationState";
5
+ import { UNAUTHENTICATED } from "./FrontEndSessionService";
6
+ export const browserNavigator = {
7
+ assign: (url) => window.location.assign(url),
8
+ };
9
+ const LOGIN_FAILED = "Login failed";
10
+ const LOGOUT_FAILED = "Logout failed";
11
+ export class AuthenticationManager {
12
+ service;
13
+ navigator;
14
+ listeners;
15
+ state;
16
+ prompt;
17
+ constructor(service, navigator = browserNavigator) {
18
+ this.service = service;
19
+ this.navigator = navigator;
20
+ this.listeners = new Set();
21
+ this.state = RESTORING;
22
+ this.prompt = undefined;
23
+ }
24
+ getState() {
25
+ return this.state;
26
+ }
27
+ subscribe(listener) {
28
+ this.listeners.add(listener);
29
+ return () => { this.listeners.delete(listener); };
30
+ }
31
+ getLoginMethods() {
32
+ return this.service.getLoginMethods();
33
+ }
34
+ changePassword(currentPassword, newPassword) {
35
+ return this.service.changePassword(currentPassword, newPassword);
36
+ }
37
+ async restore() {
38
+ try {
39
+ this.apply(await this.service.getCurrent());
40
+ }
41
+ catch (error) {
42
+ this.setState({ ...ANONYMOUS, error: messageOf(error) });
43
+ }
44
+ }
45
+ async login(userName, password) {
46
+ let status;
47
+ try {
48
+ status = await this.service.login(userName, password);
49
+ }
50
+ catch (error) {
51
+ this.recordError(messageOf(error));
52
+ throw error;
53
+ }
54
+ this.requireAuthenticated(status);
55
+ this.accept(status);
56
+ }
57
+ async startOktaLogin(returnTo) {
58
+ let url;
59
+ try {
60
+ url = await this.service.startOktaLogin(localPath(returnTo));
61
+ }
62
+ catch (error) {
63
+ this.recordError(messageOf(error));
64
+ throw error;
65
+ }
66
+ if (!url) {
67
+ this.recordError(LOGIN_FAILED);
68
+ throw new Error(LOGIN_FAILED);
69
+ }
70
+ this.navigator.assign(url);
71
+ }
72
+ async completeOktaLogin(code, state) {
73
+ let status;
74
+ try {
75
+ status = await this.service.completeOktaLogin(code, state);
76
+ }
77
+ catch (error) {
78
+ this.recordError(messageOf(error));
79
+ throw error;
80
+ }
81
+ this.requireAuthenticated(status);
82
+ this.accept(status);
83
+ return localPath(status.returnTo);
84
+ }
85
+ async logout() {
86
+ try {
87
+ const result = await this.service.logout();
88
+ if (!result.loggedOut) {
89
+ this.recordError(LOGOUT_FAILED);
90
+ return false;
91
+ }
92
+ this.settle(false);
93
+ this.setState(ANONYMOUS);
94
+ return true;
95
+ }
96
+ catch (error) {
97
+ this.recordError(messageOf(error));
98
+ return false;
99
+ }
100
+ }
101
+ async handleUnauthorized() {
102
+ if (this.prompt)
103
+ return this.prompt.promise;
104
+ const prompt = newPrompt();
105
+ let current;
106
+ this.prompt = prompt;
107
+ try {
108
+ current = await this.service.getCurrent();
109
+ }
110
+ catch {
111
+ current = UNAUTHENTICATED;
112
+ }
113
+ if (this.prompt !== prompt)
114
+ return prompt.promise;
115
+ if (current.authenticated)
116
+ this.accept(current);
117
+ else if (this.state.status === "authenticated" || this.state.status === "reauthenticating")
118
+ this.setState({ ...this.state, status: "reauthenticating", error: undefined });
119
+ else
120
+ this.settle(false);
121
+ return prompt.promise;
122
+ }
123
+ cancelReauthentication() {
124
+ if (this.state.status !== "reauthenticating")
125
+ return;
126
+ this.settle(false);
127
+ this.setState(ANONYMOUS);
128
+ }
129
+ apply(status) {
130
+ if (status.authenticated)
131
+ this.accept(status);
132
+ else
133
+ this.setState(ANONYMOUS);
134
+ }
135
+ accept(status) {
136
+ this.setState({ status: "authenticated", userName: status.userName, authorities: status.authorities, passwordEnabled: status.passwordEnabled === true, passwordSet: status.passwordSet === true });
137
+ this.settle(true);
138
+ }
139
+ requireAuthenticated(status) {
140
+ if (status.authenticated)
141
+ return;
142
+ this.recordError(LOGIN_FAILED);
143
+ throw new Error(LOGIN_FAILED);
144
+ }
145
+ settle(retry) {
146
+ const prompt = this.prompt;
147
+ this.prompt = undefined;
148
+ prompt?.resolve(retry);
149
+ }
150
+ recordError(error) {
151
+ this.setState({ ...this.state, error });
152
+ }
153
+ setState(state) {
154
+ this.state = state;
155
+ this.listeners.forEach((listener) => listener(state));
156
+ }
157
+ }
158
+ function newPrompt() {
159
+ let resolve = () => undefined;
160
+ const promise = new Promise(done => { resolve = done; });
161
+ return { promise, resolve };
162
+ }
163
+ function localPath(value) {
164
+ return value && value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\") ? value : "/";
165
+ }
166
+ function messageOf(error) {
167
+ return error instanceof Error ? error.message : String(error);
168
+ }
169
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,7 @@
1
+ import type { ReactElement, ReactNode } from "react";
2
+ import type { IAuthentication } from "./createAuthentication";
3
+ export interface IAuthenticationProviderProps {
4
+ children: ReactNode;
5
+ authentication?: IAuthentication;
6
+ }
7
+ export declare function AuthenticationProvider({ children, authentication }: IAuthenticationProviderProps): ReactElement;
@@ -0,0 +1,28 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ //////////////////////////////////////////////////////////////////////////////
3
+ // Granite.Web.Authentication
4
+ //////////////////////////////////////////////////////////////////////////////
5
+ import { useEffect, useMemo, useSyncExternalStore } from "react";
6
+ import { AuthenticationContext } from "./AuthenticationContext";
7
+ import { createAuthentication } from "./createAuthentication";
8
+ import { ReauthenticationDialog } from "../Login/ReauthenticationDialog";
9
+ export function AuthenticationProvider({ children, authentication }) {
10
+ const { manager, createFrontEndClient } = useMemo(() => authentication ?? createAuthentication(), [authentication]);
11
+ const state = useSyncExternalStore((listener) => manager.subscribe(listener), () => manager.getState());
12
+ useEffect(() => {
13
+ if (manager.getState().status === "restoring")
14
+ void manager.restore();
15
+ }, [manager]);
16
+ const actions = useMemo(() => ({
17
+ login: (userName, password) => manager.login(userName, password),
18
+ startOktaLogin: (returnTo) => manager.startOktaLogin(returnTo),
19
+ completeOktaLogin: (code, oktaState) => manager.completeOktaLogin(code, oktaState),
20
+ logout: () => manager.logout(),
21
+ getLoginMethods: () => manager.getLoginMethods(),
22
+ changePassword: (currentPassword, newPassword) => manager.changePassword(currentPassword, newPassword),
23
+ cancelReauthentication: () => manager.cancelReauthentication(),
24
+ createFrontEndClient,
25
+ }), [manager, createFrontEndClient]);
26
+ const value = useMemo(() => ({ state, ...actions }), [state, actions]);
27
+ return (_jsxs(AuthenticationContext.Provider, { value: value, children: [children, state.status === "reauthenticating" && _jsx(ReauthenticationDialog, {})] }));
28
+ }
@@ -0,0 +1,3 @@
1
+ import type { IAuthenticationState } from "./IAuthenticationState";
2
+ export declare function hasAuthority(state: IAuthenticationState, authority: string): boolean;
3
+ export declare function canEdit(state: IAuthenticationState): boolean;
@@ -0,0 +1,10 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ export function hasAuthority(state, authority) {
5
+ return (state.status === "authenticated" || state.status === "reauthenticating") && state.authorities.includes(authority);
6
+ }
7
+ export function canEdit(state) {
8
+ return hasAuthority(state, "ROLE_ADMIN");
9
+ }
10
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,16 @@
1
+ import type { IGraniteFrontEndControllerServiceClient } from "granite.frontendcontroller.client/RequestReply";
2
+ import type { IChangePasswordResult, ILoginMethods, ILogoutResult, ISessionService, ISessionStatus } from "./ISessionService";
3
+ export declare const UNAUTHENTICATED: ISessionStatus;
4
+ export declare class FrontEndSessionService implements ISessionService {
5
+ private readonly createClient;
6
+ constructor(createClient: () => IGraniteFrontEndControllerServiceClient);
7
+ getLoginMethods(): Promise<ILoginMethods>;
8
+ login(userName: string, password: string): Promise<ISessionStatus>;
9
+ startOktaLogin(returnTo: string): Promise<string | undefined>;
10
+ completeOktaLogin(code: string, state: string): Promise<ISessionStatus>;
11
+ getCurrent(): Promise<ISessionStatus>;
12
+ logout(): Promise<ILogoutResult>;
13
+ changePassword(currentPassword: string, newPassword: string): Promise<IChangePasswordResult>;
14
+ private read;
15
+ private send;
16
+ }
@@ -0,0 +1,110 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ import { GetOutputRequestBuilder, HandleInputRequestBuilder } from "strata.frontendcontroller.service/RequestReply";
5
+ import { ServiceError } from "strata.client.core/Service";
6
+ import { CompletionError } from "strata.foundation.core/Concurrent";
7
+ import { APPLICATION } from "./RuntimeConfig";
8
+ const NEW_SOURCE = "Session.New";
9
+ const CURRENT_SOURCE = "Session.Current";
10
+ const LOGIN_DESTINATION = "LoginView";
11
+ const SESSION_DESTINATION = "SessionView";
12
+ const AUTHENTICATED = "AUTHENTICATED";
13
+ const CHANGED = "CHANGED";
14
+ const CHANGE_FAILED = "Unable to change password";
15
+ export const UNAUTHENTICATED = { authenticated: false, authorities: [] };
16
+ export class FrontEndSessionService {
17
+ createClient;
18
+ constructor(createClient) {
19
+ this.createClient = createClient;
20
+ }
21
+ async getLoginMethods() {
22
+ const output = await this.read(NEW_SOURCE, LOGIN_DESTINATION);
23
+ return { passwordEnabled: output.passwordEnabled === true, oktaEnabled: output.oktaEnabled === true };
24
+ }
25
+ async login(userName, password) {
26
+ return toStatus(await this.send(NEW_SOURCE, "Login", LOGIN_DESTINATION, { userName, password, application: APPLICATION }));
27
+ }
28
+ async startOktaLogin(returnTo) {
29
+ const output = await this.send(NEW_SOURCE, "StartOktaLogin", LOGIN_DESTINATION, { returnTo, application: APPLICATION });
30
+ return typeof output.redirectUrl === "string" && output.redirectUrl.length > 0 ? output.redirectUrl : undefined;
31
+ }
32
+ async completeOktaLogin(code, state) {
33
+ return toStatus(await this.send(NEW_SOURCE, "CompleteOktaLogin", LOGIN_DESTINATION, { code, state }));
34
+ }
35
+ async getCurrent() {
36
+ try {
37
+ return toStatus(await this.read(CURRENT_SOURCE, SESSION_DESTINATION));
38
+ }
39
+ catch (error) {
40
+ if (isUnauthorized(error))
41
+ return UNAUTHENTICATED;
42
+ throw error;
43
+ }
44
+ }
45
+ async logout() {
46
+ try {
47
+ const output = await this.send(CURRENT_SOURCE, "Logout", LOGIN_DESTINATION, {});
48
+ return { loggedOut: output.loggedOut === true };
49
+ }
50
+ catch (error) {
51
+ if (isUnauthorized(error))
52
+ return { loggedOut: true };
53
+ throw error;
54
+ }
55
+ }
56
+ async changePassword(currentPassword, newPassword) {
57
+ try {
58
+ const output = await this.send(CURRENT_SOURCE, "ChangePassword", "ChangePasswordView", { currentPassword, newPassword });
59
+ if (output.status === CHANGED)
60
+ return { success: true };
61
+ return { success: false, message: output.failureMessages?.[0] || CHANGE_FAILED };
62
+ }
63
+ catch {
64
+ return { success: false, message: CHANGE_FAILED };
65
+ }
66
+ }
67
+ async read(source, destination) {
68
+ const client = this.createClient();
69
+ try {
70
+ const reply = await client.getSessionOutput(GetOutputRequestBuilder.newBuilder().setSource(source).setDestination(destination).build());
71
+ return unwrap(reply);
72
+ }
73
+ finally {
74
+ client.close();
75
+ }
76
+ }
77
+ async send(source, command, destination, fields) {
78
+ const client = this.createClient();
79
+ const input = { userId: null, source, command, destination, ...fields };
80
+ try {
81
+ const reply = await client.handleSessionInput(HandleInputRequestBuilder.newBuilder().setInput(input).build());
82
+ return unwrap(reply);
83
+ }
84
+ finally {
85
+ client.close();
86
+ }
87
+ }
88
+ }
89
+ function unwrap(reply) {
90
+ if (reply.success === false)
91
+ throw new Error(reply.failureMessage || "Request failed");
92
+ if (!reply.output)
93
+ throw new Error("Empty response");
94
+ return reply.output;
95
+ }
96
+ function toStatus(output) {
97
+ return {
98
+ authenticated: output.status === AUTHENTICATED,
99
+ userName: output.userName ?? undefined,
100
+ authorities: output.authorities ?? [],
101
+ returnTo: output.returnTo ?? undefined,
102
+ passwordEnabled: output.passwordEnabled === true,
103
+ passwordSet: output.passwordSet === true,
104
+ };
105
+ }
106
+ function isUnauthorized(error) {
107
+ const cause = error instanceof CompletionError ? error.getCause() : error;
108
+ return cause instanceof ServiceError && cause.getStatus() === 401;
109
+ }
110
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,12 @@
1
+ export type AuthenticationStatus = "restoring" | "anonymous" | "authenticated" | "reauthenticating";
2
+ export interface IAuthenticationState {
3
+ status: AuthenticationStatus;
4
+ userId?: number;
5
+ userName?: string;
6
+ authorities: Array<string>;
7
+ passwordEnabled: boolean;
8
+ passwordSet: boolean;
9
+ error?: string;
10
+ }
11
+ export declare const RESTORING: IAuthenticationState;
12
+ export declare const ANONYMOUS: IAuthenticationState;
@@ -0,0 +1,6 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ export const RESTORING = { status: "restoring", authorities: [], passwordEnabled: false, passwordSet: false };
5
+ export const ANONYMOUS = { status: "anonymous", authorities: [], passwordEnabled: false, passwordSet: false };
6
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,28 @@
1
+ export interface ILoginMethods {
2
+ passwordEnabled: boolean;
3
+ oktaEnabled: boolean;
4
+ }
5
+ export interface ISessionStatus {
6
+ authenticated: boolean;
7
+ userName?: string;
8
+ authorities: Array<string>;
9
+ returnTo?: string;
10
+ passwordEnabled?: boolean;
11
+ passwordSet?: boolean;
12
+ }
13
+ export interface ILogoutResult {
14
+ loggedOut: boolean;
15
+ }
16
+ export interface IChangePasswordResult {
17
+ success: boolean;
18
+ message?: string;
19
+ }
20
+ export interface ISessionService {
21
+ getLoginMethods(): Promise<ILoginMethods>;
22
+ login(userName: string, password: string): Promise<ISessionStatus>;
23
+ startOktaLogin(returnTo: string): Promise<string | undefined>;
24
+ completeOktaLogin(code: string, state: string): Promise<ISessionStatus>;
25
+ getCurrent(): Promise<ISessionStatus>;
26
+ logout(): Promise<ILogoutResult>;
27
+ changePassword(currentPassword: string, newPassword: string): Promise<IChangePasswordResult>;
28
+ }
@@ -0,0 +1,5 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ export {};
5
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,6 @@
1
+ import type { ReactElement, ReactNode } from "react";
2
+ export interface IRequireAuthenticationProps {
3
+ children: ReactNode;
4
+ loginPath?: string;
5
+ }
6
+ export declare function RequireAuthentication({ children, loginPath }: IRequireAuthenticationProps): ReactElement;
@@ -0,0 +1,13 @@
1
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Navigate, useLocation } from "react-router-dom";
3
+ import { Center, Loader } from "@mantine/core";
4
+ import { useAuthentication } from "./AuthenticationContext";
5
+ export function RequireAuthentication({ children, loginPath = "/login" }) {
6
+ const { state } = useAuthentication();
7
+ const location = useLocation();
8
+ if (state.status === "restoring")
9
+ return _jsx(Center, { p: "xl", children: _jsx(Loader, { "aria-label": "Restoring session" }) });
10
+ if (state.status === "anonymous")
11
+ return _jsx(Navigate, { to: loginPath, replace: true, state: { from: location.pathname + location.search } });
12
+ return _jsx(_Fragment, { children: children });
13
+ }
@@ -0,0 +1,16 @@
1
+ export interface IRuntimeConfig {
2
+ apiBaseUrl: string;
3
+ cookiePrefix: string;
4
+ application: string;
5
+ }
6
+ declare global {
7
+ interface Window {
8
+ __GRANITE_CONFIG__?: Partial<IRuntimeConfig>;
9
+ }
10
+ }
11
+ export declare const DEFAULT_COOKIE_PREFIX: string;
12
+ export declare const DEFAULT_APPLICATION: string;
13
+ export declare function normalizeCookiePrefix(prefix: string | undefined): string;
14
+ export declare function normalizeApplication(application: string | undefined): string;
15
+ export declare function getRuntimeConfig(): IRuntimeConfig;
16
+ export declare const APPLICATION: string;
@@ -0,0 +1,31 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ export const DEFAULT_COOKIE_PREFIX = "GRANITE";
5
+ export const DEFAULT_APPLICATION = "granite";
6
+ const COOKIE_PREFIX_PATTERN = /^[A-Z0-9_]+$/;
7
+ const warnedPrefixes = new Set();
8
+ export function normalizeCookiePrefix(prefix) {
9
+ const trimmed = (prefix ?? "").trim();
10
+ if (COOKIE_PREFIX_PATTERN.test(trimmed))
11
+ return trimmed;
12
+ if (trimmed !== "" && !warnedPrefixes.has(trimmed)) {
13
+ warnedPrefixes.add(trimmed);
14
+ console.warn("cookiePrefix \"" + trimmed + "\" is not valid (A-Z, 0-9, _); using " + DEFAULT_COOKIE_PREFIX);
15
+ }
16
+ return DEFAULT_COOKIE_PREFIX;
17
+ }
18
+ export function normalizeApplication(application) {
19
+ const trimmed = (application ?? "").trim();
20
+ return trimmed === "" ? DEFAULT_APPLICATION : trimmed;
21
+ }
22
+ export function getRuntimeConfig() {
23
+ const config = window.__GRANITE_CONFIG__ ?? {};
24
+ return {
25
+ apiBaseUrl: (config.apiBaseUrl ?? "").replace(/\/+$/, ""),
26
+ cookiePrefix: normalizeCookiePrefix(config.cookiePrefix),
27
+ application: normalizeApplication(config.application),
28
+ };
29
+ }
30
+ export const APPLICATION = getRuntimeConfig().application;
31
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,18 @@
1
+ import type { FetchFunction } from "../Http/CsrfFetch";
2
+ import { AuthenticationManager } from "./AuthenticationManager";
3
+ import type { INavigator } from "./AuthenticationManager";
4
+ import type { ISessionService } from "./ISessionService";
5
+ export declare const SESSION_SERVICE: string;
6
+ export interface IAuthentication {
7
+ manager: AuthenticationManager;
8
+ createFrontEndClient: <C>(create: (serviceUrl: string, fetchFunction: FetchFunction) => C, service: string) => C;
9
+ }
10
+ export interface IAuthenticationOptions {
11
+ apiBaseUrl?: string;
12
+ cookiePrefix?: string;
13
+ fetchFunction?: FetchFunction;
14
+ cookieReader?: (name: string) => string | undefined;
15
+ navigator?: INavigator;
16
+ service?: ISessionService;
17
+ }
18
+ export declare function createAuthentication(options?: IAuthenticationOptions): IAuthentication;
@@ -0,0 +1,22 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ import { GraniteFrontEndControllerServiceClient } from "granite.frontendcontroller.client/RequestReply";
5
+ import { CsrfFetch, csrfCookieName } from "../Http/CsrfFetch";
6
+ import { SessionFetch } from "../Http/SessionFetch";
7
+ import { AuthenticationManager } from "./AuthenticationManager";
8
+ import { FrontEndSessionService } from "./FrontEndSessionService";
9
+ import { getRuntimeConfig, normalizeCookiePrefix } from "./RuntimeConfig";
10
+ export const SESSION_SERVICE = "frontendcontroller-user-service";
11
+ export function createAuthentication(options = {}) {
12
+ const baseUrl = options.apiBaseUrl ?? getRuntimeConfig().apiBaseUrl;
13
+ const prefix = normalizeCookiePrefix(options.cookiePrefix ?? getRuntimeConfig().cookiePrefix);
14
+ const csrf = new CsrfFetch(options.fetchFunction, options.cookieReader, csrfCookieName(prefix));
15
+ const session = new SessionFetch(csrf.fetch);
16
+ const clientOver = (fetchFunction, create, service) => create(baseUrl + "/" + service, fetchFunction);
17
+ const manager = new AuthenticationManager(options.service ??
18
+ new FrontEndSessionService(() => clientOver(csrf.fetch, (url, fetchFunction) => new GraniteFrontEndControllerServiceClient(url, fetchFunction), SESSION_SERVICE)), options.navigator);
19
+ session.setUnauthorizedHandler(() => manager.handleUnauthorized());
20
+ return { manager, createFrontEndClient: (create, service) => clientOver(session.fetch, create, service) };
21
+ }
22
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,17 @@
1
+ export type { AuthenticationStatus, IAuthenticationState } from "./IAuthenticationState";
2
+ export { ANONYMOUS, RESTORING } from "./IAuthenticationState";
3
+ export { canEdit, hasAuthority } from "./Authorities";
4
+ export type { IRuntimeConfig } from "./RuntimeConfig";
5
+ export { APPLICATION, DEFAULT_APPLICATION, DEFAULT_COOKIE_PREFIX, getRuntimeConfig, normalizeApplication, normalizeCookiePrefix } from "./RuntimeConfig";
6
+ export type { IChangePasswordResult, ILoginMethods, ILogoutResult, ISessionService, ISessionStatus } from "./ISessionService";
7
+ export { FrontEndSessionService } from "./FrontEndSessionService";
8
+ export type { AuthenticationListener, INavigator } from "./AuthenticationManager";
9
+ export { AuthenticationManager, browserNavigator } from "./AuthenticationManager";
10
+ export type { IAuthentication, IAuthenticationOptions } from "./createAuthentication";
11
+ export { createAuthentication } from "./createAuthentication";
12
+ export type { IAuthenticationContext } from "./AuthenticationContext";
13
+ export { AuthenticationContext, useAuthentication } from "./AuthenticationContext";
14
+ export type { IAuthenticationProviderProps } from "./AuthenticationProvider";
15
+ export { AuthenticationProvider } from "./AuthenticationProvider";
16
+ export type { IRequireAuthenticationProps } from "./RequireAuthentication";
17
+ export { RequireAuthentication } from "./RequireAuthentication";
@@ -0,0 +1,9 @@
1
+ export { ANONYMOUS, RESTORING } from "./IAuthenticationState";
2
+ export { canEdit, hasAuthority } from "./Authorities";
3
+ export { APPLICATION, DEFAULT_APPLICATION, DEFAULT_COOKIE_PREFIX, getRuntimeConfig, normalizeApplication, normalizeCookiePrefix } from "./RuntimeConfig";
4
+ export { FrontEndSessionService } from "./FrontEndSessionService";
5
+ export { AuthenticationManager, browserNavigator } from "./AuthenticationManager";
6
+ export { createAuthentication } from "./createAuthentication";
7
+ export { AuthenticationContext, useAuthentication } from "./AuthenticationContext";
8
+ export { AuthenticationProvider } from "./AuthenticationProvider";
9
+ export { RequireAuthentication } from "./RequireAuthentication";
@@ -0,0 +1 @@
1
+ export declare function readCookie(name: string, source?: string): string | undefined;
@@ -0,0 +1,12 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ export function readCookie(name, source = document.cookie) {
5
+ for (const part of source.split(";")) {
6
+ const separator = part.indexOf("=");
7
+ if (separator > 0 && part.slice(0, separator).trim() === name)
8
+ return part.slice(separator + 1).trim();
9
+ }
10
+ return undefined;
11
+ }
12
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,10 @@
1
+ export type FetchFunction = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
2
+ export declare function csrfCookieName(prefix: string): string;
3
+ export declare const CSRF_HEADER: string;
4
+ export declare class CsrfFetch {
5
+ readonly fetch: FetchFunction;
6
+ private readonly send;
7
+ private readonly readToken;
8
+ constructor(fetchFunction?: FetchFunction, cookieReader?: (name: string) => string | undefined, cookieName?: string);
9
+ private execute;
10
+ }
@@ -0,0 +1,41 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ import { readCookie } from "./Cookies";
5
+ import { DEFAULT_COOKIE_PREFIX } from "../Authentication/RuntimeConfig";
6
+ export function csrfCookieName(prefix) {
7
+ return `__Host-${prefix}-XSRF-TOKEN`;
8
+ }
9
+ export const CSRF_HEADER = "X-XSRF-TOKEN";
10
+ const UNSAFE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
11
+ export class CsrfFetch {
12
+ fetch;
13
+ send;
14
+ readToken;
15
+ constructor(fetchFunction = (input, init) => window.fetch(input, init), cookieReader = (name) => readCookie(name), cookieName = csrfCookieName(DEFAULT_COOKIE_PREFIX)) {
16
+ this.send = fetchFunction;
17
+ this.readToken = () => cookieReader(cookieName);
18
+ this.fetch = (input, init) => this.execute(input, init);
19
+ }
20
+ async execute(input, init) {
21
+ const method = (init?.method ?? "GET").toUpperCase();
22
+ if (!UNSAFE_METHODS.has(method))
23
+ return this.send(input, init);
24
+ const token = this.readToken();
25
+ const response = await this.send(input, withToken(init, token));
26
+ if (response.status !== 403)
27
+ return response;
28
+ const fresh = this.readToken();
29
+ if (fresh === undefined || fresh === token)
30
+ return response;
31
+ return this.send(input, withToken(init, fresh));
32
+ }
33
+ }
34
+ function withToken(init, token) {
35
+ if (token === undefined)
36
+ return init;
37
+ const headers = new Headers(init?.headers);
38
+ headers.set(CSRF_HEADER, token);
39
+ return { ...init, headers };
40
+ }
41
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,10 @@
1
+ import type { FetchFunction } from "./CsrfFetch";
2
+ export type UnauthorizedHandler = () => Promise<boolean>;
3
+ export declare class SessionFetch {
4
+ readonly fetch: FetchFunction;
5
+ private readonly send;
6
+ private handler;
7
+ constructor(csrfFetch: FetchFunction);
8
+ setUnauthorizedHandler(handler: UnauthorizedHandler): void;
9
+ private execute;
10
+ }
@@ -0,0 +1,23 @@
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Granite.Web.Authentication
3
+ //////////////////////////////////////////////////////////////////////////////
4
+ export class SessionFetch {
5
+ fetch;
6
+ send;
7
+ handler;
8
+ constructor(csrfFetch) {
9
+ this.send = csrfFetch;
10
+ this.handler = undefined;
11
+ this.fetch = (input, init) => this.execute(input, init);
12
+ }
13
+ setUnauthorizedHandler(handler) {
14
+ this.handler = handler;
15
+ }
16
+ async execute(input, init) {
17
+ const response = await this.send(input, init);
18
+ if (response.status !== 401 || !this.handler)
19
+ return response;
20
+ return await this.handler() ? this.send(input, init) : response;
21
+ }
22
+ }
23
+ //////////////////////////////////////////////////////////////////////////////
@@ -0,0 +1,5 @@
1
+ export type { FetchFunction } from "./CsrfFetch";
2
+ export { CSRF_HEADER, CsrfFetch, csrfCookieName } from "./CsrfFetch";
3
+ export { readCookie } from "./Cookies";
4
+ export type { UnauthorizedHandler } from "./SessionFetch";
5
+ export { SessionFetch } from "./SessionFetch";
package/Http/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { CSRF_HEADER, CsrfFetch, csrfCookieName } from "./CsrfFetch";
2
+ export { readCookie } from "./Cookies";
3
+ export { SessionFetch } from "./SessionFetch";
@@ -0,0 +1,6 @@
1
+ import type { ReactElement } from "react";
2
+ export interface IChangePasswordDialogProps {
3
+ opened: boolean;
4
+ onClose: () => void;
5
+ }
6
+ export declare function ChangePasswordDialog({ opened, onClose }: IChangePasswordDialogProps): ReactElement;
@@ -0,0 +1,54 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ //////////////////////////////////////////////////////////////////////////////
3
+ // Granite.Web.Authentication
4
+ //////////////////////////////////////////////////////////////////////////////
5
+ import { useEffect, useState } from "react";
6
+ import { Alert, Button, Group, Modal, PasswordInput, Stack, Text } from "@mantine/core";
7
+ import { useAuthentication } from "../Authentication/AuthenticationContext";
8
+ const MISMATCH = "Passwords do not match";
9
+ export function ChangePasswordDialog({ opened, onClose }) {
10
+ const { changePassword } = useAuthentication();
11
+ const [current, setCurrent] = useState("");
12
+ const [next, setNext] = useState("");
13
+ const [confirm, setConfirm] = useState("");
14
+ const [submitting, setSubmitting] = useState(false);
15
+ const [error, setError] = useState(undefined);
16
+ const [changed, setChanged] = useState(false);
17
+ const filled = current.length > 0 && next.length > 0 && confirm.length > 0;
18
+ const mismatch = confirm.length > 0 && next !== confirm;
19
+ useEffect(() => {
20
+ if (opened)
21
+ return;
22
+ setCurrent("");
23
+ setNext("");
24
+ setConfirm("");
25
+ setSubmitting(false);
26
+ setError(undefined);
27
+ setChanged(false);
28
+ }, [opened]);
29
+ async function submit(event) {
30
+ event.preventDefault();
31
+ if (!filled || submitting)
32
+ return;
33
+ if (next !== confirm) {
34
+ setError(MISMATCH);
35
+ return;
36
+ }
37
+ setSubmitting(true);
38
+ setError(undefined);
39
+ const result = await changePassword(current, next);
40
+ setSubmitting(false);
41
+ if (result.success) {
42
+ setCurrent("");
43
+ setNext("");
44
+ setConfirm("");
45
+ setChanged(true);
46
+ }
47
+ else
48
+ setError(result.message ?? "Unable to change password");
49
+ }
50
+ return (_jsx(Modal, { opened: opened, centered: true, onClose: onClose, title: "Change Password", transitionProps: { duration: 0 }, children: changed
51
+ ? _jsxs(Stack, { children: [_jsx(Text, { size: "sm", children: "Your password has been changed. Other sessions were signed out." }), _jsx(Group, { justify: "flex-end", children: _jsx(Button, { onClick: onClose, children: "Close" }) })] })
52
+ : _jsx("form", { onSubmit: (event) => { void submit(event); }, children: _jsxs(Stack, { children: [_jsx(PasswordInput, { label: "Current password", autoComplete: "current-password", value: current, onChange: (event) => setCurrent(event.currentTarget.value) }), _jsx(PasswordInput, { label: "New password", autoComplete: "new-password", value: next, onChange: (event) => setNext(event.currentTarget.value) }), _jsx(PasswordInput, { label: "Confirm new password", autoComplete: "new-password", value: confirm, onChange: (event) => setConfirm(event.currentTarget.value), error: mismatch ? MISMATCH : undefined }), error !== undefined && !(mismatch && error === MISMATCH) &&
53
+ _jsx(Alert, { color: "red", role: "alert", children: error }), _jsx(Group, { justify: "flex-end", children: _jsx(Button, { type: "submit", loading: submitting, disabled: !filled, children: "Change Password" }) })] }) }) }));
54
+ }
@@ -0,0 +1,2 @@
1
+ import type { ReactElement } from "react";
2
+ export declare function LoginCallbackView(): ReactElement;
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ //////////////////////////////////////////////////////////////////////////////
3
+ // Granite.Web.Authentication
4
+ //////////////////////////////////////////////////////////////////////////////
5
+ import { useEffect, useRef, useState } from "react";
6
+ import { Link, useNavigate, useSearchParams } from "react-router-dom";
7
+ import { Alert, Anchor, Center, Loader, Stack } from "@mantine/core";
8
+ import { useAuthentication } from "../Authentication/AuthenticationContext";
9
+ export function LoginCallbackView() {
10
+ const { completeOktaLogin } = useAuthentication();
11
+ const [params] = useSearchParams();
12
+ const navigate = useNavigate();
13
+ const started = useRef(false);
14
+ const [error, setError] = useState(null);
15
+ useEffect(() => {
16
+ if (started.current)
17
+ return;
18
+ started.current = true;
19
+ const code = params.get("code");
20
+ const state = params.get("state");
21
+ const refusal = params.get("error");
22
+ if (refusal || !code || !state) {
23
+ setError("Login was not completed");
24
+ return;
25
+ }
26
+ completeOktaLogin(code, state).then((returnTo) => navigate(returnTo, { replace: true }), () => setError("Login failed"));
27
+ }, [completeOktaLogin, navigate, params]);
28
+ return (_jsx(Center, { py: "xl", children: _jsx(Stack, { gap: "md", align: "center", children: error
29
+ ? _jsxs(_Fragment, { children: [_jsx(Alert, { color: "red", role: "alert", children: error }), _jsx(Anchor, { component: Link, to: "/login", children: "Back to login" })] })
30
+ : _jsx(Loader, { "aria-label": "Completing login" }) }) }));
31
+ }
@@ -0,0 +1,6 @@
1
+ import type { ReactElement } from "react";
2
+ export interface ILoginFormProps {
3
+ returnTo: string;
4
+ onLoggedIn?: () => void;
5
+ }
6
+ export declare function LoginForm({ returnTo, onLoggedIn }: ILoginFormProps): ReactElement;
@@ -0,0 +1,50 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ //////////////////////////////////////////////////////////////////////////////
3
+ // Granite.Web.Authentication
4
+ //////////////////////////////////////////////////////////////////////////////
5
+ import { useEffect, useState } from "react";
6
+ import { Alert, Button, Divider, Loader, PasswordInput, Stack, Text, TextInput } from "@mantine/core";
7
+ import { useAuthentication } from "../Authentication/AuthenticationContext";
8
+ export function LoginForm({ returnTo, onLoggedIn }) {
9
+ const { getLoginMethods, login, startOktaLogin } = useAuthentication();
10
+ const [methods, setMethods] = useState(null);
11
+ const [loadFailed, setLoadFailed] = useState(false);
12
+ const [userName, setUserName] = useState("");
13
+ const [password, setPassword] = useState("");
14
+ const [error, setError] = useState(null);
15
+ const [busy, setBusy] = useState(false);
16
+ useEffect(() => {
17
+ let active = true;
18
+ getLoginMethods().then((loaded) => { if (active)
19
+ setMethods(loaded); }, () => { if (active)
20
+ setLoadFailed(true); });
21
+ return () => { active = false; };
22
+ }, [getLoginMethods]);
23
+ const attempt = async (action) => {
24
+ setError(null);
25
+ setBusy(true);
26
+ try {
27
+ await action();
28
+ onLoggedIn?.();
29
+ }
30
+ catch (failure) {
31
+ setError(failure instanceof Error ? failure.message : "Login failed");
32
+ }
33
+ finally {
34
+ setBusy(false);
35
+ }
36
+ };
37
+ const onSubmit = (event) => {
38
+ event.preventDefault();
39
+ void attempt(() => login(userName, password));
40
+ };
41
+ if (loadFailed)
42
+ return _jsx(Alert, { color: "red", role: "alert", children: "Unable to load login options" });
43
+ if (!methods)
44
+ return _jsx(Loader, { "aria-label": "Loading login options" });
45
+ if (!methods.passwordEnabled && !methods.oktaEnabled)
46
+ return _jsx(Text, { children: "No login method is enabled." });
47
+ return (_jsxs(Stack, { gap: "md", children: [error && _jsx(Alert, { color: "red", role: "alert", children: error }), methods.passwordEnabled &&
48
+ _jsx("form", { onSubmit: onSubmit, children: _jsxs(Stack, { gap: "md", children: [_jsx(TextInput, { label: "User name", autoComplete: "username", required: true, value: userName, onChange: (event) => setUserName(event.currentTarget.value) }), _jsx(PasswordInput, { label: "Password", autoComplete: "current-password", required: true, value: password, onChange: (event) => setPassword(event.currentTarget.value) }), _jsx(Button, { type: "submit", loading: busy, disabled: !userName || !password, children: "Login" })] }) }), methods.passwordEnabled && methods.oktaEnabled && _jsx(Divider, { label: "or", labelPosition: "center" }), methods.oktaEnabled &&
49
+ _jsx(Button, { variant: "default", loading: busy, onClick: () => { void attempt(() => startOktaLogin(returnTo)); }, children: "Login with Okta" })] }));
50
+ }
@@ -0,0 +1,2 @@
1
+ import type { ReactElement } from "react";
2
+ export declare function LoginView(): ReactElement;
@@ -0,0 +1,13 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Navigate, useLocation } from "react-router-dom";
3
+ import { Center, Paper, Stack, Title } from "@mantine/core";
4
+ import { useAuthentication } from "../Authentication/AuthenticationContext";
5
+ import { LoginForm } from "./LoginForm";
6
+ export function LoginView() {
7
+ const { state } = useAuthentication();
8
+ const location = useLocation();
9
+ const target = location.state?.from ?? "/";
10
+ if (state.status === "authenticated")
11
+ return _jsx(Navigate, { to: target, replace: true });
12
+ return (_jsx(Center, { py: "xl", children: _jsx(Paper, { withBorder: true, shadow: "sm", p: "lg", w: 360, children: _jsxs(Stack, { gap: "md", children: [_jsx(Title, { order: 3, children: "Login" }), _jsx(LoginForm, { returnTo: target })] }) }) }));
13
+ }
@@ -0,0 +1,2 @@
1
+ import type { ReactElement } from "react";
2
+ export declare function ReauthenticationDialog(): ReactElement;
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Modal, Text } from "@mantine/core";
3
+ import { useAuthentication } from "../Authentication/AuthenticationContext";
4
+ import { LoginForm } from "./LoginForm";
5
+ export function ReauthenticationDialog() {
6
+ const { state, cancelReauthentication } = useAuthentication();
7
+ const returnTo = window.location.pathname + window.location.search + window.location.hash;
8
+ return (_jsxs(Modal, { opened: true, centered: true, onClose: cancelReauthentication, title: "Session expired", closeOnClickOutside: false, closeButtonProps: { "aria-label": "Cancel login" }, transitionProps: { duration: 0 }, children: [_jsx(Text, { size: "sm", mb: "md", children: state.userName ? state.userName + ", log in again to continue." : "Log in again to continue." }), _jsx(LoginForm, { returnTo: returnTo })] }));
9
+ }
@@ -0,0 +1,13 @@
1
+ import type { CSSProperties, ReactElement } from "react";
2
+ export interface IUserMenuItem {
3
+ label: string;
4
+ onClick: () => void;
5
+ }
6
+ export interface IUserMenuProps {
7
+ preferencesPath?: string;
8
+ loginPath?: string;
9
+ items?: Array<IUserMenuItem>;
10
+ className?: string;
11
+ style?: CSSProperties;
12
+ }
13
+ export declare function UserMenu(props: IUserMenuProps): ReactElement;
@@ -0,0 +1,37 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ //////////////////////////////////////////////////////////////////////////////
3
+ // Granite.Web.Authentication
4
+ //////////////////////////////////////////////////////////////////////////////
5
+ import { useState } from "react";
6
+ import { useLocation, useNavigate } from "react-router-dom";
7
+ import { ActionIcon, Group, Menu, Text, UnstyledButton } from "@mantine/core";
8
+ import { useAuthentication } from "../Authentication/AuthenticationContext";
9
+ import { ChangePasswordDialog } from "./ChangePasswordDialog";
10
+ export function UserMenu(props) {
11
+ const { preferencesPath, items } = props;
12
+ const loginPath = props.loginPath ?? "/login";
13
+ const { state, logout } = useAuthentication();
14
+ const navigate = useNavigate();
15
+ const [changing, setChanging] = useState(false);
16
+ const location = useLocation();
17
+ const loggedIn = state.status === "authenticated" || state.status === "reauthenticating";
18
+ const restoring = state.status === "restoring";
19
+ const pathname = location.pathname;
20
+ const active = preferencesPath !== undefined && (pathname === preferencesPath || pathname.startsWith(preferencesPath + "/"));
21
+ const canChangePassword = loggedIn && state.passwordEnabled === true && state.passwordSet === true;
22
+ const classes = ["app-bar-user-menu", active ? "active" : "", props.className ?? ""].filter((name) => name !== "").join(" ");
23
+ return (_jsxs(_Fragment, { children: [_jsxs(Menu, { shadow: "md", width: 200, children: [_jsx(Menu.Target, { children: _jsx(UnstyledButton, { className: classes, style: {
24
+ marginLeft: "auto",
25
+ display: "flex",
26
+ alignItems: "center",
27
+ borderBottom: "var(--user-menu-border-width, 3px) solid " + (active ? "var(--user-menu-active-color, var(--mantine-primary-color-filled))" : "var(--user-menu-border-color, transparent)"),
28
+ ...props.style
29
+ }, children: _jsxs(Group, { gap: 2, align: "center", children: [_jsx(ActionIcon, { variant: "subtle", color: "gray", title: "User menu", "aria-label": "User menu", size: "lg", style: { color: "inherit" }, children: _jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", width: "22", height: "22", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("circle", { cx: "12", cy: "12", r: "10" }), _jsx("circle", { cx: "12", cy: "8", r: "3" }), _jsx("path", { d: "M6 20.5c0-3 2.7-5.5 6-5.5s6 2.5 6 5.5" })] }) }), _jsx(Text, { size: "sm", fw: 500, children: restoring ? "" : loggedIn ? state.userName : "Login" })] }) }) }), _jsxs(Menu.Dropdown, { children: [restoring
30
+ ? null
31
+ : loggedIn
32
+ ? _jsx(Menu.Item, { onClick: () => { void logout().then((done) => { if (done)
33
+ navigate(loginPath); }); }, children: "Logout" })
34
+ : _jsx(Menu.Item, { onClick: () => navigate(loginPath), children: "Login" }), canChangePassword &&
35
+ _jsx(Menu.Item, { onClick: () => setChanging(true), children: "Change Password" }), preferencesPath !== undefined &&
36
+ _jsx(Menu.Item, { onClick: () => navigate(preferencesPath), children: "Preferences" }), (items ?? []).map((item, index) => _jsx(Menu.Item, { onClick: item.onClick, children: item.label }, `${index}-${item.label}`))] })] }), _jsx(ChangePasswordDialog, { opened: changing, onClose: () => setChanging(false) })] }));
37
+ }
@@ -0,0 +1,9 @@
1
+ export type { ILoginFormProps } from "./LoginForm";
2
+ export { LoginForm } from "./LoginForm";
3
+ export { LoginView } from "./LoginView";
4
+ export { LoginCallbackView } from "./LoginCallbackView";
5
+ export type { IChangePasswordDialogProps } from "./ChangePasswordDialog";
6
+ export { ChangePasswordDialog } from "./ChangePasswordDialog";
7
+ export { ReauthenticationDialog } from "./ReauthenticationDialog";
8
+ export type { IUserMenuItem, IUserMenuProps } from "./UserMenu";
9
+ export { UserMenu } from "./UserMenu";
package/Login/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { LoginForm } from "./LoginForm";
2
+ export { LoginView } from "./LoginView";
3
+ export { LoginCallbackView } from "./LoginCallbackView";
4
+ export { ChangePasswordDialog } from "./ChangePasswordDialog";
5
+ export { ReauthenticationDialog } from "./ReauthenticationDialog";
6
+ export { UserMenu } from "./UserMenu";
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./Authentication";
2
+ export * from "./Login";
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./Authentication";
2
+ export * from "./Login";
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "granite.web.authentication",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-release.1795807978031",
4
+ "license": "Apache-2.0",
5
+ "scripts": {
6
+ "increment-snapshot": "npm-prerelease-timestamp -v 1.0.0"
7
+ },
8
+ "dependencies": {
9
+ "@mantine/core": "^7.17.0",
10
+ "@mantine/hooks": "^7.17.0",
11
+ "granite.frontendcontroller.client": "release-1.0.0",
12
+ "granite.frontendcontroller.service": "release-1.0.0",
13
+ "react": "^19.0.0",
14
+ "react-router-dom": "^7.0.0",
15
+ "strata.client.core": "release-1.0.0",
16
+ "strata.foundation.core": "release-1.0.0",
17
+ "strata.frontendcontroller.client": "release-1.0.0",
18
+ "strata.frontendcontroller.service": "release-1.0.0"
19
+ }
20
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.