@jsb188/auth-web 1.1.3 → 1.1.11

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.
@@ -1,71 +1,138 @@
1
- import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
2
- import type { ErrorMessageProps } from '@jsb188/react-web/ui/Layout';
3
- import { FullPageLayout, ErrorMessage } from '@jsb188/react-web/ui/Layout';
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type {
3
+ ServerErrorObj,
4
+ SimpleErrorType,
5
+ } from '@jsb188/app/types/app.d.ts';
6
+ import type { ErrorMessageProps } from '@jsb188/react-web/modules/layout/MainLayout';
7
+ import {
8
+ AppContentArea,
9
+ ErrorMessage,
10
+ FullPageLayout,
11
+ } from '@jsb188/react-web/modules/layout/MainLayout';
4
12
  import { BigLoading } from '@jsb188/react-web/ui/Loading';
5
13
  import { useIsLoggedIn } from '@jsb188/react/states';
6
- import i18n from '@jsb188/app/i18n';
14
+
15
+ /**
16
+ * Auth gate; loading
17
+ */
18
+
19
+ function AuthGateLoading({ message }: { message?: string }) {
20
+ return (
21
+ <>
22
+ <BigLoading color="active" />
23
+ {message && <p className="mt_df cl_md">{message}</p>}
24
+ </>
25
+ );
26
+ }
7
27
 
8
28
  /**
9
29
  * Loading or Error interface
10
30
  */
11
31
 
12
32
  interface AuthGateProps extends ErrorMessageProps {
13
- children: React.ReactNode;
14
- connectedToServer?: boolean;
15
- notReady?: boolean;
16
- loading?: boolean;
17
- loadingMessage?: string;
18
- defaultErrorMessage?: string;
19
- error?: ServerErrorObj | SimpleErrorType | null;
33
+ children: React.ReactNode;
34
+ notLayout?: boolean;
35
+ connectedToServer?: boolean;
36
+ notReady?: boolean;
37
+ appLoading?: boolean; // Only used if `notLayout=true`
38
+ loading?: boolean;
39
+ loadingMessage?: string;
40
+ defaultErrorMessage?: string;
41
+ error?: ServerErrorObj | SimpleErrorType | null;
20
42
  }
21
43
 
22
44
  export function AuthGate(p: AuthGateProps) {
23
- const { notReady, loading, loadingMessage, defaultErrorMessage, error, children, connectedToServer, ...other } = p;
24
- const isLoggedIn = useIsLoggedIn();
25
- const isNetworkError = (error as ServerErrorObj)?.errorCode === 'network_error';
45
+ const {
46
+ notReady,
47
+ appLoading,
48
+ loading,
49
+ loadingMessage,
50
+ defaultErrorMessage,
51
+ error,
52
+ children,
53
+ notLayout,
54
+ connectedToServer,
55
+ ...other
56
+ } = p;
57
+ const isLoggedIn = useIsLoggedIn();
58
+ const isNetworkError =
59
+ (error as ServerErrorObj)?.errorCode === 'network_error';
60
+ const isAuthLoading = loading && !isLoggedIn;
61
+ const shouldRender = isLoggedIn && !notReady && !error;
62
+
63
+ if (shouldRender || ((isAuthLoading || notReady) && notLayout)) {
64
+ if (notLayout) {
65
+ // The loading element needs to be absolute for `notLayout=true`
66
+ // NOTE: Obviously if `appLoading=true`, then this will hide the actual content forever.
67
+ // This was done intentionally-- if the route is using this feature, the route has to turn off the loading state manually from inside the route.
68
+ return (
69
+ <>
70
+ {appLoading && (
71
+ <div className="abs_full v_center bg z6">
72
+ <AuthGateLoading message={loadingMessage} />
73
+ </div>
74
+ )}
75
+ {shouldRender ? children : null}
76
+ </>
77
+ );
78
+ }
79
+
80
+ // ONLY return this if `notLayout=false`
81
+ return children;
82
+ }
83
+
84
+ if (notReady || isAuthLoading) {
85
+ // If `notLayout=true` this code block should NEVER happen
86
+ // There should be no need to do `noLayout` check here because it should be caught above
87
+ return (
88
+ <FullPageLayout>
89
+ <AuthGateLoading message={loadingMessage} />
90
+ </FullPageLayout>
91
+ );
92
+ }
26
93
 
27
- if (isLoggedIn && !notReady) {
28
- return children;
29
- }
94
+ if (!isLoggedIn && !isNetworkError) {
95
+ // Gota do log in form here
96
+ // Gota do log in form here
97
+ // Gota do log in form here
98
+ // Gota do log in form here
99
+ }
30
100
 
31
- if (notReady || (loading && !isLoggedIn)) {
32
- return <FullPageLayout>
33
- <BigLoading color='active' />
34
- {loadingMessage && (
35
- <p className='mt_df cl_md'>
36
- {loadingMessage}
37
- </p>
38
- )}
39
- </FullPageLayout>;
40
- }
101
+ // IMPORTANT NOTE:
102
+ // {connectedToServer} is currently always true, passed down from graphql hooks.
103
+ // This is a placeholder logic, and must properly return a real network state in the future.
41
104
 
42
- if (!isLoggedIn && !isNetworkError) {
43
- // Gota do log in form here
44
- // Gota do log in form here
45
- // Gota do log in form here
46
- // Gota do log in form here
47
- }
105
+ let errorCode, errorMessage;
106
+ if (error?.message) {
107
+ errorMessage = error.message;
108
+ } else if (isNetworkError || (!connectedToServer && isLoggedIn)) {
109
+ errorCode = 'network_error';
110
+ errorMessage = i18n.t('error.network_error');
111
+ } else if (!isLoggedIn) {
112
+ errorCode = '20019';
113
+ errorMessage = i18n.t('error.20019');
114
+ } else {
115
+ errorMessage = defaultErrorMessage;
116
+ }
48
117
 
49
- // IMPORTANT NOTE:
50
- // {connectedToServer} is currently always true, passed down from graphql hooks.
51
- // This is a placeholder logic, and must properly return a real network state in the future.
118
+ const errorProps = {
119
+ ...error,
120
+ ...other,
121
+ errorCode,
122
+ message: errorMessage,
123
+ };
52
124
 
53
- let errorMessage;
54
- if (error?.message) {
55
- errorMessage = error.message;
56
- } else if (isNetworkError || !connectedToServer) {
57
- errorMessage = i18n.t('error.network_error');
58
- } else if (!isLoggedIn) {
59
- errorMessage = i18n.t('error.20019');
60
- } else {
61
- errorMessage = defaultErrorMessage;
62
- }
125
+ if (notLayout) {
126
+ return (
127
+ <AppContentArea className="v_center pb_xl">
128
+ <ErrorMessage {...errorProps} />
129
+ </AppContentArea>
130
+ );
131
+ }
63
132
 
64
- return <FullPageLayout>
65
- <ErrorMessage
66
- message={errorMessage}
67
- {...error}
68
- {...other}
69
- />
70
- </FullPageLayout>;
133
+ return (
134
+ <FullPageLayout>
135
+ <ErrorMessage {...errorProps} />
136
+ </FullPageLayout>
137
+ );
71
138
  }
