Last active
April 11, 2018 14:39
-
-
Save matija/4c5b2cb93e1e7bad41a359a25201c9e9 to your computer and use it in GitHub Desktop.
jwt_auth_controller.rb
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 JWTAuthController < ActionController::API | |
| attr_reader :current_user | |
| protected | |
| def authenticate_request! | |
| fail StandardError.new('NotAuthenticatedError') unless user_id_included_in_auth_token? | |
| @current_user = User.find(decoded_auth_token['user_id']) | |
| rescue JWT::ExpiredSignature | |
| raise StandardError.new('AuthenticationTimeoutError') | |
| rescue JWT::VerificationError, JWT::DecodeError | |
| raise StandardError.new('NotAuthenticatedError') | |
| end | |
| private | |
| def user_id_included_in_auth_token? | |
| http_auth_token && decoded_auth_token && decoded_auth_token['user_id'] | |
| end | |
| def decoded_auth_token | |
| @decoded_auth_token ||= AuthToken.decode(http_auth_token)[0] | |
| end | |
| def http_auth_token | |
| if request.headers['Authorization'].blank? && params[:headers].blank? | |
| raise StandardError.new("NotAuthenticatedError") | |
| end | |
| authorization = request.headers['Authorization'] || params[:headers][:authorization] | |
| @http_auth_token ||= if authorization.present? | |
| authorization.split(' ').last | |
| end | |
| end | |
| def authentication_timeout | |
| render json: { errors: ['Authentication Timeout'] }, status: 419 | |
| end | |
| def forbidden_resource | |
| render json: { errors: ['Not Authorized To Access Resource'] }, status: :forbidden | |
| end | |
| def user_not_authenticated | |
| render json: { errors: ['Not Authenticated'] }, status: :unauthorized | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment