generated from w3hc/another-star
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify.ts
49 lines (40 loc) · 1.67 KB
/
verify.ts
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
import { NextApiRequest, NextApiResponse } from 'next'
import { SiweMessage } from 'siwe'
import { withSessionRoute } from '../../../utils/server'
import { ethers } from 'ethers'
import { NFT_CONTRACT_ADDRESS, NFT_CONTRACT_ABI } from '../../../lib/consts'
export default withSessionRoute(async function handler(req: NextApiRequest, res: NextApiResponse) {
console.log(req.method, '/api/account/verify', req.session)
const verifyNftOwnership = async (addr: any) => {
const provider = new ethers.JsonRpcProvider('https://rpc.arthera.net')
const nft = new ethers.Contract(NFT_CONTRACT_ADDRESS, NFT_CONTRACT_ABI, provider)
const nftBal = await nft.balanceOf(addr)
console.log('nftBal:', nftBal)
if (Number(nftBal) > 0) {
return true
}
}
if (req.method === 'POST') {
try {
const { message, signature } = req.body
const siweMessage = new SiweMessage(message)
const fields = await siweMessage.validate(signature)
if (fields.nonce !== req.session.nonce) return res.status(422).json({ message: 'Invalid nonce.' })
const isNftOwner = await verifyNftOwnership(message.address)
if (!isNftOwner) return res.status(422).json({ message: 'Could not verify the NFT ownership.' })
const secretContent = isNftOwner ? process.env.NEXT_PUBLIC_SECRET : 'oh!'
const responseObj = {
ok: true,
secretContent: secretContent,
}
req.session.siwe = fields
await req.session.save()
return res.json(responseObj)
} catch (ex) {
console.error(ex)
return res.json({ ok: false })
}
}
res.setHeader('Allow', ['POST'])
return res.status(405).end(`Method ${req.method} Not Allowed`)
})