Module: Cloudinary::AuthToken

Defined in:
lib/cloudinary/auth_token.rb

Constant Summary collapse

SEPARATOR =
'~'
UNSAFE =
/[ "#%&\'\/:;<=>?@\[\\\]^`{\|}~]/
EMPTY_TOKEN =
{}.freeze

Class Method Summary collapse

Class Method Details

.generate(options = {}) ⇒ Object



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
# File 'lib/cloudinary/auth_token.rb', line 13

def self.generate(options = {})
  key = options[:key]
  raise "Missing auth token key configuration" unless key
  name = options[:token_name] || "__cld_token__"
  start = options[:start_time]
  expiration = options[:expiration]
  ip = options[:ip]

  acl = options[:acl]
  if acl.present?
    acl = acl.is_a?(String) ? [acl] : acl
  end

  duration = options[:duration]
  url = options[:url]
  start = Time.new.getgm.to_i if start == 'now'
  if expiration.nil? || expiration == 0
    if !(duration.nil? || duration == 0)
      expiration = (start || Time.new.getgm.to_i) + duration
    else
      raise 'Must provide either expiration or duration'
    end
  end

  if url.blank? && acl.blank?
    raise 'AuthToken must contain either an acl or a url property'
  end

  token = []
  token << "ip=#{ip}" if ip
  token << "st=#{start}" if start
  token << "exp=#{expiration}"
  token << "acl=#{escape_to_lower(acl.join('!'))}" if acl && acl.size > 0
  to_sign = token.clone
  to_sign << "url=#{escape_to_lower(url)}" if url && (acl.blank? || acl.size == 0)
  auth = digest(to_sign.join(SEPARATOR), key)
  token << "hmac=#{auth}"
  "#{name}=#{token.join(SEPARATOR)}"
end

.merge_auth_token(token1, token2) ⇒ Object

Merge token2 to token1 returning a new Requires to support Ruby 1.9



55
56
57
58
59
60
61
# File 'lib/cloudinary/auth_token.rb', line 55

def self.merge_auth_token(token1, token2)
  token1 = token1 || EMPTY_TOKEN
  token2 = token2 || EMPTY_TOKEN
  token1 = token1.respond_to?( :to_h) ? token1.to_h : token1
  token2 = token2.respond_to?( :to_h) ? token2.to_h : token2
  token1.merge(token2)
end