Created
July 1, 2015 13:21
-
-
Save ansonK/e01f1559ae078bb8b4a8 to your computer and use it in GitHub Desktop.
Manually set Rails 4 session cookie for tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Manually set the contents of an encrypted session cookie | |
# | |
# Uses the same encryption keys as the Rails app using devise | |
# | |
# Based off http://big-elephants.com/2014-01/handling-rails-4-sessions-with-go/ | |
# Verified against https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/cookies.rb | |
# | |
class TestSession | |
def create_session_cookie(user_id:, csrf_token: nil, flash: {}, session_id: nil, last_request_at: nil) | |
hash = { | |
session_id: (session_id || "73b9eb8e8f265c5672ed2135a2d518f7"), | |
flashes: flash, | |
"warden.user.user.key" => [[user_id],"$2a$10$dIKBfN/6tcQsjDAAubmNDu"], | |
"warden.user.user.session" => {"last_request_at": (last_request_at || Time.current).to_i}, | |
_csrf_token: (csrf_token || "n01FGBu5O2RGf7MaB3L0DrcmeMySJhqIP/Q7dDV37Vg=") | |
} | |
encrypt_session_cookie hash | |
end | |
def encrypt_session_cookie(hash) | |
encryptor.encrypt_and_sign ActiveSupport::JSON.encode hash | |
end | |
def decrypt_session_cookie(cookie) | |
ActiveSupport::JSON.decode encryptor.decrypt_and_verify CGI.unescape cookie | |
end | |
private | |
def config | |
Rails.application.config | |
end | |
def encrypted_cookie_salt | |
config.action_dispatch.encrypted_cookie_salt | |
end | |
def encrypted_signed_cookie_salt | |
config.action_dispatch.encrypted_signed_cookie_salt | |
end | |
def key_generator | |
@key_generator ||= ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base, iterations: 1000) | |
end | |
def secret | |
key_generator.generate_key(encrypted_cookie_salt) | |
end | |
def sign_secret | |
key_generator.generate_key(encrypted_signed_cookie_salt) | |
end | |
def encryptor | |
@encryptor ||= ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment