Skip to content

Instantly share code, notes, and snippets.

@mlangenberg
Created October 24, 2011 20:47
Show Gist options
  • Save mlangenberg/1310205 to your computer and use it in GitHub Desktop.
Save mlangenberg/1310205 to your computer and use it in GitHub Desktop.
var chatData = JSON.stringify({
timestamp: (currentDate.getTime() - currentDate.getMilliseconds()) / 1000
, chat: {
employee_id: employeeId
, created_at: chat.created_at
, username: chat.chatname
, message: chat.message
}
});
var chatString = JSON.stringify({
data: chatData,
signature: self.signData(chatData)
});
var chatToken = new Buffer(chatString, 'utf-8').toString('base64');
Jeffrey.prototype.signData = function(data) {
var self = this;
return crypto.createHash('sha256').update(new Buffer(data + self.settings.private_salt)).digest("hex");
}
Jeffrey.prototype.getDataFromToken = function(token) {
var self = this;
var json = JSON.parse(new Buffer(token, 'base64').toString('utf-8'));
if (json.signature == self.signData(json.data)) {
var data = JSON.parse(json.data);
var tokenDate = new Date(data['timestamp'] * 1000);
var expirationDate = new Date(new Date() - 7 * 24 * 3600 * 1000);
if (tokenDate > expirationDate) {
return data;
}
return false;
}
}
class JeffreyToken
def self.get_token_for_employee(employee, options = {})
current_time = options[:current_time] || Time.now
data = {
:employee_id => employee.id,
:chatname => employee.chatname,
:timestamp => current_time.to_i,
}.to_json
signature = sign(data)
json = { :data => data, :signature => signature }.to_json
[json].pack("m").gsub("\n", '')
end
def self.get_data_from_token(token)
raise InvalidToken if token.blank?
json = ActiveSupport::JSON.decode(token.unpack("m").first)
if json['signature'] == sign(json['data'])
data = ActiveSupport::JSON.decode(json['data'])
if data['timestamp'].to_i > 1.week.ago.to_i
return data
end
end
raise InvalidToken
end
private
def self.sign(data)
Digest::SHA256.hexdigest(data + Rails::Jeffrey['shared_password'])
end
class InvalidToken < StandardError; end;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment