Module: Aaalex::PermanentCookies

Defined in:
lib/permanent_cookies.rb

Constant Summary collapse

MAX =
4096
PCOOKIE_SUFFIX =
"_pcookie"
SECRET =
"534b44a19bf18d20b71ecc4eb77c572f"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
# File 'lib/permanent_cookies.rb', line 3

def self.included(base)
  base.around_filter :permanent_cookies
end

Instance Method Details

#generate_digest(data) ⇒ Object

end



41
42
43
# File 'lib/permanent_cookies.rb', line 41

def generate_digest(data)
  OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), SECRET, data)
end

#marshal(var) ⇒ Object



44
45
46
47
# File 'lib/permanent_cookies.rb', line 44

def marshal(var)
  data = ActiveSupport::Base64.encode64(Marshal.dump(var)).chop
  "#{data}--#{generate_digest(data)}"
end

#permanent_cookiesObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/permanent_cookies.rb', line 11

def permanent_cookies
  @pcookies = {}
  cookies.each_pair do |cname, cvalue|
    if cname.include?(PCOOKIE_SUFFIX)
      @pcookies[cname.split(PCOOKIE_SUFFIX).first] = unmarshal( cvalue.first)
    end
  end
  logger.info "got pcookie\n#{@pcookies.to_yaml}"

  yield

  @pcookies.each_pair do |pcookie_name, pcookie_val|
    pc_val = if pcookie_val.is_a?( Hash)
      pcookie_val
    else
      { :value => pcookie_val,
        :expires => 1.week.from_now }
    end
    pc_val[:value] = marshal pc_val[:value]
    raise StandardError if pc_val[:value].size > MAX
    cookies[pcookie_name + PCOOKIE_SUFFIX] = pc_val
  end
  # delete all other unused pcookies
#      pcookies = defined?(@pcookies) ? @pcookies : {}
#      cookies.each_key do |cookie|
#        if cookie.include?(PCOOKIE_SUFFIX) && !pcookies.key?(cookie)
#          cookies[cookie] = {:value => nil, :expires => 1.year.ago}
#        end
#      end
end

#unmarshal(cookie) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/permanent_cookies.rb', line 48

def unmarshal(cookie)
  if cookie
    data, digest = cookie.split('--')
    unless digest == generate_digest(data) || digest == generate_digest(data = CGI.unescape(data))
      # tampered with cookie
      raise StandardError
    end
    Marshal.load(ActiveSupport::Base64.decode64(data))
  end
end