impress/lib/openneo-auth/session.rb

89 lines
2.3 KiB
Ruby
Raw Normal View History

2010-10-18 14:58:45 -07:00
require 'active_support/core_ext/hash'
require 'msgpack'
require 'openneo-auth-signatory'
2011-06-04 15:40:15 -07:00
require 'utf8'
2010-10-18 14:58:45 -07:00
module Openneo
module Auth
class Session
REMOTE_MSG_KEYS = %w(session_id source user)
TMP_STORAGE_DIR = Rails.root.join('tmp', 'openneo-auth-sessions')
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
attr_writer :id
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def save!
2011-06-04 15:40:15 -07:00
content = +MessagePack.pack(@message)
2010-10-18 14:58:45 -07:00
FileUtils.mkdir_p TMP_STORAGE_DIR
File.open(tmp_storage_path, 'w') do |file|
2011-06-04 15:40:15 -07:00
file.write content
2010-10-18 14:58:45 -07:00
end
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def destroy!
File.delete(tmp_storage_path)
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def load_message!
raise NotFound, "Session #{id} not found" unless File.exists?(tmp_storage_path)
@message = File.open(tmp_storage_path, 'r') do |file|
MessagePack.unpack file.read
end
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def params=(params)
unless Auth.config.secret
raise "Must set config.secret to the remote auth server's secret"
end
given_signature = params['signature']
2011-06-04 15:40:15 -07:00
secret = +Auth.config.secret
signatory = Auth::Signatory.new(secret)
2010-10-18 14:58:45 -07:00
REMOTE_MSG_KEYS.each do |key|
unless params.include?(key)
raise MissingParam, "Missing required param #{key.inspect}"
end
end
@message = params.slice(*REMOTE_MSG_KEYS)
correct_signature = signatory.sign(@message)
unless given_signature == correct_signature
raise InvalidSignature, "Signature (#{given_signature}) " +
"did not match message #{@message.inspect} (#{correct_signature})"
end
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def user
2010-11-13 16:42:56 -08:00
Auth.config.find_user_with_remote_auth(@message['user'])
2010-10-18 14:58:45 -07:00
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def self.from_params(params)
session = new
session.params = params
session
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def self.find(id)
session = new
session.id = id
session.load_message!
session
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
private
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def id
@id ||= @message[:session_id]
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
def tmp_storage_path
name = "#{id}.mpac"
File.join TMP_STORAGE_DIR, name
end
2011-06-04 15:40:15 -07:00
2010-10-18 14:58:45 -07:00
class InvalidSession < ArgumentError;end
class InvalidSignature < InvalidSession;end
class MissingParam < InvalidSession;end
class NotFound < StandardError;end
end
end
end
2011-06-04 15:40:15 -07:00