-
Notifications
You must be signed in to change notification settings - Fork 71
/
auth.js
53 lines (41 loc) · 1.42 KB
/
auth.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
var express = require('express');
var moment = require('moment');
var crypto = require('crypto');
var TOKEN_TTL_MINUTES = 60;
var AUTH_SIGN_KEY = '95810db3f765480999a8d5089b0815bd4b55e831';
function createToken(req, res, next) {
var username = req.user.username;
var timespamp = moment();
var message = username + ';' + timespamp.valueOf();
var hmac = crypto.createHmac('sha1', AUTH_SIGN_KEY).update(message).digest('hex');
var token = username + ';' + timespamp.valueOf() + ';' + hmac;
var tokenBase64 = new Buffer(token).toString('base64');
req.token = tokenBase64;
next();
}
function validateToken (req, res, next) {
var basic = express.basicAuth(hmacAuthentication);
return basic(req, res, next);
function hmacAuthentication(user, password) {
var token = new Buffer(password, 'base64').toString();
var parsed = token.split(';');
if (parsed.length !== 3) {
return false;
}
var username = parsed[0], timespamp = parsed[1], recievedHmac = parsed[2];
var message = username + ';' + timespamp;
var computedHmac = crypto.createHmac('sha1', AUTH_SIGN_KEY).update(message).digest('hex');
if (recievedHmac !== computedHmac) {
return false;
}
var currentTimespamp = moment(), recievedTimespamp = moment(+timespamp);
if (currentTimespamp.diff(recievedTimespamp, 'minutes') > TOKEN_TTL_MINUTES) {
return false;
}
return true;
}
}
module.exports = {
createToken: createToken,
validateToken: validateToken
};