module Api::Authenticator

Public Instance Methods

authentication() click to toggle source
# File lib/generators/kriangle/templates/authenticator.rb, line 30
def authentication
  # user has already been found and authenticated
  return @authentication if @authentication

  # get details from header or params
  uid = headers['X-Uid'] || params['uid']
  @token     ||= headers['X-Authentication-Token'] || params['access-token']
  @client_id ||= request.headers['X-Client-Id'] || params['client-id']

  # client_id isn't required, set to 'default' if absent
  @client_id ||= 'default'

  # ensure we clear the client_id
  unless @token
    @client_id = nil
    return
  end

  return unless @token

  auth = Authentication.where(<%= underscored_user_class %>_id: uid, client_id: @client_id).last || return
  return @authentication = auth if ::BCrypt::Password.new(auth.token) == @token

  @authentication = nil
end
create_authentication(<%= underscored_user_class %>, client_id = ENV['CLIENT_ID']) click to toggle source
# File lib/generators/kriangle/templates/authenticator.rb, line 15
def create_authentication(<%= underscored_user_class %>, client_id = ENV['CLIENT_ID'])
  # delete all old tokens if any present
  <%= underscored_user_class %>.authentications.delete_all

  # create new auth token
  client_id ||= SecureRandom.urlsafe_base64(nil, false)
  token = generate_random_string
  authentication = <%= underscored_user_class %>.authentications.create(client_id: client_id, token: BCrypt::Password.create(token))

  # build auth header
  header 'X-Uid', authentication.<%= underscored_user_class %>_id
  header 'X-Client-Id', authentication.client_id
  header 'X-Authentication-Token', token
end
current_(<%= underscored_user_class %> @current_<%= underscored_user_class %> ||= authentication&.<%= underscored_user_class %> end def authenticate! render_unauthorized_access && return unless current_<%= underscored_user_class %>) click to toggle source
# File lib/generators/kriangle/templates/authenticator.rb, line 60
def current_<%= underscored_user_class %>
  @current_<%= underscored_user_class %> ||= authentication&.<%= underscored_user_class %>
end

def authenticate!
  render_unauthorized_access && return unless current_<%= underscored_user_class %>
end
destroy_authentication_token() click to toggle source
# File lib/generators/kriangle/templates/authenticator.rb, line 56
def destroy_authentication_token
  authentication&.destroy
end
generate_random_string() click to toggle source
# File lib/generators/kriangle/templates/authenticator.rb, line 11
def generate_random_string
  "#{SecureRandom.urlsafe_base64}#{DateTime.now.to_i}#{SecureRandom.urlsafe_base64}"
end