-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
58 lines (47 loc) · 1.53 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
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
"use strict";
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressJwt = require('express-jwt');
var ethUtil = require('ethereumjs-util');
var sigUtil = require('eth-sig-util');
var jwt = require('jsonwebtoken');
module.exports = {};
module.exports.attach = function(app, secret) {
// Don't accept non-AJAX requests to prevent XSRF attacks.
app.use(function(req, res, next) {
if (!req.xhr) {
res.status(500).send('Not AJAX');
}
else {
next();
}
});
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressJwt({
secret: secret,
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
return req.cookies.token;
}
}).unless({path: ['/sign-in']})
);
app.post('/sign-in', function (req, res) {
console.log(req.body);
var baseUrl = req.protocol + "://" + req.hostname;
var msgParams = {
data: ethUtil.bufferToHex(new Buffer("Sign into " + baseUrl, 'utf8')),
sig: req.body.signed,
};
var recovered = sigUtil.recoverPersonalSignature(msgParams)
if (recovered === req.body.account) {
console.log('SigUtil Successfully verified signer as ' + req.body.account);
var token = jwt.sign({loggedInAs: req.body.account}, secret);
console.log('JWT token: ' + token);
res.cookie('token', token, {domain: 'localhost', httpOnly: true});
res.end();
} else {
console.log('SigUtil unable to recover the message signer');
}
});
}