summaryrefslogtreecommitdiff
path: root/app/controllers/api/controller.rb
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2016-12-03 22:26:35 -0700
committermo khan <mo@mokhan.ca>2016-12-03 22:26:35 -0700
commit514540a223ab20f5f66f8e8ba59b2c9bbf5f6547 (patch)
treec2ff751d3b31d29992e7ac32c809d357efd5439b /app/controllers/api/controller.rb
parentb7a8c1d2e03ebbbbfd50813c050aa594aaf8018a (diff)
implement api auth.
Diffstat (limited to 'app/controllers/api/controller.rb')
-rw-r--r--app/controllers/api/controller.rb28
1 files changed, 27 insertions, 1 deletions
diff --git a/app/controllers/api/controller.rb b/app/controllers/api/controller.rb
index 6c90721..05fdedb 100644
--- a/app/controllers/api/controller.rb
+++ b/app/controllers/api/controller.rb
@@ -2,10 +2,36 @@ class Api::Controller < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
+ before_action :authenticate!
- def current_session
+ protected
+
+ def current_session(session_id = auth_token[:session_id])
+ @current_session ||= UserSession.authenticate(session_id)
end
def current_user
+ @current_user ||= User.find(current_session.try(:user_id))
+ rescue ActiveRecord::RecordNotFound
+ nil
+ end
+
+ private
+
+ def authenticate!
+ return if current_user.present?
+ return render json: { errors: ['Not Authenticated'] }, status: :unauthorized
+ rescue JWT::VerificationError, JWT::DecodeError
+ return render json: { errors: ['Not Authenticated'] }, status: :unauthorized
+ end
+
+ def auth_token
+ @auth_token ||= JsonWebToken.decode(http_token)
+ end
+
+ def http_token
+ if request.headers['Authorization'].present?
+ request.headers['Authorization'].split(' ').last
+ end
end
end