-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
32 lines (29 loc) · 1.17 KB
/
index.js
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
const jwt = require('jsonwebtoken');
const ethers = require('ethers');
exports.generate = function (address, secret) {
function generateRandomToken(length) {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
let randomToken = generateRandomToken(32);
return jwt.sign({name: "eth-auth token", address: address, randomToken: randomToken}, secret, "", "");
}
exports.validate = async function (token, signature, secret) {
let decodedJwt = jwt.verify(token, secret, "", "");
try {
const signerAddr = ethers.utils.verifyMessage(token, signature);
if (signerAddr === decodedJwt.address) {
return {address: decodedJwt.address, authorized: true, err: null};
} else {
return {address: null, authorized: false, err: "Invalid signature"};
}
} catch (err) {
return {address: null, authorized: false, err: err};
}
}