Module: Cyclid::UI::Helpers

Defined in:
app/cyclid_ui/helpers.rb

Overview

Various helper methods for Sinatra controllers

Instance Method Summary collapse

Instance Method Details

#csrf_tag(rack_env) ⇒ Object

CSRF HTML forms tag



28
29
30
# File 'app/cyclid_ui/helpers.rb', line 28

def csrf_tag(rack_env)
  Rack::Csrf.csrf_tag(rack_env)
end

#csrf_token(rack_env) ⇒ Object

Raw CSRF token



23
24
25
# File 'app/cyclid_ui/helpers.rb', line 23

def csrf_token(rack_env)
  Rack::Csrf.csrf_token(rack_env)
end

#halt_with_401Object

Standard unauthenticated 401 message



33
34
35
36
# File 'app/cyclid_ui/helpers.rb', line 33

def halt_with_401
  flash[:login_error] = 'Invalid username or password'
  halt 401, flash.now[:login_error]
end

#parse_request_bodyObject

Safely parse & validate the request body



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/cyclid_ui/helpers.rb', line 39

def parse_request_body
  # Parse the the request
  begin
    request.body.rewind

    if request.content_type == 'application/json' or \
       request.content_type == 'text/json'

      data = Oj.load request.body.read
    else
      halt(415, "unsupported content type #{request.content_type}")
    end
  rescue Oj::ParseError, YAML::Exception => ex
    Cyclid.logger.debug ex.message
    halt(400, ex.message)
  end

  # Sanity check the request
  halt(400, 'request body can not be empty') if data.nil?
  halt(400, 'request body is invalid') unless data.is_a?(Hash)

  return data
end