-
Notifications
You must be signed in to change notification settings - Fork 94
/
redis-nonce-store.coffee
45 lines (31 loc) · 1.38 KB
/
redis-nonce-store.coffee
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
NonceStore = require './nonce-store'
# Five minutes
EXPIRE_IN_SEC = 5*60
class RedisNonceStore extends NonceStore
constructor: (redisClient) ->
if typeof redisClient is 'string' and arguments.length is 2
redisClient = arguments[1]
@redis = redisClient
isNew: (nonce, timestamp, next=()->)->
if typeof nonce is 'undefined' or nonce is null or typeof nonce is 'function' or typeof timestamp is 'function' or typeof timestamp is 'undefined'
return next new Error('Invalid parameters'), false
if typeof timestamp is 'undefined' or timestamp is null
return next new Error('Timestamp required'), false
# Generate unix time in seconds
currentTime = Math.round(Date.now()/1000)
# Make sure this request is fresh (within the grace period)
freshTimestamp = (currentTime - parseInt(timestamp,10)) <= EXPIRE_IN_SEC
if not freshTimestamp
return next new Error('Expired timestamp'), false
# Pass all the parameter checks, now check to see if used
@redis.get nonce, (err, seen) =>
if seen
return next new Error('Nonce already seen'), false
# Dont have to wait for callback b/c it's a sync op
@setUsed nonce, timestamp
next null, true
setUsed: (nonce, timestamp, next=()->)->
@redis.set(nonce, timestamp)
@redis.expire(nonce, EXPIRE_IN_SEC)
next(null)
exports = module.exports = RedisNonceStore