Skip to content

Instantly share code, notes, and snippets.

@danielalvarenga
Last active May 2, 2018 12:50
Show Gist options
  • Save danielalvarenga/794ef81a6bec9915939a6c0e8865f65c to your computer and use it in GitHub Desktop.
Save danielalvarenga/794ef81a6bec9915939a6c0e8865f65c to your computer and use it in GitHub Desktop.
Bearer Authentication in Rails Model
# credential.rb
class Credential < ApplicationRecord
before_create :initialize_api_key
private
# Assign an API key on create
def initialize_api_key
self.api_key ||= generate_api_key
end
# Generate a unique API key
def generate_api_key
loop do
token = SecureRandom.base64.tr('+/=', 'Qrt')
break token unless Credential.exists?(api_key: token)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment