Class: Rails::Auth::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/auth/env.rb

Overview

Wrapper for Rack environments with Rails::Auth helpers

Constant Summary collapse

AUTHORIZED_ENV_KEY =

Rack environment key for marking external authorization

"rails-auth.authorized"
ALLOWED_BY_ENV_KEY =

Rack environment key for storing what allowed the request

"rails-auth.allowed-by"
CREDENTIALS_ENV_KEY =

Rack environment key for all rails-auth credentials

"rails-auth.credentials"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, credentials: {}, authorized: false, allowed_by: nil) ⇒ Env

Returns a new instance of Env.

Parameters:

  • :env (Hash)

    Rack environment

Raises:

  • (TypeError)


19
20
21
22
23
24
25
26
# File 'lib/rails/auth/env.rb', line 19

def initialize(env, credentials: {}, authorized: false, allowed_by: nil)
  raise TypeError, "expected Hash for credentials, got #{credentials.class}" unless credentials.is_a?(Hash)

  @env         = env
  @credentials = Credentials.new(credentials.merge(@env.fetch(CREDENTIALS_ENV_KEY, {})))
  @authorized  = env.fetch(AUTHORIZED_ENV_KEY, authorized)
  @allowed_by  = env.fetch(ALLOWED_BY_ENV_KEY, allowed_by)
end

Instance Attribute Details

#allowed_byObject

Returns the value of attribute allowed_by.



16
17
18
# File 'lib/rails/auth/env.rb', line 16

def allowed_by
  @allowed_by
end

#credentialsObject (readonly)

Returns the value of attribute credentials.



16
17
18
# File 'lib/rails/auth/env.rb', line 16

def credentials
  @credentials
end

Instance Method Details

#authorize(allowed_by) ⇒ Object

Mark the environment as authorized to access the requested resource

Parameters:

  • :allowed_by (String)

    label of what allowed the request



36
37
38
39
# File 'lib/rails/auth/env.rb', line 36

def authorize(allowed_by)
  self.allowed_by = allowed_by
  @authorized = true
end

#authorized?Boolean

Check whether a request has been authorized

Returns:

  • (Boolean)


29
30
31
# File 'lib/rails/auth/env.rb', line 29

def authorized?
  @authorized
end

#to_rackHash

Return a Rack environment

Returns:

  • (Hash)

    Rack environment



54
55
56
57
58
59
60
61
# File 'lib/rails/auth/env.rb', line 54

def to_rack
  @env[CREDENTIALS_ENV_KEY] = (@env[CREDENTIALS_ENV_KEY] || {}).merge(@credentials.to_hash)

  @env[AUTHORIZED_ENV_KEY] = @authorized if @authorized
  @env[ALLOWED_BY_ENV_KEY] = @allowed_by if @allowed_by

  @env
end