Last active
September 24, 2019 15:39
-
-
Save luiskhernandez/55f7750669fe723c06af to your computer and use it in GitHub Desktop.
Devise authenticate_user_from_token
This file contains hidden or 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
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