master
1class Api::Controller < ActionController::Base
2 # Prevent CSRF attacks by raising an exception.
3 # For APIs, you may want to use :null_session instead.
4 protect_from_forgery with: :null_session
5 before_action :authenticate!
6
7 protected
8
9 def current_session(session_id = auth_token[:session_id])
10 @current_session ||= UserSession.authenticate(session_id)
11 end
12
13 def current_user
14 @current_user ||= User.find(current_session.try(:user_id))
15 rescue ActiveRecord::RecordNotFound
16 nil
17 end
18
19 private
20
21 def authenticate!
22 return if current_user.present?
23 not_authenticated!
24 rescue
25 not_authenticated!
26 end
27
28 def not_authenticated!
29 render json: { errors: ['Not Authenticated'] }, status: :unauthorized
30 end
31
32 def auth_token
33 @auth_token ||= JsonWebToken.decode(http_token)
34 end
35
36 def http_token
37 request.headers['Authorization'].split(' ').last
38 end
39end