File: cookies.rb

package info (click to toggle)
ruby-sinatra 4.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,944 kB
  • sloc: ruby: 17,702; sh: 25; makefile: 8
file content (345 lines) | stat: -rw-r--r-- 7,147 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# frozen_string_literal: true

require 'sinatra/base'

module Sinatra
  # = Sinatra::Cookies
  #
  # Easy way to deal with cookies
  #
  # == Usage
  #
  # Allows you to read cookies:
  #
  #   get '/' do
  #     "value: #{cookies[:something]}"
  #   end
  #
  # And of course to write cookies:
  #
  #   get '/set' do
  #     cookies[:something] = 'foobar'
  #     redirect to('/')
  #   end
  #
  # And generally behaves like a hash:
  #
  #   get '/demo' do
  #     cookies.merge! 'foo' => 'bar', 'bar' => 'baz'
  #     cookies.keep_if { |key, value| key.start_with? 'b' }
  #     foo, bar = cookies.values_at 'foo', 'bar'
  #     "size: #{cookies.length}"
  #   end
  #
  # === Classic Application
  #
  # In a classic application simply require the helpers, and start using them:
  #
  #     require "sinatra"
  #     require "sinatra/cookies"
  #
  #     # The rest of your classic application code goes here...
  #
  # === Modular Application
  #
  # In a modular application you need to require the helpers, and then tell
  # the application to use them:
  #
  #     require "sinatra/base"
  #     require "sinatra/cookies"
  #
  #     class MyApp < Sinatra::Base
  #       helpers Sinatra::Cookies
  #
  #       # The rest of your modular application code goes here...
  #     end
  #
  module Cookies
    class Jar
      include Enumerable
      attr_reader :options

      def initialize(app)
        @response_array  = nil
        @response_hash   = {}
        @response        = app.response
        @request         = app.request
        @deleted         = []

        @options = {
          path: @request.script_name.to_s.empty? ? '/' : @request.script_name,
          domain: @request.host == 'localhost' ? nil : @request.host,
          secure: @request.secure?,
          httponly: true
        }

        return unless app.settings.respond_to? :cookie_options

        @options.merge! app.settings.cookie_options
      end

      def ==(other)
        other.respond_to? :to_hash and to_hash == other.to_hash
      end

      def [](key)
        response_cookies[key.to_s] || request_cookies[key.to_s]
      end

      def []=(key, value)
        set(key, value: value)
      end

      if Hash.method_defined? :assoc
        def assoc(key)
          to_hash.assoc(key.to_s)
        end
      end

      def clear
        each_key { |k| delete(k) }
      end

      def compare_by_identity?
        false
      end

      def default
        nil
      end

      alias default_proc default

      def delete(key)
        result = self[key]
        @response.delete_cookie(key.to_s, @options)
        result
      end

      def delete_if
        return enum_for(__method__) unless block_given?

        each { |k, v| delete(k) if yield(k, v) }
        self
      end

      def each(&block)
        return enum_for(__method__) unless block_given?

        to_hash.each(&block)
      end

      def each_key(&block)
        return enum_for(__method__) unless block_given?

        to_hash.each_key(&block)
      end

      alias each_pair each

      def each_value(&block)
        return enum_for(__method__) unless block_given?

        to_hash.each_value(&block)
      end

      def empty?
        to_hash.empty?
      end

      def fetch(key, &block)
        response_cookies.fetch(key.to_s) do
          request_cookies.fetch(key.to_s, &block)
        end
      end

      if Hash.method_defined? :flatten
        def flatten
          to_hash.flatten
        end
      end

      def has_key?(key)
        response_cookies.key? key.to_s or request_cookies.key? key.to_s
      end

      def has_value?(value)
        response_cookies.value? value or request_cookies.value? value
      end

      def hash
        to_hash.hash
      end

      alias include? has_key?
      alias member?  has_key?

      def inspect
        "<##{self.class}: #{to_hash.inspect[1..-2]}>"
      end

      if Hash.method_defined? :invert
        def invert
          to_hash.invert
        end
      end

      def keep_if
        return enum_for(__method__) unless block_given?

        delete_if { |*a| !yield(*a) }
      end

      def key(value)
        to_hash.key(value)
      end

      alias key? has_key?

      def keys
        to_hash.keys
      end

      def length
        to_hash.length
      end

      def merge(other, &block)
        to_hash.merge(other, &block)
      end

      def merge!(other)
        other.each_pair do |key, value|
          self[key] = if block_given? && include?(key)
                        yield(key.to_s, self[key], value)
                      else
                        value
                      end
        end
      end

      def rassoc(value)
        to_hash.rassoc(value)
      end

      def rehash
        response_cookies.rehash
        request_cookies.rehash
        self
      end

      def reject(&block)
        return enum_for(__method__) unless block_given?

        to_hash.reject(&block)
      end

      alias reject! delete_if

      def replace(other)
        select! { |k, _v| other.include?(k) or other.include?(k.to_s) }
        merge! other
      end

      def select(&block)
        return enum_for(__method__) unless block_given?

        to_hash.select(&block)
      end

      alias select! keep_if if Hash.method_defined? :select!

      def set(key, options = {})
        @response.set_cookie key.to_s, @options.merge(options)
      end

      def shift
        key, value = to_hash.shift
        delete(key)
        [key, value]
      end

      alias size length

      if Hash.method_defined? :sort
        def sort(&block)
          to_hash.sort(&block)
        end
      end

      alias store []=

      def to_hash
        request_cookies.merge(response_cookies)
      end

      def to_a
        to_hash.to_a
      end

      def to_s
        to_hash.to_s
      end

      alias update merge!
      alias value? has_value?

      def values
        to_hash.values
      end

      def values_at(*list)
        list.map { |k| self[k] }
      end

      private

      def warn(message)
        super "#{caller.first[/^[^:]:\d+:/]} warning: #{message}"
      end

      def deleted
        parse_response
        @deleted
      end

      def response_cookies
        parse_response
        @response_hash
      end

      def parse_response
        cookies_from_response = Array(@response['Set-Cookie'])
        return if @response_array == cookies_from_response

        hash = {}

        cookies_from_response.each do |line|
          key, value = line.split(';', 2).first.to_s.split('=', 2)
          next if key.nil?

          key = Rack::Utils.unescape(key)
          if line =~ /expires=Thu, 01[-\s]Jan[-\s]1970/
            @deleted << key
          else
            @deleted.delete key
            hash[key] = value
          end
        end

        @response_hash.replace hash
        @response_array = cookies_from_response
      end

      def request_cookies
        @request.cookies.reject { |key, _value| deleted.include? key }
      end
    end

    def cookies
      @cookies ||= Jar.new(self)
    end
  end

  helpers Cookies
end