-
Notifications
You must be signed in to change notification settings - Fork 45
/
siwe.tsx
78 lines (71 loc) · 1.83 KB
/
siwe.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
import { getCsrfToken, signIn, useSession } from "next-auth/react"
import { SiweMessage } from "siwe"
import { useAccount, useConnect, useNetwork, useSignMessage } from "wagmi"
import Layout from "../components/layout"
import { InjectedConnector } from 'wagmi/connectors/injected'
import { useEffect, useState } from "react"
function Siwe() {
const { signMessageAsync } = useSignMessage()
const { chain } = useNetwork()
const { address, isConnected } = useAccount()
const { connect } = useConnect({
connector: new InjectedConnector(),
});
const { data: session, status } = useSession()
const handleLogin = async () => {
try {
const callbackUrl = "/protected"
const message = new SiweMessage({
domain: window.location.host,
address: address,
statement: "Sign in with Ethereum to the app.",
uri: window.location.origin,
version: "1",
chainId: chain?.id,
nonce: await getCsrfToken(),
})
const signature = await signMessageAsync({
message: message.prepareMessage(),
})
signIn("credentials", {
message: JSON.stringify(message),
redirect: false,
signature,
callbackUrl,
})
} catch (error) {
window.alert(error)
}
}
useEffect(() => {
console.log(isConnected);
if (isConnected && !session) {
handleLogin()
}
}, [isConnected])
return (
<Layout>
<button
onClick={(e) => {
e.preventDefault()
if (!isConnected) {
connect()
} else {
handleLogin()
}
}}
>
Sign-in
</button>
</Layout>
)
}
export async function getServerSideProps(context: any) {
return {
props: {
csrfToken: await getCsrfToken(context),
},
}
}
Siwe.Layout = Layout
export default Siwe