"use strict";
// load modules
var async = require("async");
var crypto = require("crypto");
var Redis = require("redis");

var rds = Redis.createClient();

// init express
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json();

// init fitbit client
var FitbitApiClient = require("fitbit-node");
var	client = new FitbitApiClient(process.env.FITBIT_CLIENT_ID, process.env.FITBIT_SECERT);
var FITBITSCOPES = 'activity profile weight';

var saveToken = function( user_id, data, cb ){
	var _data = {
		access_token: data.access_token,
		refresh_token: data.refresh_token,
		user_id: data.user_id,
		fitbit_user: data.user_id,
		scope: data.scope,
		expire_ts: Date.now() + ( 1000 * data.expires_in )
	};
	
	rds.hset( "fitbit-subscription-example", user_id, JSON.stringify( _data ), function( err ){
		if( err ){
        port:((redisParameters.port)?(redisParameters.port):6379),
        host:((redisParameters.hostname)?(redisParameters.hostname):'localhost'),
        password:((redisParameters.auth)?(redisParameters.auth.split(":")[1]):null)
    };
    } else {
        throw new Error('Unable to parse as URL enviroment variable of redisUrl '+process.env.redisUrl);
    }
} else {
    var config = {
        port:6379,
        host:'localhost',
        password:null
    };
}

var client=redis.createClient(config.port,config.host);
if(config.password){
    client.auth(config.password,function(err){
        if(err) throw err;
    });
}


exports.set = function (key, value, callback, ttlInMs) {
    client.set('express-view-cache-'+key,value,function(err){
        if(err){
            callback(err);
        } else {
            var ttlInSecond=Math.floor((ttlInMs/1000));
            // i know of
            // http://redis.io/commands/pexpireat
Example #3
0
    init: function(callback) {
        _.bindAll(this, "loadModels");

        var redis = redis_lib.createClient(
            parseInt(this.options.UNHANGOUT_REDIS_PORT),
            this.options.UNHANGOUT_REDIS_HOST
        );
        this.users = new models.ServerUserList();
        this.events = new models.ServerEventList();
        this.permalinkSessions = new models.ServerSessionList();

        // Users keep a cache of events they admin. Update this cache on any
        // relevant changes to events.
        this.events.on("change:admins add remove", _.bind(function(event) {
            var prev, i, user, admins;
            admins = event.get("admins");
            prev = event.previous("admins") || [];
            for (i = 0; i < prev.length; i++) {
                user = event.findAdminAsUser(prev[i], this.users);
                if (user) {
                    delete user.adminCache[event.id];
                }
            }
            for (i = 0; i < admins.length; i++) {
                user = event.findAdminAsUser(prev[i], this.users);
                if (user) {
                    user.adminCache[event.id] = true;
                }
            }
        }, this));
        this.users.on("add", _.bind(function(user) {
            user.adminCache = {};
            this.events.each(function (event) {
                if (event.userIsAdmin(user)) {
                    user.adminCache[event.id] = true;
                }
            });
        }, this));

        redis.auth(this.options.UNHANGOUT_REDIS_PASSWORD);
        redis.on("end", function() { logger.warn("redis end"); });
        redis.on("error", function(err) { logger.error("redis error: ", err); });
        redis.on("ready", function() { logger.info("redis ready"); });
        redis.once("ready", _.bind(function(err) {
            if (err) {
                logger.error("Error connecting to redis: " + err);
                this.emit("error", "Error connecting to redis: " + err);
                return callback && callback(err);
            }
            
            redis.select(this.options.UNHANGOUT_REDIS_DB, _.bind(function() {
                sync.init(logger, redis);
                sync.setPersist(this.options.persist);
                this.loadModels(_.bind(function(err) {
                    if (err) {
                        logger.error("Error loading models from redis: " + err);
                    } else {
                        logger.info("Loaded " + this.users.length + " users from redis.");
                        logger.info("loaded " + this.events.length + " events from redis.");
                        var counter = 0;
                        this.events.each(function(event) {
                            counter += event.get("sessions").length;
                        });
                        logger.info("Loaded " + counter + " sessions from redis.");
                        this.emit("inited");
                    }
                    callback && callback(err);
                }, this));
            }, this));
        }, this));
        this.redis = redis;

    },
Example #4
0
var redis = require('redis');
var db = redis.createClient();

module.exports = Entry;

// glom attributes
function Entry(obj) {
  for (var key in obj) {
    this[key] = obj[key];
  }
}

Entry.prototype.save = function(fn){
  var entryJSON = JSON.stringify(this);

  db.lpush(
    'entries',
    entryJSON,
    function(err) {
      if (err) return fn(err);
      fn();
    }
  );
};

Entry.getRange = function(from, to, fn){
  db.lrange('entries', from, to, function(err, items){
    if (err) return fn(err);
    var entries = [];

    items.forEach(function(item){
var conf = require('../loop/config').conf;
var async = require('async');
var redis = require("redis");

var storage = conf.get("storage");

if (storage.engine === "redis") {
  var options = storage.settings;
  var client = redis.createClient(
    options.port,
    options.host,
    options.options
  );
  if (options.db) client.select(options.db);

  client.keys("userUrls.*", function(err, keys){
    if (err) throw err;
    console.log("processing", keys.length, "users");

    var multi = client.multi();
    keys.forEach(function(key) {
      multi.scard(key);
    });
    multi.exec(function(err, results) {
      if (err) throw err;
      var totalUrls = results.reduce(function(total, result) {
        return total + result;
      }, 0);
      process.stdout.write(totalUrls + " URLs for " +
                           keys.length + " users.\nAverage " +
                           (totalUrls / keys.length).toFixed(2) +
Example #6
0
    dumpExceptions: true,
    showStack: true
  }));
});
// specific to production
app.configure('production', function () {
  app.use(express.errorHandler());
});

// Configure Redis client
var redisOptions = {
  maxReconnectionAttempts: 10,
  parser: 'javascript',
  return_buffer: false
};
redisClient = redis.createClient(6379, '127.0.0.1', redisOptions);
var pub = redis.createClient(6379, '127.0.0.1', redisOptions);
var sub = redis.createClient(6379, '127.0.0.1', redisOptions);
var conn = io.listen(app);
Sync.config({
  io: conn,
  database: redisClient,
  publish: pub,
  subscribe: sub
});

// start listening
if (!module.parent) {
  app.listen(80);
  console.log("Express server listening on port %d", app.address().port);
}
Example #7
0
var redis = require('redis');
var client = redis.createClient();

function addToDb(score, name) {
    client.ZADD('drag race contestants', score, name, function(err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log(reply);
        }
    });
}

function getData(callback) {
    client.ZRANGE('drag race contestants', 0, -1, function(err, reply) {
        if (err) {
            console.log(err);
        } else {
            callback(reply);
        }
    });
}

module.exports = {
    addToDb: addToDb,
    getData: getData
};
Example #8
0
 create: function(callback) {
     var redis = require('redis');
     var client = redis.createClient(redisConfig.port, redisConfig.host);
     callback(null, client);
 },
Example #9
0
var config = require('./configuration');
var mailin = require('mailin');
var mongo = require('./lib/mongo');
var db = new mongo();
var async = require('async');
var redis = require('redis');
var redisConfig = config.redis;
var redisClient = redis.createClient(redisConfig.port, redisConfig.host);

/* Start the Mailin server. The available options are:
 *  options = {
 *     port: 25,
 *     webhook: 'http://mydomain.com/mailin/incoming,
 *     disableWebhook: false,
 *     logFile: '/some/local/path',
 *     logLevel: 'warn', // One of silly, info, debug, warn, error
 *     smtpOptions: { // Set of options directly passed to simplesmtp.createServer(smtpOptions)
 *        SMTPBanner: 'Hi from a custom Mailin instance'
 *     }
 *  };
 * Here disable the webhook posting so that you can do what you want with the
 * parsed message. */
mailin.start({
    port: 25,
    disableWebhook: true, // Disable the webhook posting.
    logFile:'/usr/local/mailtest/log.txt',
    logLevel:'warn',
    disableSpamScore:true // ½ûÓÃSpam
});

/* Access simplesmtp server instance. */
Example #10
0
    server: "irc.freenode.net",
    botName: "credits-bot"
};

var irc = require('irc');

var bot = new irc.Client(config.server, config.botName, {
    channels: config.channels,
    userName: config.botName
});

var nr = require('newrelic');
var redis = require('redis');
var url = require('url');
var redisURL = url.parse(process.env.REDISCLOUD_URL);
var client = redis.createClient(redisURL.port, redisURL.hostname, {no_ready_check: true});
client.auth(redisURL.auth.split(":")[1]);
var Leaderboard = require('leaderboard');
var plus_lb = new Leaderboard('pluses', {}, client);

var users = [];

bot.addListener("message", function(nick, to, text, message) {
    var words = text.replace(/[^\w\d-+=]/, "").split(" ");
    var credits = words[0].split("+=");
    var numCredits = parseInt(credits[1]);
    var plusReceiver;

    if (!isNaN(numCredits) && numCredits > 0) {
        console.log("credits[0]: " + credits[0]);
        for (var i = users.length - 1; i >= 0; --i) {
Example #11
0
var clients = [],
	http = require('http'), 
	url = require('url'), 
	fs = require('fs'), 
	querystring = require('querystring'),
	qrcode = require('qrcode'), 
	UUID = require('uuid-js'), 
	sha1 = require('sha1'), 
	redis = require('redis'), 
	redisClient = redis.createClient(), 
	redisKey = 'QRCODE_LOGIN_TOKEN';

function generateIndex(sessionID, req, res) {
	fs.readFile('./index.html', 'UTF-8', function(err, data) {
		data = data.replace(/SESSIONID/g, sessionID);
		res.writeHead(200, {
			'Content-Type' : 'text/html; charset=UTF-8'
		});
		res.end(data);
	});
}

function generateQRCode(sessionID, req, res) {
	res.writeHead(200, {
		'Content-Type' : 'image/png'
	});
	qrcode.draw(sessionID, function(err, canvas) {
		res.end(canvas.toBuffer());
	});
} 
Example #12
0
function createClient(port, host, pass) {
    var client = redis.createClient(port, host);
    client.auth(pass);
    return client;
}
Example #13
0
var redis = require("redis"),
	client_pub = redis.createClient(6379,'127.0.0.1'),
	client_sub = redis.createClient(6379,'127.0.0.1');

client_sub.on('pmessage', function (pattern, channel,message) {
	console.log(channel,message);
	// TO:FROM:RESPONSEID:FUNC:OPTIONS
	var param = channel.split(':');
	var from 	= param[1]
	  ,  rID	= param[2]
	  , func	= param[3];
	  
	if( param[2] == "SAVE_MAP"){
		if(param[3] == "START"){
			client_pub.publish('DATA:'+USERID+':SAVE_MAP:START', JSON.stringify(message));
			client_sub.subscribe('DATA:'+USERID+':SAVE_MAP:DONE');
		}else{
			client_pub.publish('EDITOR:'+USERID+':SAVE_MAP:DONE', JSON.stringify({result:'OK'}));
			client_sub.unsubscribe(channel);
		}
	}else if( param[2] == "SAVE_CHARACTER"){
		if(param[3] == "START"){
			client_pub.publish('DATA:'+USERID+':SAVE_CHARACTER:START', JSON.stringify(message));
			client_sub.subscribe('DATA:'+USERID+':SAVE_CHARACTER:DONE');
		}else{
			client_pub.publish('EDITOR:'+USERID+':SAVE_CHARACTER:DONE', JSON.stringify({result:'OK'}));
			client_sub.unsubscribe(channel);
		}
	}
});
client_sub.on('psubscribe' , function (channel, message) {
Example #14
0
#!/usr/bin/env node

var redis = require('redis');
var url = require('url');

var apuesta = require("./Apuesta.js"),
porra = require("./Porra.js");

var redisURL = url.parse(process.env.REDISCLOUD_URL);
var client = redis.createClient(redisURL.port, redisURL.hostname, {no_ready_check: true, auth_pass: redisURL.auth.split(":")[1]});

var esta_porra = new porra.Porra("FLA", "FLU", "Premier", 1950+Math.floor(Math.random()*70) );
console.log(esta_porra);
for ( var i in esta_porra.vars() ) {
    client.hset(esta_porra.ID, "var:"+esta_porra.vars()[i], esta_porra[i], redis.print);
}

var bettors = ['UNO', 'OTRO','OTROMAS'];

for ( var i in bettors ) {
    var esta_apuesta = new apuesta.Apuesta(esta_porra, bettors[i], Math.floor(Math.random()*5), Math.floor(Math.random()*4) );
    client.hset(esta_porra.ID, "bet:"+esta_apuesta.quien, esta_apuesta.resultado());
    client.sadd(esta_porra.ID+":"+esta_apuesta.resultado(), esta_apuesta.quien,redis.print );
    
}

client.hkeys(esta_porra.ID, function (err, replies) {
    console.log( 'hkeys');
    replies.forEach(function (reply, i) {
        console.log("    " + i + ": " + reply);
    });
Example #15
0
Redis.prototype.stream = function (options) {
  var self = this,
      options = options || {},
      stream = new Stream,
      container = this.container(options),
      channel = this.channel(options);

  stream.destroy = function () {
    if (this.destroyed) return;

    this.destroyed = true;

    var i = self.subscription.__channels[channel].indexOf(message);
    if (~i) self.subscription.__channels[channel].splice(i, 1);

    if (!self.subscription.__channels[channel].length) {
      self.subscription.punsubscribe(channel);
      delete self.subscription.__channels[channel];
    }

    if (!Object.keys(self.subscription.__channels).length) {
      try {
        self.subscription.end();
        self.subscription.stream.destroy();
      } catch (e) {
        ;
      }
      delete self.subscription;
    }
  };

  if (!this.subscription) {
    this.subscription = redis.createClient(
      this.redis.options.host,
      this.redis.options.port
    );
    this.subscription.__channels = {};
    this.subscription.on('pmessage', function (pattern, channel, message) {
      var listeners = self.subscription.__channels[pattern];
      if (!listeners) return;
      listeners.forEach(function (listener) {
        listener.call(self.subscription, pattern, channel, message);
      });
    });
  }

  if (!this.subscription.__channels[channel]) {
    this.subscription.psubscribe(channel);
    this.subscription.__channels[channel] = [];
  }

  this.subscription.__channels[channel].push(message);

  function message(pattern, channel, message) {
    if (stream.destroyed) return;

    try {
      message = JSON.parse(message);
    } catch (e) {
      return stream.emit('error',
        new Error('Could not parse: "' + message + '".'));
    }

    stream.emit('log', message);
  }

  if (options.start === -1) {
    delete options.start;
  }

  if (options.start == null) {
    return stream;
  }

  this.redis.lrange(container, options.start, -1, function (err, results) {
    if (stream.destroyed) return;

    if (err) {
      return stream.emit('error', err);
    }

    results.forEach(function (log) {
      try {
        stream.emit('log', JSON.parse(log));
      } catch (e) {
        return stream.emit('error',
          new Error('Could not parse: "' + log + '".'));
      }
    });
  });

  return stream;
};
/**
 * Module dependencies.
 */
var express = require('express');
var querystring = require('querystring');
var i18n = require("i18n");

var config = require('./config');
var errors = require('./error');
var utils = require('./utils');

var RedisStore = require('connect-redis')(express);
var redis = require('redis'), redisClient = redis.createClient();

var app = null;
if (config.https.enabled) {
  var fs = require("fs");
  var privateKey = fs.readFileSync(config.https.key);
  var certificate = fs.readFileSync(config.https.cert);
  app = module.exports = express.createServer({ key: privateKey, cert: certificate });
} else {
  app = module.exports = express.createServer();
}

var session = express.session({ secret: config.sessionSecret, store: new RedisStore() });

i18n.configure({
    locales: ['en', 'cs', 'de']
});

// Configuration
Example #17
0
'use strict';

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var socketio = require('socket.io');

var app = express();
var redis = require('redis');
var client = redis.createClient();

var port = process.env.PORT;

app.set('port', port || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.logger('short'));
app.use(express.bodyParser());
app.use(app.router);

if (app.env === 'development') {
  app.use(express.errorHandler()); 
}

app.get('/', routes.index);
app.post('/createUser', routes.createUser);
app.post('/checkUser', routes.checkUser);
app.post('/deleteFile', routes.deleteFile);
Example #18
0
Node.prototype.connect = function() {
  var self = this;
  this.setStatus('initializing');
  this.client = redis.createClient(this.port, this.host, this.options);
  if (this.auth_pass) {
    this.client.auth(this.auth_pass);
  }
  this.clients.push(this.client);
  this.client.on('error', function(err) {
    self.emit('error', err);
  });
  this.client.on('end', function() {
    if (!this.closing) {
      self.setStatus('reconnecting');
      // Client connection closed without quit(). If reconnection fails, the
      // node is considered down.
      setTimeout(function waitForReconnect() {
        if (!self.client.connected) {
          self.emit('error', new Error(self + ' connection dropped and reconnection failed!'));
          self.setStatus('down');
        }
      }, Math.floor(this.retry_delay * this.retry_backoff * 2));
    }
  });
  this.client.on('connect', function() {
    if (self.options.single_mode) {
      // No failover possible, don't check for slave-read-only
      self.setStatus('up');
    }
    else {
      self.client.CONFIG('GET', 'slave-read-only', function(err, reply) {
        if (err) {
          return self.emit('error', err);
        }
        if (reply[1] !== 'yes') {
          self.setStatus('up');
        }
        else {
          console.warn('WARNING! ' + self + ' has slave-read-only mode ON, which breaks haredis failover! slave-read-only automatically turned OFF.');
          self.client.CONFIG('SET', 'slave-read-only', 'no', function(err, reply) {
            if (err) {
              return self.emit('error', err);
            }
            self.setStatus('up');
          });
        }
      });
    }
  });
  this.client.on('monitor', function(time, args) {
    self.emit('monitor', time, args);
  });

  // Maintain a separate pub/sub client.
  this.subClient = redis.createClient(this.port, this.host, this.options);
  if (this.auth_pass) {
    this.subClient.auth(this.auth_pass);
  }
  this.clients.push(this.subClient);
  this.subClient.on('error', function(err) {
    self.emit('error', err);
  });
  this.subClient.on('connect', function() {
    // UGLY HACK: node_redis does not restore pub/sub subscriptions correctly upon
    // reconnect. In fact, the client crashes! Resubscription will be handled at the RedisHAClient level.
    // @see https://github.com/mranney/node_redis/issues/191
    this.subscribe('haredis:gossip:master');
    this.subscription_set = {};
  });

  // Subtract 1 from all counts, for the gossip channel we've set up.
  this.subClient.on('subscribe', function(channel, count) {
    self.emit('subscribe', channel, count - 1);
  });
  this.subClient.on('unsubscribe', function(channel, count) {
    self.emit('unsubscribe', channel, count - 1);
  });
  this.subClient.on('message', function(channel, message) {
    self.emit('message', channel, message);
  });
  this.subClient.on('psubscribe', function(pattern, count) {
    self.emit('psubscribe', pattern, count - 1);
  });
  this.subClient.on('punsubscribe', function(pattern, count) {
    self.emit('punsubscribe', pattern, count - 1);
  });
  this.subClient.on('pmessage', function(pattern, channel, message) {
    self.emit('pmessage', pattern, channel, message);
  });
};
Example #19
0
/**
* UserController
*
* @description :: Server-side logic for managing users
* @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var redis = require('redis');
var client = redis.createClient(6379, '127.0.0.1');

module.exports = {
  create:function(req,res){
    User.create({firstname:req.body['first_name'],lastname:req.body['last_name'],email:req.body['email'],password:req.body['password'],confirmpassword:req.body['password']}).exec(function createCB(err, created){
      if(err){
        console.log(err)
        res.send({success:false});
      }
      else
      {
        req.session.id = created.id;
        console.log(req.session.id)
        res.send({success:true});
      }
    });
  },
  signin:function(req,res){
    User.findOne({
      email:req.body['email'],
      password:req.body['password']
    }).exec(function (err, data){
      if (err) {
        return res.negotiate(err);
 return hosts.map(function(config) {
     return redis.createClient(config.port, config.host, {retry_max_delay: 1000});
 });
Example #21
0
/**
 * Created with JetBrains WebStorm.
 * User: hanqingnan
 * Date: 13-1-28
 * Time: 上午4:38
 * To change this template use File | Settings | File Templates.
 */
var redis = require("redis");
var test = require("./test");
var config = require("../config/config.json");


var testEvent = test.createMangerFactory();


var redisClient = redis.createClient(config.redis.port, config.redis.host);

/**
 * ready events
 */
redisClient.once("ready", function(){
    console.log("redis server is ready!");
    testEvent.emit("ready");//发出ready事件
});

testEvent.once("ready", function(){
    console.log("manager events test");
});
Example #22
0
exports.connect = function(settings){
    redis = redisAdapter.createClient(settings.port, settings.host);
    redis.on("error", console.log);
    updateInfo.startUpdatingInfo();
};
Example #23
0
var redis   = require('redis')
  , utils   = require('./utils')
  ;

var connectionRedis = redis.createClient();

var tot = 40
  , nb  = 0;
connectionRedis.on('ready', function(err) {
  if (err) console.log('ERROR redis ready : ' + err);
  else { // ready
    for (var i=0; i<=tot; i++) {
      (function(e) {
        var r = fib(e);
        connectionRedis.set('fib:'+e, r, function(err,res) {
          if (err) console.error('error : ' + err);
          else console.log('res redis fib : ' + res);
          nb++;
          if (nb == tot) console.log('Fib into Redis: finished');
        });
      })(i);
    }
  }
});
connectionRedis.on("error", function (err) {
  console.log("RedisClient Error : " + err);
}); 

var fib = function fibb(n) {
  if (n < 2) {
    return 1;
Example #24
0
describe('redis', function () {
	var redis	= require('redis')
	,	client	= redis.createClient()
	,	engine	= require(__dirname + '/../../../lib/store/redis')({
			"ttl": 1000 //set TTL to 1 second
		})
	;
	
	beforeEach(function (done) {
		client.flushdb(function () {
			client.multi()
			.set('ROOT.buzz', JSON.stringify('foo'))
			.set('ROOT.biz', JSON.stringify('bar'))
			.exec(done);
		});
	});
	
	describe('#put', function () {
		it('should add the given value to the given key', function (done) {
			engine.put('blah', 'baz', function (err, success) {
				success.should.be.ok;
				
				client.get('ROOT.baz', function (err, reply) {
					should.not.exist(err);
					reply.should.eql(JSON.stringify('blah'));
					
					client.ttl('ROOT.baz', function (err, reply) {
						reply.should.be.within(0,1);
						done();
					});
				});
			});
		});
	});
	
	describe('#get', function () {
		it('should given a null value for a non existant key', function (done) {
			engine.get('bar', function (err, value) {
				should.not.exist(value);
				done();
			});
		});
		it('should give back the proper value for an existing key', function (done) {
			engine.get('buzz', function (err, value) {
				should.exist(value);
				value.should.eql('foo');
				done();
			});
		});
		it('should be able to return a JSON object.', function (done) {
			var value	= {
				'test': "This a test",
				"nested": {
					"nest_test": "boo"
				}
			};
			engine.put(value, 'blah', function (err) {
				should.not.exist(err);
				
				engine.get('blah', function (err, reply) {
					should.not.exist(err);
					reply.should.eql(reply);
					done();
				});
			});
			
		});
	});
	
	describe('#del', function () {
		it("should remove the given key from the store", function (done) {
			engine.del("buzz", function (err, success) {
				should.not.exist(err);
				success.should.be.ok;
				
				client.exists("buzz", function (err, reply) {
					should.not.exist(err);
					reply.should.not.be.ok;
					done();
				});
			});
		});
	});
	
	describe ('#clear', function () {
		it("should clear the current cache", function (done) {
			engine.clear(function (err, success) {
				success.should.be.ok;
				client.dbsize(function (err, reply) {
					should.not.exist(err);
					reply.should.eql(0);
					done();
				});
			});
		});
	});
});
Example #25
0
var express = require('express');
var path = require('path');
var redis = require('redis');
var favicon = require('serve-favicon');
var logger = require('morgan');
var CookieParser = require('cookie-parser');
var SECRET = 'hellonihao';
var COOKIENAME = 'hello';
var cookieParser = CookieParser(SECRET);
var bodyParser = require('body-parser');
var ExpressSession = require('express-session');
var connectRedis = require('connect-redis');
var RedisStore = connectRedis(ExpressSession);
var rClient = redis.createClient();
var sessionStore = new RedisStore({client: rClient});

var app = express();
var session = ExpressSession({
  store: sessionStore,
  secret: SECRET,
  resave: true,
  saveUninitialized: true
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.json());
Example #26
0
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var faye = require('faye');
var redis = require('redis');
var url = require('url');
var crypto = require('crypto');

var app = express();
var server = http.createServer(app);
var db = redis.createClient(6379, 'acm.tpu.ru');
var bayeux = new faye.NodeAdapter({mount: '/game', timeout: 45});
var ajax = '*'; //for debug purposes, CHANGE IN PRODUCTION

app.use(bodyParser.urlencoded({ extended: false }));

function onAuth(request, response)
{
	var name = request.param('name');
	var password = request.param('password');
	response.setHeader('Access-Control-Allow-Origin', ajax);
	if(name == null || name == "" || password == null || password == "")
		return response.status(400).send('Bad request');
	db.hget('users', name, function(err, id){
		if(err) throw err;
		if(id == null)
		{
			return response.status(401).send('Invalid username/password');
		}
		else
		{
Example #27
0
'use strict';

const express = require('express');
const redis = require('redis');
const bodyParser = require('body-parser');

// Constants
const PORT = 8080;

// collaborators
var client = redis.createClient('6379', 'store');
var sclient = redis.createClient('6379', 'store'); // subscription only

// awaiting service
var queue = [];

sclient.on('message', function(channel,message){
  fetch(function(err, curval) {
    if (err) return;
    var jent = JSON.stringify(curval);
    for (var i=0; i<queue.length; ++i) {
      queue[i].setHeader('Content-Type', 'application/json');
      queue[i].send(jent);
    }
    queue.length = 0;
  });
});
sclient.subscribe('motd');

var entity = function(serial, message) {
  return {"serial":serial, "message":message};
Example #28
0
var express = require('express');
var router = express.Router();
var request = require('request');

var redis = require('redis');

if (process.env.REDISTOGO_URL) {
  var rtg   = require('url').parse(process.env.REDISTOGO_URL);
  var client = redis.createClient(rtg.port, rtg.hostname);

  client.auth(rtg.auth.split(':')[1]);
} else {
  var client = redis.createClient();
}

client.on('connect', function() {
  console.log('connected to redis');
});

var listExists = false;

router.post('/', function(req, res) {

  var rbody = req.body,
    trigger = rbody.trigger_word,
    item = rbody.text.replace(new RegExp(trigger, 'gi'), '').trim(),
    channelId = rbody.channel_id,
    userId = rbody.user_id,
    userName = rbody.user_name,

    // Post item to list
Example #29
0
  , Checkin = require("./api/checkin");

//
// Setup Express and socket.io
//
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//io.set('transports', ['xhr-polling']);
io.set('log level', 1);

//
// Use Redis as the session store
//
var RedisStore = require('connect-redis')(express),
  redisClient = redis.createClient(),
  sessionStore = new RedisStore({client: redisClient});

//
// Configure the Express application
//
var cookieParser = express.cookieParser('secret');

app.configure(function() {
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger('dev'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.favicon());
  app.use(express.bodyParser());
Example #30
0
app.use(bodyParser());

if(config.username && config.password) {
  app.use(basicAuth(config.username, config.password));
}

process.on('exit', function() {
  for (var id in cluster.workers) {
    cluster.workers[id].kill();
  }
});

var components = url.parse(config.redisUrl);

var client = redis.createClient(components.port || 6379, components.hostname || "localhost", {
  auth_pass: (components.auth) ? ((components.auth.split(':').length > 1) ? components.auth.split(':')[1] : components.auth) : undefined
});

client.on('error', function(err) {
  console.warn('ERROR:', err);
});

var prefixesQueues = [];
var confQueues = [];

function refresh(cb) {
  client.keys("*:ids", function(err, keys) {
    if(err) {
      return cb(err);
    }