forked from AdamPflug/express-brute-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (71 loc) · 2.2 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var AbstractClientStore = require('express-brute/lib/AbstractClientStore'),
Redis = require('redis'),
_ = require('underscore');
var RedisStore = module.exports = function (options) {
AbstractClientStore.apply(this, arguments);
this.options = _.extend({}, RedisStore.defaults, options);
this.redisOptions = _(this.options).clone();
delete this.redisOptions.prefix;
delete this.redisOptions.client;
delete this.redisOptions.port;
delete this.redisOptions.host;
if (this.options.client) {
this.client = this.options.client;
} else {
this.client = RedisStore.Redis.createClient(
this.options.port,
this.options.host,
this.options.redisOptions
);
}
};
RedisStore.prototype = Object.create(AbstractClientStore.prototype);
RedisStore.prototype.set = function (key, value, lifetime, callback) {
lifetime = parseInt(lifetime, 10) || 0;
var multi = this.client.multi(),
redisKey = this.options.prefix+key;
multi.set(redisKey, JSON.stringify(value));
if (lifetime > 0) {
multi.expire(redisKey, lifetime);
}
var ok = multi.exec(function (err, data) {
typeof callback == 'function' && callback.call(this, null);
});
if (!ok) {
var err = new Error('Failed redis request');
typeof callback == 'function' && callback(err, null);
}
};
RedisStore.prototype.get = function (key, callback) {
var ok = this.client.get(this.options.prefix+key, function (err, data) {
if (err) {
typeof callback == 'function' && callback(err, null);
} else {
if (data) {
data = JSON.parse(data);
data.lastRequest = new Date(data.lastRequest);
data.firstRequest = new Date(data.firstRequest);
}
typeof callback == 'function' && callback(err, data);
}
});
if (!ok) {
var err = new Error('Failed redis request');
typeof callback == 'function' && callback(err, null);
}
};
RedisStore.prototype.reset = function (key, callback) {
var ok = this.client.del(this.options.prefix+key, function (err, data) {
typeof callback == 'function' && callback.apply(this, arguments);
});
if (!ok) {
var err = new Error('Failed redis request');
typeof callback == 'function' && callback(err, null);
}
};
RedisStore.Redis = Redis;
RedisStore.defaults = {
prefix: '',
port: 6379,
host: '127.0.0.1'
};