pensieve_controller.rb 1.12 KB
Newer Older
1
class PensieveController < ApplicationController
2
    include Cors
3
  skip_before_action :verify_authenticity_token
4
  before_action :cors_preflight_check
5
  before_action :authenticate
6
  before_action :check_auth!
7
  after_action :cors_headers
8

9
  def bookmark
10
    if is_page_load?
11
      ChapterLoadEvent.from_params(current_user, request, params).save!
12
    else
13
      ChapterExitEvent.from_params(current_user, request, params).save!
14 15 16 17 18
    end

    render_200
  end

19
  protected
20 21 22 23 24

  def render_200
    head 200, content_type: 'application/json'
  end

25

26 27 28 29 30 31 32
  def is_page_load?
    params['event_name'] == 'chapter_load'
  end

  # If this is a preflight OPTIONS request, then short-circuit the
  # request, return only the necessary headers and return an empty
  # text/plain.
33 34 35 36 37
  def authenticate
    authenticate_or_request_with_http_token do |token, options|
      @current_user = User.find_by(auth_token: token)
    end
  end
38

39 40 41 42 43 44 45
  def check_auth!
    unless current_user
      cors_headers
      headers['Access-Control-Allow-Headers'] = request.headers['Access-Control-Request-Headers'] || ''
      head 401, content_type: 'application/json'
    end
  end
46
end