module SnowmanIO::API::AuthHelpers

Constants

AUTHN_PAIR_DELIMITERS
TOKEN_REGEX

Public Instance Methods

authenticate!() click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 10
def authenticate!
  current_user || render_unauthorized
end
authenticate_user_from_token() click to toggle source

Code below grabbed from [Ruby on Rails](github.com/rails/rails)

# File lib/snowman-io/api/auth_helpers.rb, line 23
def authenticate_user_from_token
  authenticate_with_http_token do |token, options|
    # # Let use only token for authentication. It helps to keep session after email change.
    # user_email    = options[:email]
    # user_email && User.where(email: user_email, authentication_token: token).first
    User.where(authentication_token: token).first
  end
end
authenticate_with_http_token(&login_procedure) click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 32
def authenticate_with_http_token(&login_procedure)
  token, options = token_and_options
  unless token.blank?
    login_procedure.call(token, options)
  end
end
authorization_request() click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 48
def authorization_request
  headers["Authorization"]
end
current_user() click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 18
def current_user
  @current_user ||= authenticate_user_from_token
end
params_array_from(raw_params) click to toggle source

Takes raw_params and turns it into an array of parameters

# File lib/snowman-io/api/auth_helpers.rb, line 57
def params_array_from(raw_params)
  raw_params.map { |param| param.split %r/=(.+)?/ }
end
raw_params(auth) click to toggle source

pairs by the standardized `:`, `;`, or `t` delimiters defined in `AUTHN_PAIR_DELIMITERS`.

# File lib/snowman-io/api/auth_helpers.rb, line 68
def raw_params(auth)
  auth.sub(TOKEN_REGEX, '').split(/"\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
end
render_unauthorized() click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 14
def render_unauthorized
  error! 'Unauthorized', 401, 'WWW-Authenticate' => 'Token realm="Application"'
end
rewrite_param_values(array_params) click to toggle source

This removes the `“` characters wrapping the value.

# File lib/snowman-io/api/auth_helpers.rb, line 62
def rewrite_param_values(array_params)
  array_params.each { |param| param.last.gsub! %r/^"|"$/, '' }
end
token_and_options() click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 39
def token_and_options
  return if authorization_request.blank?

  if authorization_request.to_s[TOKEN_REGEX]
    params = token_params_from authorization_request
    [params.shift.last, Hash[params].with_indifferent_access]
  end
end
token_params_from(auth) click to toggle source
# File lib/snowman-io/api/auth_helpers.rb, line 52
def token_params_from(auth)
  rewrite_param_values(params_array_from(raw_params(auth)))
end