@@ -0,0 +1,161 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { useCurrentAccount } from '@jsb188/react/states';
3
+ import { AvatarImg } from '@jsb188/react-web/ui/Avatar';
4
+ import { PageFormHeaderOAuthButton } from '@jsb188/react-web/ui/PageFormUI';
5
+ import { TextWithLinks } from '@jsb188/react-web/ui/Markdown';
6
+ import { memo, useCallback, type ReactNode } from 'react';
7
+ import {
8
+ useContinueWithGoogle,
9
+ useContinueWithMicrosoft,
10
+ } from '../hooks/use-oauth';
11
+
12
+ /**
13
+ * Types
14
+ */
15
+
16
+ interface InlineAuthFormProps {
17
+ // Sign-in button labels; a null/absent label hides that provider's button
18
+ googleLabel?: string | null;
19
+ microsoftLabel?: string | null;
20
+ // Verified email of a temporary (account-less) respondent token holder; shown
21
+ // as the identity when there is no signed-in account
22
+ respondentEmail?: string | null;
23
+ // Respondent status / helper text shown next to the buttons; a plain string
24
+ // is parsed for inline links, a node is rendered as-is
25
+ accountMessage?: ReactNode;
26
+ // When true, an OAuth-verified email with no account does not error; the
27
+ // server returns a temporary respondent token (ANYONE web forms)
28
+ authenticateOnly?: boolean;
29
+ // Public web form context (contact-gated account creation / respondent token)
30
+ formPublicId?: string | null;
31
+ // Called after a real account sign-in flips the app into a logged-in state,
32
+ // with the fresh auth token (e.g. to silently persist the SSR session cookie)
33
+ onSignedIn?: (
34
+ token: string,
35
+ sessionBootstrapToken?: string | null,
36
+ sessionPersisted?: boolean,
37
+ ) => boolean | Promise<boolean>;
38
+ // Called when authenticateOnly returned a temporary form respondent token
39
+ onRespondentToken?: (token: string, email: string | null) => void;
40
+ }
41
+
42
+ /*
43
+ * Inline Google/Microsoft sign-in that keeps the user on the current page.
44
+ * The OAuth popup authenticates the user and the underlying hooks flip the
45
+ * shared app state to logged-in (via onAccountLogin) with no navigation.
46
+ * ANYONE web forms may pass authenticateOnly to accept account-less
47
+ * respondents via a temporary token instead of forcing account creation.
48
+ */
49
+
50
+ const InlineAuthForm = (p: InlineAuthFormProps) => {
51
+ const {
52
+ googleLabel,
53
+ microsoftLabel,
54
+ respondentEmail,
55
+ accountMessage,
56
+ authenticateOnly,
57
+ formPublicId,
58
+ onSignedIn,
59
+ onRespondentToken,
60
+ } = p;
61
+
62
+ // A signed-in account takes precedence; otherwise a temporary respondent
63
+ // token holder is identified by their verified email
64
+ const { isLoggedIn, displayName, labelName } = useCurrentAccount();
65
+ const signedInName = isLoggedIn
66
+ ? displayName || labelName
67
+ : respondentEmail || null;
68
+
69
+ /*
70
+ * A real account sign-in already applied the logged-in app state; hand the
71
+ * token to the caller for any follow-up (e.g. persisting the session cookie).
72
+ */
73
+ const onFinishSignIn = useCallback(
74
+ (
75
+ token: string,
76
+ sessionBootstrapToken?: string | null,
77
+ sessionPersisted?: boolean,
78
+ ) => onSignedIn?.(token, sessionBootstrapToken, sessionPersisted) ?? false,
79
+ [onSignedIn],
80
+ );
81
+
82
+ const {
83
+ onInitiateGoogleSignIn,
84
+ oauthButtonDisabled: googleDisabled,
85
+ waitingForOAuth: googleLoading,
86
+ } = useContinueWithGoogle({ onFinishSignIn, onRespondentToken });
87
+ const {
88
+ onInitiateMicrosoftSignIn,
89
+ oauthButtonDisabled: microsoftDisabled,
90
+ waitingForOAuth: microsoftLoading,
91
+ } = useContinueWithMicrosoft({ onFinishSignIn, onRespondentToken });
92
+
93
+ const onGoogle = useCallback(() => {
94
+ onInitiateGoogleSignIn(
95
+ undefined,
96
+ null,
97
+ formPublicId ?? null,
98
+ authenticateOnly,
99
+ );
100
+ }, [onInitiateGoogleSignIn, formPublicId, authenticateOnly]);
101
+
102
+ const onMicrosoft = useCallback(() => {
103
+ onInitiateMicrosoftSignIn(
104
+ undefined,
105
+ undefined,
106
+ formPublicId ?? null,
107
+ authenticateOnly,
108
+ );
109
+ }, [onInitiateMicrosoftSignIn, formPublicId, authenticateOnly]);
110
+
111
+ return (
112
+ <div className="h_item gap_sm min_w_0 f_wrap rel">
113
+ {signedInName ? (
114
+ <div className="h_item gap_8 min_w_0">
115
+ <AvatarImg
116
+ className="shift_up"
117
+ displayName={signedInName}
118
+ size="small"
119
+ letterBackgroundClassName="bd_2 bd_lt bg"
120
+ />
121
+ <p className="ft_medium">
122
+ {i18n.t('auth.logged_in_as_', { name: signedInName })}
123
+ </p>
124
+ </div>
125
+ ) : (
126
+ (!!googleLabel || !!microsoftLabel) && (
127
+ <div className="h_item gap_5 no_shrink">
128
+ {!!googleLabel && (
129
+ <PageFormHeaderOAuthButton
130
+ iconName="brand-google-color"
131
+ label={googleLabel}
132
+ disabled={googleDisabled}
133
+ loading={googleLoading}
134
+ onClick={onGoogle}
135
+ />
136
+ )}
137
+ {!!microsoftLabel && (
138
+ <PageFormHeaderOAuthButton
139
+ iconName="brand-microsoft-color"
140
+ label={microsoftLabel}
141
+ disabled={microsoftDisabled}
142
+ loading={microsoftLoading}
143
+ onClick={onMicrosoft}
144
+ />
145
+ )}
146
+ </div>
147
+ )
148
+ )}
149
+ {!!accountMessage &&
150
+ (typeof accountMessage === 'string' ? (
151
+ <TextWithLinks as="p" className="cl_md ml_xs" linkClassName="u cl_df">
152
+ {accountMessage}
153
+ </TextWithLinks>
154
+ ) : (
155
+ <p className="cl_md ft_md">{accountMessage}</p>
156
+ ))}
157
+ </div>
158
+ );
159
+ };
160
+
161
+ export default memo(InlineAuthForm);
@@ -0,0 +1,135 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { AccountSessionData } from '@jsb188/app/types/auth.d.ts';
3
+ import {
4
+ useRevokeMyAccountSession,
5
+ useRevokeMyOtherAccountSessions,
6
+ } from '@jsb188/graphql/hooks/use-auth-mtn';
7
+ import { useMyAccountSessions } from '@jsb188/graphql/hooks/use-auth-qry';
8
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
9
+ import { BigLoading } from '@jsb188/react-web/ui/Loading';
10
+ import { useMemo, useState } from 'react';
11
+ import {
12
+ type ManagedSessionListItem,
13
+ ManagedSessionListUI,
14
+ } from '../ui/ManagedSessionUI.tsx';
15
+
16
+ /*
17
+ * Format one managed-session timestamp for the current browser locale.
18
+ */
19
+ function formatManagedSessionDate(value?: string | null) {
20
+ const date = value ? new Date(value) : null;
21
+ return date && !isNaN(date.getTime()) ? date.toLocaleString() : '-';
22
+ }
23
+
24
+ /*
25
+ * Convert server session rows into display-ready immutable list items.
26
+ */
27
+ export function mapManagedSessionItems(
28
+ sessions?: AccountSessionData[] | null,
29
+ ): ManagedSessionListItem[] {
30
+ return (sessions || [])
31
+ .filter((session) => !session.revokedAt)
32
+ .map((session) => ({
33
+ ...session,
34
+ displayName:
35
+ session.deviceName ||
36
+ session.userAgent ||
37
+ i18n.t('account.session_unknown_device'),
38
+ displayExpiresAt: formatManagedSessionDate(session.absoluteExpiresAt),
39
+ displayLastActivityAt: formatManagedSessionDate(session.lastActivityAt),
40
+ }))
41
+ .sort(
42
+ (a, b) =>
43
+ Number(b.current) - Number(a.current) ||
44
+ new Date(b.lastActivityAt).getTime() -
45
+ new Date(a.lastActivityAt).getTime(),
46
+ );
47
+ }
48
+
49
+ /*
50
+ * Load and manage the current account's active device sessions.
51
+ */
52
+ export function ManagedSessions() {
53
+ const { accountSessions, loading } = useMyAccountSessions();
54
+ const [savingSessionId, setSavingSessionId] = useState<string | null>(null);
55
+ const [revokedSessionIds, setRevokedSessionIds] = useState<Set<string>>(
56
+ () => new Set(),
57
+ );
58
+ const [hideOtherSessions, setHideOtherSessions] = useState(false);
59
+ const { revokeMyAccountSession } = useRevokeMyAccountSession({
60
+ onCompleted: (data, _error, variables) => {
61
+ if (data?.revokeMyAccountSession && variables?.sessionId) {
62
+ setRevokedSessionIds((current) =>
63
+ new Set(current).add(variables.sessionId),
64
+ );
65
+ }
66
+ setSavingSessionId(null);
67
+ },
68
+ onError: () => setSavingSessionId(null),
69
+ });
70
+ const { revokeMyOtherAccountSessions, saving: savingOthers } =
71
+ useRevokeMyOtherAccountSessions({
72
+ onCompleted: (data) => {
73
+ if (data?.revokeMyOtherAccountSessions) {
74
+ setHideOtherSessions(true);
75
+ }
76
+ },
77
+ });
78
+ const items = useMemo(
79
+ () =>
80
+ mapManagedSessionItems(accountSessions).filter(
81
+ (session) =>
82
+ !revokedSessionIds.has(session.id) &&
83
+ (!hideOtherSessions || session.current),
84
+ ),
85
+ [accountSessions, hideOtherSessions, revokedSessionIds],
86
+ );
87
+
88
+ /*
89
+ * Revoke one selected managed session.
90
+ */
91
+ const onRevokeSession = (sessionId: string) => {
92
+ setSavingSessionId(sessionId);
93
+ revokeMyAccountSession({
94
+ variables: {
95
+ sessionId,
96
+ },
97
+ });
98
+ };
99
+
100
+ if (loading && !accountSessions) {
101
+ return (
102
+ <div className="h_160 v_center">
103
+ <BigLoading />
104
+ </div>
105
+ );
106
+ }
107
+
108
+ return (
109
+ <div className="max_w_600">
110
+ <p className="cl_lt mb_sm">{i18n.t('account.sessions_desc')}</p>
111
+ <ManagedSessionListUI
112
+ items={items}
113
+ emptyText={i18n.t('account.session_none')}
114
+ revokeText={i18n.t('account.session_sign_out')}
115
+ currentText={i18n.t('account.session_current')}
116
+ expiresText={i18n.t('account.session_expires')}
117
+ lastActiveText={i18n.t('account.session_last_active')}
118
+ savingSessionId={savingSessionId}
119
+ onRevoke={onRevokeSession}
120
+ />
121
+ {items.length <= 1 ? null : (
122
+ <FullWidthButton
123
+ fullWidth={false}
124
+ className="mt_md"
125
+ preset="outline"
126
+ loading={savingOthers}
127
+ disabled={savingOthers}
128
+ onClick={() => revokeMyOtherAccountSessions()}
129
+ >
130
+ {i18n.t('account.session_sign_out_others')}
131
+ </FullWidthButton>
132
+ )}
133
+ </div>
134
+ );
135
+ }
@@ -0,0 +1,116 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
3
+ import { useCallback } from 'react';
4
+ import {
5
+ type OnFinishSignInFn,
6
+ useContinueWithGoogle,
7
+ useContinueWithMicrosoft,
8
+ } from '../hooks/use-oauth';
9
+
10
+ interface OAuthButtonProps {
11
+ formPublicId?: string | null;
12
+ onFinishSignIn: OnFinishSignInFn;
13
+ }
14
+
15
+ interface AuthMethodButtonProps {
16
+ onClickButton: () => void;
17
+ }
18
+
19
+ /**
20
+ * Google OAuth button
21
+ */
22
+
23
+ export const ContinueWithGoogle = (p: OAuthButtonProps) => {
24
+ const { onFinishSignIn, formPublicId } = p;
25
+ const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } =
26
+ useContinueWithGoogle({
27
+ onFinishSignIn,
28
+ });
29
+
30
+ /* Launch Google OAuth with the current public-form context. */
31
+ const onClick = useCallback(() => {
32
+ onInitiateGoogleSignIn(undefined, null, formPublicId ?? null);
33
+ }, [formPublicId, onInitiateGoogleSignIn]);
34
+
35
+ return (
36
+ <FullWidthButton
37
+ disabled={oauthButtonDisabled}
38
+ loading={waitingForOAuth}
39
+ onClick={onClick}
40
+ preset="em"
41
+ className="mb_sm"
42
+ iconName="brand-google-color"
43
+ >
44
+ {i18n.t('auth.continue_with_google')}
45
+ </FullWidthButton>
46
+ );
47
+ };
48
+
49
+ /**
50
+ * Microsoft OAuth button
51
+ */
52
+
53
+ export const ContinueWithMicrosoft = (p: OAuthButtonProps) => {
54
+ const { onFinishSignIn, formPublicId } = p;
55
+ const { onInitiateMicrosoftSignIn, oauthButtonDisabled, waitingForOAuth } =
56
+ useContinueWithMicrosoft({
57
+ onFinishSignIn,
58
+ });
59
+
60
+ /* Launch Microsoft OAuth with the current public-form context. */
61
+ const onClick = useCallback(() => {
62
+ onInitiateMicrosoftSignIn(undefined, undefined, formPublicId ?? null);
63
+ }, [formPublicId, onInitiateMicrosoftSignIn]);
64
+
65
+ return (
66
+ <FullWidthButton
67
+ disabled={oauthButtonDisabled}
68
+ loading={waitingForOAuth}
69
+ onClick={onClick}
70
+ preset="em"
71
+ className="mb_sm"
72
+ iconName="brand-microsoft-color"
73
+ >
74
+ {i18n.t('auth.continue_with_microsoft')}
75
+ </FullWidthButton>
76
+ );
77
+ };
78
+
79
+ /**
80
+ * Org SSO button (email-first home realm discovery)
81
+ */
82
+
83
+ export const ContinueWithSso = (p: AuthMethodButtonProps) => {
84
+ const { onClickButton } = p;
85
+ return (
86
+ <FullWidthButton
87
+ onClick={onClickButton}
88
+ preset="em"
89
+ className="mb_sm"
90
+ iconName="buildings-2-color"
91
+ iconClassName="ft_md shift_up"
92
+ >
93
+ {i18n.t('auth.continue_with_sso')}
94
+ </FullWidthButton>
95
+ );
96
+ };
97
+
98
+ /**
99
+ * Phone sign-in button
100
+ */
101
+
102
+ export const ContinueWithPhone = (p: AuthMethodButtonProps) => {
103
+ const { onClickButton } = p;
104
+ return (
105
+ <FullWidthButton
106
+ onClick={onClickButton}
107
+ preset="em"
108
+ className="mb_sm"
109
+ iconName="phone-circle"
110
+ iconClassName="ft_md shift_up"
111
+ tryColor
112
+ >
113
+ {i18n.t('auth.continue_with_phone')}
114
+ </FullWidthButton>
115
+ );
116
+ };