Last active
May 2, 2018 12:50
-
-
Save danielalvarenga/794ef81a6bec9915939a6c0e8865f65c to your computer and use it in GitHub Desktop.
Bearer Authentication in Rails Model
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
# 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