This repository was archived by the owner on Feb 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathethereumAuth.js
More file actions
96 lines (86 loc) · 2.31 KB
/
ethereumAuth.js
File metadata and controls
96 lines (86 loc) · 2.31 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
import { AuthenticationError } from '@redwoodjs/api'
import { bufferToHex } from 'ethereumjs-util'
import { recoverPersonalSignature } from 'eth-sig-util'
import jwt from 'jsonwebtoken'
import { db } from 'src/lib/db'
const NONCE_MESSAGE =
'Please prove you control this wallet by signing this random text: '
const getNonceMessage = (nonce, options) => {
let optionsText = ''
if (options)
optionsText =
'&' +
Object.keys(options)
.map(
(key) =>
encodeURIComponent(key) + '=' + encodeURIComponent(options[key])
)
.join('&')
return NONCE_MESSAGE + nonce + optionsText
}
export const beforeResolver = (rules) => {
rules.skip({ only: ['authChallenge', 'authVerify'] })
}
export const authChallenge = async ({
input: { address: addressRaw, options },
}) => {
const nonce = Math.floor(Math.random() * 1000000).toString()
const address = addressRaw.toLowerCase()
await db.user.upsert({
where: { address },
update: {
authDetail: {
update: {
nonce,
timestamp: new Date(),
},
},
},
create: {
address,
authDetail: {
create: {
nonce,
},
},
},
})
return { message: getNonceMessage(nonce, options) }
}
export const authVerify = async ({
input: { signature, address: addressRaw, options },
}) => {
try {
const address = addressRaw.toLowerCase()
const user = await db.user.findUnique({
where: { address },
})
if (!user) throw new Error('No authentication started')
const { nonce, timestamp } = await db.user
.findUnique({
where: { address },
})
.authDetail()
const startTime = new Date(timestamp)
if (new Date() - startTime > 5 * 60 * 1000)
throw new Error(
'The challenge must have been generated within the last 5 minutes'
)
const signerAddress = recoverPersonalSignature({
data: bufferToHex(Buffer.from(getNonceMessage(nonce, options), 'utf8')),
sig: signature,
})
if (address !== signerAddress.toLowerCase())
throw new Error('invalid signature')
const token = jwt.sign(
{ address, id: user.id },
process.env.ETHEREUM_JWT_SECRET,
{
expiresIn: '5h',
}
)
return { token }
} catch (e) {
throw new Error(e)
}
}