Permalink
Browse files

Add Devise strategy for authentication

  • Loading branch information...
1 parent dc74a64 commit b675073901b9fb659ceafe772f23f596f6e55c88 @excid3 excid3 committed Jan 7, 2017
Showing with 25 additions and 17 deletions.
  1. +1 −14 app/controllers/api_controller.rb
  2. +24 −3 config/initializers/devise.rb
@@ -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
@@ -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
@@ -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.