Module: BetterAuth::Grape::Extension::ClassMethods

Defined in:
lib/better_auth/grape/extension.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#better_auth_authObject (readonly)

Returns the value of attribute better_auth_auth.



12
13
14
# File 'lib/better_auth/grape/extension.rb', line 12

def better_auth_auth
  @better_auth_auth
end

#better_auth_mount_pathObject (readonly)

Returns the value of attribute better_auth_mount_path.



12
13
14
# File 'lib/better_auth/grape/extension.rb', line 12

def better_auth_mount_path
  @better_auth_mount_path
end

Instance Method Details

#better_auth(at: BetterAuth::Configuration::DEFAULT_BASE_PATH, auth: nil, **overrides) {|config| ... } ⇒ Object

Yields:

  • (config)

Raises:

  • (ArgumentError)


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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/better_auth/grape/extension.rb', line 14

def better_auth(at: BetterAuth::Configuration::DEFAULT_BASE_PATH, auth: nil, **overrides)
  mount_path = effective_better_auth_mount_path(at)
  if mount_path == "/"
    raise ArgumentError,
      "better_auth mount path cannot be '/' (it would capture every request). " \
      "Use a prefix such as #{BetterAuth::Configuration::DEFAULT_BASE_PATH.inspect}."
  end
  raise ArgumentError, "better_auth is already configured for this API" if @better_auth_auth

  config = BetterAuth::Grape.configuration.copy
  yield config if block_given?
  config.base_path = mount_path
  options = config.to_auth_options.merge(overrides).merge(base_path: mount_path)
  auth_instance = auth || BetterAuth.auth(options)
  @better_auth_auth = auth_instance
  @better_auth_mount_path = mount_path

  mounted_app = BetterAuth::Grape::MountedApp.new(auth_instance, mount_path: mount_path)
  helpers do
    define_method(:better_auth_auth) { auth_instance }
  end
  mount({mounted_app => mount_path})
  route_setting :better_auth_internal, true
  route(:any, "/*better_auth_path") do
    path_info = env.fetch("PATH_INFO", "").to_s
    normalized_path_info = path_info.start_with?("/") ? path_info.squeeze("/") : "/#{path_info}".squeeze("/")
    script_name = env.fetch("SCRIPT_NAME", "").to_s
    normalized_script_name = script_name.start_with?("/") ? script_name.squeeze("/") : "/#{script_name}".squeeze("/")
    unless normalized_path_info == mount_path ||
        normalized_path_info.start_with?("#{mount_path}/") ||
        normalized_script_name == mount_path ||
        normalized_script_name.end_with?(mount_path)
      error!({error: "Not Found"}, 404)
    end

    rack_status, rack_headers, rack_body = mounted_app.call(env)
    status rack_status
    rack_headers.each { |key, value| header key, value }
    env[::Grape::Env::API_FORMAT] = :txt
    body rack_body.each.to_a.join
    nil
  end
end