-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact.tsx
50 lines (43 loc) · 1.21 KB
/
react.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
import React from "react";
import { Session } from "../src/session.js";
// Setup the session
const session = new Session({
clientId: "client-id",
returnUrl: "https://app.example.com/return",
scopes: ["openid", "offline_access"],
openidConfiguration: {
authorizationEndpoint: "https://auth.example.com/auth",
tokenEndpoint: "https://auth.example.com/token",
endSessionEndpoint: "https://auth.example.com/session/end",
},
});
/**
* The main app scaffold
*/
function App() {
return (
<TokenProvider>
<Authenticate />
</TokenProvider>
);
}
const Token = React.createContext<string | null>(null);
/**
* Provide the access token from the session to the app
*/
function TokenProvider({ children }: React.PropsWithChildren<{}>) {
const [token, setToken] = React.useState<string | null>(null);
React.useEffect(() => session.onChange(setToken), []);
return <Token.Provider value={token}>{children}</Token.Provider>;
}
/**
* Display a login or logout button
*/
function Authenticate() {
const token = React.useContext(Token);
return token !== null ? (
<button onClick={() => session.login()}>Login</button>
) : (
<button onClick={() => session.logout()}>Logout</button>
);
}