Skip to content

Commit

Permalink
Add Devise strategy for authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
excid3 committed Jan 7, 2017
1 parent dc74a64 commit b675073
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
15 changes: 1 addition & 14 deletions app/controllers/api_controller.rb
Expand Up @@ -2,24 +2,11 @@ class ApiController < ApplicationController
skip_before_action :verify_authenticity_token

before_action :set_default_format
before_action :authenticate_token!
before_action :authenticate_user!

private

def set_default_format
request.format = :json
end

def authenticate_token!
payload = JsonWebToken.decode(auth_token)
@current_user = User.find(payload["sub"])
rescue JWT::ExpiredSignature
render json: {errors: ["Auth token has expired"]}, status: :unauthorized
rescue JWT::DecodeError
render json: {errors: ["Invalid auth token"]}, status: :unauthorized
end

def auth_token
@auth_token ||= request.headers.fetch("Authorization", "").split(" ").last
end
end
27 changes: 24 additions & 3 deletions config/initializers/devise.rb
Expand Up @@ -253,10 +253,11 @@
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
manager.strategies.add :jwt, Devise::Strategies::JWT
manager.default_strategies(scope: :user).unshift :jwt
end

# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
Expand All @@ -272,3 +273,23 @@
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end

module Devise
module Strategies
class JWT < Base
def valid?
request.headers["Authorization"].present?
end

def authenticate!
token = request.headers.fetch("Authorization", "").split(" ").last
payload = JsonWebToken.decode(token)
success! User.find(payload["sub"])
rescue ::JWT::ExpiredSignature
fail! "Auth token has expired"
rescue ::JWT::DecodeError
fail! "Auth token is invalid"
end
end
end
end

0 comments on commit b675073

Please sign in to comment.