Sha256: 658fd2fd734e47fad3e9be03d62e090067e60c3f48ad0111601193a6f08b07c0

Contents?: true

Size: 1.51 KB

Versions: 3

Compression:

Stored size: 1.51 KB

Contents

require 'cgi'

module Alondra
  module SessionParser
    extend self

    def verifier
      @verifier ||= ActiveSupport::MessageVerifier.new(Rails.application.config.secret_token)
    end

    def parse(websocket)
      cookie = websocket.request['cookie'] || websocket.request['Cookie']
      token  = websocket.request['query']['token']

      if token.present?
        SessionParser.parse_token(token)
      elsif cookie.present?
        SessionParser.parse_cookie(cookie)
      else
        Hash.new
      end
    end

    def parse_cookie(cookie)
      begin
        cookies = cookie.split(';')
        session_key = Rails.application.config.session_options[:key]

        encoded_session = cookies.detect{|c| c.include?(session_key)}.gsub("#{session_key}=",'').strip
        verifier.verify(CGI.unescape(encoded_session))
      rescue ActiveSupport::MessageVerifier::InvalidSignature => ex
        Log.error "invalid session cookie: #{cookie}"
        Hash.new
      rescue Exception => ex
        Log.error "Exception parsing session from cookie: #{ex.message}"
      end
    end

    def parse_token(token)
      begin
        decoded_token = verifier.verify(token)
        ActiveSupport::JSON.decode(decoded_token)
      rescue ActiveSupport::MessageVerifier::InvalidSignature => ex
        Log.error "invalid session token: #{token}"
        Hash.new
      end
    end

    def session_key
      Rails.application.config.session_options.key
    end

    def marshall
      Rails.application.config.session_options[:coder]
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
alondra-0.1.1 lib/alondra/session_parser.rb
alondra-0.1.0 lib/alondra/session_parser.rb
alondra-0.0.4 lib/alondra/session_parser.rb