Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Last active January 18, 2021 15:13
Show Gist options
  • Save sheharyarn/8f3e1c8aadd833e8654166d8369fbf7e to your computer and use it in GitHub Desktop.
Save sheharyarn/8f3e1c8aadd833e8654166d8369fbf7e to your computer and use it in GitHub Desktop.
API Authentication with Devise in Rails
class API::BaseController < ApplicationController
def index
render json: { active: true }
end
def authenticate
if user = User.authenticate(request.headers['X-AUTH-TOKEN'])
sign_in(user, store: false)
authenticate_user!
end
end
def authenticate!
authenticate
render_401 unless current_user
# For better json errors: https://gist.github.com/sheharyarn/aa80af81896fa03ef64f
end
end
class User < ApplicationRecord
TOKEN_DELIMITER = ':'
before_save :ensure_auth_token
## Create an `auth_token` string field
# For Mongoid:
# field :auth_token, type: String
# Get Auth Token for API use
def authentication_token
"#{id}#{TOKEN_DELIMITER}#{self.auth_token}"
end
# Authenticate User by Token
def self.authenticate(token)
id, token = token.try(:split, TOKEN_DELIMITER)
user = User.where(id: id).first
if user && Devise.secure_compare(user.auth_token, token)
user
else
false
end
end
# Ensure it exists
def ensure_auth_token
if auth_token.blank?
self.auth_token = generate_auth_token
end
end
private
def generate_auth_token
loop do
token = Devise.friendly_token
break token unless User.where(auth_token: token).first
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment