Last active
August 29, 2015 14:17
-
-
Save karloku/b33a83eb3b24de3bd16a to your computer and use it in GitHub Desktop.
Using Sorcery's basic authorization in Grape
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
module API | |
module SorceryAdapter | |
AUTHENTICITY_TOKEN_LENGTH = 32 | |
def self.included(mod) | |
mod.instance_eval { | |
helpers do | |
### Adapt for Sorcery (some directly taken from rails codes) | |
# Get session | |
def session | |
env[Rack::Session::Abstract::ENV_SESSION_KEY] | |
end | |
# Disable remember_me because of the cookies type conflict | |
def current_user | |
unless defined?(@current_user) | |
@current_user = login_from_session || nil | |
end | |
@current_user | |
end | |
## ActionDispatch::Request | |
def reset_session | |
if session && session.respond_to?(:destroy) | |
session.destroy | |
else | |
self.session = {} | |
end | |
@env['action_dispatch.request.flash_hash'] = nil | |
end | |
## ActionController::RequestForgeryProtection::ProtectionMethods::NullSession | |
# Sets the token value for the current session. | |
def form_authenticity_token | |
masked_authenticity_token(session) | |
end | |
def real_csrf_token(session) | |
session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH) | |
Base64.strict_decode64(session[:_csrf_token]) | |
end | |
# Creates a masked version of the authenticity token that varies | |
# on each request. The masking is used to mitigate SSL attacks | |
# like BREACH. | |
def masked_authenticity_token(session) | |
one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH) | |
encrypted_csrf_token = xor_byte_strings(one_time_pad, real_csrf_token(session)) | |
masked_token = one_time_pad + encrypted_csrf_token | |
Base64.strict_encode64(masked_token) | |
end | |
def xor_byte_strings(s1, s2) | |
s1.bytes.zip(s2.bytes).map { |(c1,c2)| c1 ^ c2 }.pack('c*') | |
end | |
end | |
} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment