Class: Shamu::Sessions::CookieStore

Inherits:
Shamu::Services::Service show all
Includes:
Shamu::Security::HashedValue, SessionStore
Defined in:
lib/shamu/sessions/cookie_store.rb

Overview

Track persistent values in a cookie stored on the user's machine. Values kept in the CookieStore are not encrypted but they are protected by HMAC hashing to ensure that they have not been modified.

To support cookies, in your service it must be instantiated as part of a Rack request and you must add Rack::CookieMiddleware to your app.

Adding support to a Rails app

# application.rb

config.middleware.use Shamu::Rack::CookiesMiddleware

In a standalone Rack app

require "shamu/rack"

app = Rack::Builder.new do
  use Shamu::Rack::CookiesMiddleware

end

run app

Constant Summary collapse

TTL =

How long cookies should be kept.

( 30 * 24 * 60 * 60 ).freeze

Dependencies collapse

Instance Method Summary collapse

Methods included from Shamu::Security::HashedValue

#hash_value

Methods included from SessionStore

create

Methods inherited from Shamu::Services::Service

#cache_for, #cached_lookup, #entity_list, #entity_lookup_list, #find_by_lookup, #lazy_association, #lookup_association

Constructor Details

#initialize(private_key = Shamu::Security.private_key) ⇒ CookieStore

Returns a new instance of CookieStore.

Parameters:

  • private_key (String) (defaults to: Shamu::Security.private_key)

    the private key used to verify cookie values.



54
55
56
57
58
# File 'lib/shamu/sessions/cookie_store.rb', line 54

def initialize( private_key = Shamu::Security.private_key )
  @private_key = private_key

  super()
end

Instance Attribute Details

#cookiesShamu::Rack::Cookies



46
# File 'lib/shamu/sessions/cookie_store.rb', line 46

attr_dependency :cookies, Shamu::Rack::Cookies

Instance Method Details

#delete(key) ⇒ nil

Remove the value with the given key.

Parameters:

  • key (String)

Returns:

  • (nil)


75
76
77
# File 'lib/shamu/sessions/cookie_store.rb', line 75

def delete( key )
  cookies.delete( key )
end

#fetch(key, &block) ⇒ Object

Fetch the value with the given key from the store. If they key does not yet exist, yields to the block and caches the result.

Parameters:

  • key (String)

Yield Returns:

  • The calculated value of the key.

Returns:

  • (Object)


61
62
63
64
65
66
67
# File 'lib/shamu/sessions/cookie_store.rb', line 61

def fetch( key, &block )
  if cookies.key?( key )
    verify_hash( cookies.get( key ) )
  elsif block_given?
    yield
  end
end

#set(key, value) ⇒ value

Save a named value in the session.

Parameters:

  • key (String)
  • value. (Object)

    Must be a primitive (String, Number, Hash, Array).

Returns:

  • (value)


70
71
72
# File 'lib/shamu/sessions/cookie_store.rb', line 70

def set( key, value )
  cookies.set( key, value: hash_value( value ), secure: true, max_age: TTL )
end