Sha256: 6b030c7420e09a6188784944056314aec74ac9ad88d6dffa1aff5949d90bda39

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

require 'redis'
require "token_redis_session_store/version"

module TokenRedisSessionStore
  # Token Redis session storage that uses redis and
  # passes the sessionid on an http header instead of cookie
  class TokenRedisStore < ActionDispatch::Session::AbstractStore
    def initialize(app, options = {})
      redis_options = options[:redis] || {}
      @session_header = options[:session_header] || 'Session-Id'
      @redis = Redis.new(redis_options)
      options[:defer] = true
      super
    end

    # Get a session from the cache.
    def find_session(_req, sid)
      unless sid && (session = parse_session(sid))
        sid = generate_sid
        session = {}
      end
      [sid, session]
    end

    # Set a session in the cache.
    def write_session(_req, sid, session, options)
      unless session.nil?
        if options[:expire_after].nil?
          redis.set(sid, session.to_json)
        else
          redis.setex(sid, options[:expire_after], session.to_json)
        end
      end
      sid
    end

    # Remove a session from the cache.
    def delete_session(req, sid, _session)
      req.delete_header "HTTP_#{@session_header.sub('-', '_').upcase}"
      redis.del(sid)
      generate_sid
    end

    private

    attr_reader :redis

    def extract_session_id(req)
      req.get_header "HTTP_#{@session_header.sub('-', '_').upcase}"
    end

    def parse_session(sid)
      (entry = redis.get(sid)) ? JSON.parse(entry) : nil
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
token_redis_session_store-0.1.3 lib/token_redis_session_store.rb
token_redis_session_store-0.1.2 lib/token_redis_session_store.rb