Class: Apicraft::Web::App

Inherits:
Object
  • Object
show all
Defined in:
lib/apicraft/web/app.rb

Overview

Apicraft Rack App that is mounted for all the views to be served

Class Method Summary collapse

Class Method Details

.authorized?(env) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
47
# File 'lib/apicraft/web/app.rb', line 43

def self.authorized?(env)
  auth = Rack::Auth::Basic::Request.new(env)
  username, password = auth.provided? && auth.basic? && auth.credentials
  @use&.call(username, password).present?
end

.call(env) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/apicraft/web/app.rb', line 8

def self.call(env)
  return unauthorized_response unless authorized?(env)

  uri = env["REQUEST_URI"]
  method = env["REQUEST_METHOD"]
  Router.namespace = env["SCRIPT_NAME"]
  path = uri.split(
    Router.namespace
  )[-1] || "/"

  content, content_type = Router.load_response!(
    method, path
  )

  raise Errors::RouteNotFound if content.nil?

  [
    200,
    { 'Content-Type': content_type },
    [content]
  ]
rescue Errors::RouteNotFound
  [
    404,
    { 'Content-Type': "text/plain" },
    ["Error: not found"]
  ]
rescue StandardError => e
  [
    500,
    { 'Content-Type': "text/plain" },
    ["Error: #{e.message}"]
  ]
end

.unauthorized_responseObject



53
54
55
56
57
58
59
60
61
62
# File 'lib/apicraft/web/app.rb', line 53

def self.unauthorized_response
  [
    401,
    {
      "Content-Type": "text/plain",
      "WWW-Authenticate": "Basic realm=\"Restricted Area\""
    },
    ["Unauthorized"]
  ]
end

.use(&block) ⇒ Object



49
50
51
# File 'lib/apicraft/web/app.rb', line 49

def self.use(&block)
  @use = block
end