/
login.tsx
180 lines (168 loc) · 6.93 KB
/
login.tsx
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* Copyright 2023 Shinami Corp.
* SPDX-License-Identifier: Apache-2.0
*/
import { SuiClient } from "@mysten/sui.js/client";
import React, { FunctionComponent, useEffect, useState } from "react";
import { useNewZkLoginSession } from "../hooks/login.js";
import { ZkLoginLocalSession } from "../hooks/session.js";
/**
* React HOC for implementing the login page.
*
* Resets local session state and prepares a new one. The new session state will be needed to get a
* new JWT from the OpenID providers.
*
* @param getMaxEpoch The function to determine the maxEpoch for this zkLogin session.
* Usually you would want this to be `relativeToCurrentEpoch`.
* @param Component Your React component that renders the login page.
* The props will be augmented with the new session state.
* @param Loading A transient React component for when the session is being initialized.
* @returns The wrapped component.
*/
export function withNewZkLoginSession<P extends object>(
getMaxEpoch: () => Promise<number> | number,
Component: FunctionComponent<P & { session: ZkLoginLocalSession }>,
Loading: FunctionComponent<P> = () => <p>Preparing zkLogin session...</p>
) {
const WrappedComponent: FunctionComponent<P> = (props) => {
const { mutateAsync: newSession } = useNewZkLoginSession();
const [session, setSession] = useState<ZkLoginLocalSession>();
useEffect(() => {
(async () => {
const session = await newSession({ getMaxEpoch });
setSession(session);
})();
}, [newSession]);
if (!session) return <Loading {...props} />;
return <Component session={session} {...props} />;
};
WrappedComponent.displayName = `WithNewZkLoginSession<${Component.displayName}>`;
return WrappedComponent;
}
/**
* Helper function to calculate a epoch relative to the current one.
*
* The current epoch is retrieved using `SuiClient`.
*
* @param sui The `SuiClient`.
* @param epochsBeyondCurrent The number of epochs beyond the current one.
* Defaults to 1, i.e. the next epoch.
* @returns Epoch number.
*/
export async function relativeToCurrentEpoch(
sui: SuiClient,
epochsBeyondCurrent: number = 1
): Promise<number> {
const { epoch } = await sui.getLatestSuiSystemState();
return Number(epoch) + epochsBeyondCurrent;
}
/**
* Helper function to compose the auth URL for Google.
*
* You'll need to redirect your user to this URL to complete the sign-in process.
*
* @param session A new zkLogin local session. Can be prepared with `useNewZkLoginSession`.
* @param clientId Your OAuth application client id.
* @param callback The callback page URL. Must be whitelisted on your OAuth application settings.
* A login will be initiated with your app backend from the callback page.
* @param redirectTo The redirect path after a successful login.
* @param extraScopes The "openid" scope is included by default. You can optionally request extra
* scopes, e.g. "email", which will be included in the JWT claims that can be consumed by your
* app. Your OAuth application must have the permission to request these scopes.
* @param prompt The information to prompt for. See the Google developer link below for details.
* @returns The Google auth URL.
*
* @see https://developers.google.com/identity/openid-connect/openid-connect#sendauthrequest
*/
export function getGoogleAuthUrl(
session: ZkLoginLocalSession,
clientId: string,
callback: URL,
redirectTo: string = "/",
extraScopes: string[] = [],
prompt: string[] = []
): URL {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: callback.toString(),
response_type: "id_token",
scope: ["openid", ...extraScopes].join(" "),
nonce: session.nonce,
state: new URLSearchParams({ redirectTo, nonce: session.nonce }).toString(),
prompt: prompt.join(" "),
}).toString();
return new URL(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);
}
/**
* Helper function to compose the auth URL for Facebook.
*
* You'll need to redirect your user to this URL to complete the sign-in process.
*
* @param session A new zkLogin local session. Can be prepared with `useNewZkLoginSession`.
* @param clientId Your OAuth application client id.
* @param callback The callback page URL. Must be whitelisted on your OAuth application settings.
* A login will be initiated with your app backend from the callback page.
* @param redirectTo The redirect path after a successful login.
* @param extraScopes The "openid" scope is included by default. You can optionally request extra
* scopes, e.g. "email", which will be included in the JWT claims that can be consumed by your
* app. Your OAuth application must have the permission to request these scopes.
* @returns The Facebook auth URL.
*
* @see https://developers.facebook.com/docs/facebook-login/guides/advanced/oidc-token
*/
export function getFacebookAuthUrl(
session: ZkLoginLocalSession,
clientId: string,
callback: URL,
redirectTo: string = "/",
extraScopes: string[] = []
): URL {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: callback.toString(),
response_type: "id_token",
scope: ["openid", ...extraScopes].join(" "),
nonce: session.nonce,
state: new URLSearchParams({ redirectTo, nonce: session.nonce }).toString(),
}).toString();
return new URL(`https://www.facebook.com/v18.0/dialog/oauth?${params}`);
}
/**
* Helper function to compose the auth URL for Twitch.
*
* You'll need to redirect your user to this URL to complete the sign-in process.
*
* @param session A new zkLogin local session. Can be prepared with `useNewZkLoginSession`.
* @param clientId Your OAuth application client id.
* @param callback The callback page URL. Must be whitelisted on your OAuth application settings.
* A login will be initiated with your app backend from the callback page.
* @param redirectTo The redirect path after a successful login.
* @param extraScopes The "openid" scope is included by default. You can optionally request extra
* scopes, e.g. "user:read:email".
* Your OAuth application must have the permission to request these scopes.
* @param extraClaims Extra claims to be included in the JWT, e.g. "email".
* @returns The Twitch auth URL.
*
* @see https://dev.twitch.tv/docs/authentication/getting-tokens-oidc/#oidc-implicit-grant-flow
*/
export function getTwitchAuthUrl(
session: ZkLoginLocalSession,
clientId: string,
callback: URL,
redirectTo: string = "/",
extraScopes: string[] = [],
extraClaims: string[] = []
): URL {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: callback.toString(),
response_type: "id_token",
scope: ["openid", ...extraScopes].join(" "),
claims: JSON.stringify({
id_token: Object.fromEntries(extraClaims.map((x) => [x, null])),
}),
nonce: session.nonce,
state: new URLSearchParams({ redirectTo, nonce: session.nonce }).toString(),
}).toString();
return new URL(`https://id.twitch.tv/oauth2/authorize?${params}`);
}