Skip to content

Commit f6ac2e5

Browse files
committed
Expose auth cache helpers as module functions
Quick reminder: module functions are available on the module itself and also added as `private` methods when the module is included. It is best that they are stateless, or rely on a more global state, due to this dual accessibility. This is in preparation for providing a new set of RSpec auth helpers targeting API endpoints. Most APIs are stateless and the newer Rails 5 `ActionController::API` base class does not mix in cookie or session support by default. Because of this the existing `sign_in` helper is not properly suited for these controllers. Additionally, for API endpoints the `sign_in` helper hides the fact that authentication _must_ be provided through the `Authorization` header; instead of assuming it was set previously in the session. This could cause some edge cases bugs to slip through where authorization isn't getting set, checked, or goes through the proper process.
1 parent 4e45d80 commit f6ac2e5

File tree

1 file changed

+21
-19
lines changed

1 file changed

+21
-19
lines changed

lib/kracken/controllers/token_authenticatable.rb

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,27 @@ def request_http_token_authentication(realm = 'Application')
2929
end
3030
end
3131

32+
module_function
33+
34+
def cache_valid_auth(token, &generate_cache)
35+
cache_key = "auth/token/#{token}"
36+
val = Rails.cache.read(cache_key)
37+
val ||= store_valid_auth(cache_key, &generate_cache)
38+
shallow_freeze(val)
39+
end
40+
41+
def shallow_freeze(val)
42+
# `nil` is frozen in Ruby 2.2 but not in Ruby 2.1
43+
return val if val.frozen? || val.nil?
44+
val.each { |_k, v| v.freeze }.freeze
45+
end
46+
47+
def store_valid_auth(cache_key)
48+
val = yield
49+
Rails.cache.write(cache_key, val, CACHE_TTL_OPTS) if val
50+
val
51+
end
52+
3253
private
3354

3455
CACHE_TTL_OPTS = {
@@ -51,19 +72,6 @@ def authenticate_user_with_token!
5172
}
5273
end
5374

54-
def cache_valid_auth(token, &generate_cache)
55-
cache_key = "auth/token/#{token}"
56-
val = Rails.cache.read(cache_key)
57-
val ||= store_valid_auth(cache_key, &generate_cache)
58-
shallow_freeze(val)
59-
end
60-
61-
def shallow_freeze(val)
62-
# `nil` is frozen in Ruby 2.2 but not in Ruby 2.1
63-
return val if val.frozen? || val.nil?
64-
val.each { |_k, v| v.freeze }.freeze
65-
end
66-
6775
def current_auth_info
6876
@_auth_info ||= {}
6977
end
@@ -96,12 +104,6 @@ def munge_header_auth_token!
96104
def realm
97105
self.class.realm
98106
end
99-
100-
def store_valid_auth(cache_key)
101-
val = yield
102-
Rails.cache.write(cache_key, val, CACHE_TTL_OPTS) if val
103-
val
104-
end
105107
end
106108

107109
end

0 commit comments

Comments
 (0)