class ApplicationController < ActionController::Base
  include AbstractController::Translation

  ## TODO temp commented out
  before_action :authenticate_user_from_token!

  respond_to :json

  ##
  # User Authentication
  # Authenticates the user with OAuth2 Resource Owner Password Credentials
  def authenticate_user_from_token!
    auth_token = request.headers['Authorization']

    if auth_token
      authenticate_with_auth_token auth_token
    else
      authenticate_error
    end
  end

  private

  def authenticate_with_auth_token auth_token
    unless auth_token.include?(':')
      authenticate_error
      return
    end

    user_id = auth_token.split(':').first
    user = User.where(id: user_id).first

    if user && Devise.secure_compare(user.access_token, auth_token)
      # User can access
      sign_in user, store: false
    else
      authenticate_error
    end
  end

  ##
  # Authentication Failure
  # Renders a 401 error
  def authenticate_error
    # User's token is either invalid or not in the right format
    render json: { error: t('unauthorized') }, status: 401 # Authentication
  end
end


# class ApplicationController < ActionController::API

# class ApplicationController < ActionController::Base
#   protect_from_forgery with: :exception
# end
