Skip to content

Instantly share code, notes, and snippets.

@luiskhernandez
Last active September 24, 2019 15:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luiskhernandez/55f7750669fe723c06af to your computer and use it in GitHub Desktop.
Save luiskhernandez/55f7750669fe723c06af to your computer and use it in GitHub Desktop.
Devise authenticate_user_from_token
class ApplicationController < ActionController::API
before_action :authenticate_user_from_token!
def authenticate_user_from_token!
auth_token = request.headers['Authorization']
auth_token ? authenticate_with_token!(auth_token) : authentication_error
end
def authenticate_with_token!(token)
unless token.include?(':')
authentication_error
return
end
user_id = token.split(':').first
user = User.where(id: user_id).first
if user && Devise.secure_compare(user.authentication_token, token)
sign_in user, store: false
else
authentication_error
end
end
def authentication_error
render json: {error: 'unauthorized'}, status: :unauthorized
end
private :authenticate_with_token!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment