Last active
August 29, 2015 14:04
-
-
Save dweldon/cbe355b622d54df775a2 to your computer and use it in GitHub Desktop.
Leaderboard with ip-based vote restriction.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Players = new Meteor.Collection("players"); | |
IPs = new Meteor.Collection('ips'); | |
if (Meteor.isClient) { | |
Template.leaderboard.players = function () { | |
return Players.find({}, {sort: {score: -1, name: 1}}); | |
}; | |
Template.leaderboard.selected_name = function () { | |
var player = Players.findOne(Session.get("selected_player")); | |
return player && player.name; | |
}; | |
Template.player.selected = function () { | |
return Session.equals("selected_player", this._id) ? "selected" : ''; | |
}; | |
Template.leaderboard.events({ | |
'click input.inc': function() { | |
var playerId = Session.get('selected_player'); | |
Meteor.call('givePoints', playerId, function(err) { | |
if (err) | |
alert(err.reason); | |
}); | |
} | |
}); | |
Template.player.events({ | |
'click': function () { | |
Session.set("selected_player", this._id); | |
} | |
}); | |
} | |
// On server startup, create some players if the database is empty. | |
if (Meteor.isServer) { | |
Meteor.methods({ | |
givePoints: function(playerId) { | |
check(playerId, String); | |
// we want to use a date with a 1-day granularity | |
var startOfDay = new Date; | |
startOfDay.setHours(0, 0, 0, 0); | |
// the IP address of the caller | |
ip = this.connection.clientAddress; | |
// check by ip and date (these should be indexed) | |
if (IPs.findOne({ip: ip, date: startOfDay})) { | |
throw new Meteor.Error(403, 'You already voted!'); | |
} else { | |
// the player has not voted yet | |
Players.update(playerId, {$inc: {score: 5}}); | |
// make sure she cannot vote again today | |
IPs.insert({ip: ip, date: startOfDay}); | |
} | |
} | |
}); | |
Meteor.startup(function () { | |
if (Players.find().count() === 0) { | |
var names = ["Ada Lovelace", | |
"Grace Hopper", | |
"Marie Curie", | |
"Carl Friedrich Gauss", | |
"Nikola Tesla", | |
"Claude Shannon"]; | |
for (var i = 0; i < names.length; i++) | |
Players.insert({name: names[i], score: Math.floor(Random.fraction()*10)*5}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment