Permalink
Browse files

Authenticate filter

  • Loading branch information...
RohitRox committed Jun 24, 2015
1 parent 10a17cb commit 548a1268c943a8895d3f67ad33358150e45449ec
Showing with 25 additions and 2 deletions.
  1. +22 −0 app/controllers/api/base_controller.rb
  2. +1 −2 config/application.rb
  3. +2 −0 config/secrets.yml
@@ -2,8 +2,30 @@ class Api::BaseController < ApplicationController
include ActionController::ImplicitRender
respond_to :json
+ before_filter :authenticate_user_from_token!
+
protected
+ def authenticate_user_from_token!
+ if claims and user = User.find_by(email: claims[0]['user'])
+ @current_user = user
+ else
+ return render_unauthorized errors: { unauthorized: ["You are not authorized perform this action."] }
+ end
+ end
+
+ def claims
+ auth_header = request.headers['Authorization'] and
+ token = auth_header.split(' ').last and
+ ::JsonWebToken.decode(token)
+ rescue
+ nil
+ end
+
+ def jwt_token user
+ JsonWebToken.encode('user' => user.email)
+ end
+
def render_unauthorized(payload)
render json: payload.merge(response: { code: 401 })
end
View
@@ -27,8 +27,7 @@ class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
- config.autoload_paths << Rails.root.join('app/lib')
-
+ config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
View
@@ -12,9 +12,11 @@
development:
secret_key_base: ddd5336f5426a07606d538a6a108530f4be24f4a9adf3a96d8a3f0348833676e153e9132ad11dd4b0483d2e463d970a2b59ae26ec844a7f95bae8930c78ac088
+ json_web_token_secret: ddd5336f5426a07606d538a6a108530f4be24f4a9adf3a96d8a3f0348833676e153e9132ad11dd4b0483d2e463d970a2b59ae26ec844a7f95bae8930c78ac088
test:
secret_key_base: 4d6762be621907e10d081031edf05d88745efd0e936e251ba619774e4f25de57b722c69c23e0efc751aceb75d666e6c37077c0c2dd31fdb3a3cb01715af1f3d2
+ json_web_token_secret: 4d6762be621907e10d081031edf05d88745efd0e936e251ba619774e4f25de57b722c69c23e0efc751aceb75d666e6c37077c0c2dd31fdb3a3cb01715af1f3d2
# Do not keep production secrets in the repository,
# instead read values from the environment.

0 comments on commit 548a126

Please sign in to comment.