-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.tsx
More file actions
111 lines (93 loc) · 3.07 KB
/
page.tsx
File metadata and controls
111 lines (93 loc) · 3.07 KB
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
"use client";
import { Suspense, useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import { jwtDecode } from "jwt-decode";
import Loader from "@/app/react-contact-form/components/loader";
const LINKEDIN_CLIENT_ID = process.env.NEXT_PUBLIC_LINKEDIN_CLIENT_ID;
function Search({
setCode,
setLoading,
}: {
setCode: (code: string) => void;
setLoading: (loading: boolean) => void;
}) {
const searchParams = useSearchParams();
const code = searchParams.get("code") as string;
if (code) {
setCode(code);
setLoading(true);
}
return <></>;
}
const getUserInfo = async (code: string) => {
const response = await fetch(`/.netlify/functions/linkedin-authorization`, {
method: "POST",
body: JSON.stringify({
code,
}),
});
const data = await response.json();
sessionStorage.setItem("linkedin_jwt_token", data.id_token);
};
export default function Page() {
const [code, setCode] = useState("");
const [userInfo, setUserInfo] = useState("");
const [loading, setLoading] = useState(false);
const getAuthorizationClickHandler = async (event: {
preventDefault: () => void;
}) => {
event.preventDefault();
const callback = encodeURIComponent(
`${location.origin}${location.pathname}`
);
window.location.replace(
`https://api.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${LINKEDIN_CLIENT_ID}&redirect_uri=${callback}&scope=profile%20email%20openid`
);
};
useEffect(() => {
if (!code) {
return;
}
getUserInfo(code).then(() => {
const locationWithoutCode = location.origin + location.pathname;
window.location.replace(locationWithoutCode);
});
}, [code]);
useEffect(() => {
const jwt = sessionStorage.getItem("linkedin_jwt_token");
if (!jwt) {
return;
}
setUserInfo(jwtDecode(jwt) as unknown as string);
}, []);
return (
<div style={{ maxWidth: 400, margin: "0 auto", padding: 12 }}>
<h1 style={{ marginBottom: 20, textAlign: "center" }}>
LinkedIn Access Token in 10 Steps
</h1>
{!userInfo && (
<a
href=""
onClick={getAuthorizationClickHandler}
style={{
padding: 20,
border: "1px solid black",
display: "block",
textAlign: "center",
}}
>
Authorize
</a>
)}
<Suspense>
<Search setCode={setCode} setLoading={setLoading} />
</Suspense>
<div>
<pre>{userInfo && JSON.stringify(userInfo, null, 2)}</pre>
</div>
<div style={{ marginTop: 20, width: "100%", textAlign: "center" }}>
{loading && <Loader />}
</div>
</div>
);
}