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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/atomic_tenant/current_application_instance_middleware.rb', line 12
def call(env)
begin
request = Rack::Request.new(env)
if env['atomic.validated.oauth_consumer_key'].present?
oauth_consumer_key = env['atomic.validated.oauth_consumer_key']
if ai = ApplicationInstance.find_by(lti_key: oauth_consumer_key)
env['atomic.validated.application_instance_id'] = ai.id
end
elsif env['atomic.validated.id_token'].present?
custom_strategies = AtomicTenant.custom_strategies || []
default_strategies = [
AtomicTenant::DeploymentManager::PlatformGuidStrategy.new,
AtomicTenant::DeploymentManager::ClientIdStrategy.new
]
deployment_manager = AtomicTenant::DeploymentManager::DeploymentManager.new(custom_strategies.concat(default_strategies))
decoded_token = env['atomic.validated.decoded_id_token']
iss = env['atomic.validated.decoded_id_token']['iss']
deployment_id = env['atomic.validated.decoded_id_token'][AtomicLti::Definitions::DEPLOYMENT_ID]
if deployment = AtomicTenant::LtiDeployment.find_by(iss: iss, deployment_id: deployment_id)
env['atomic.validated.application_instance_id'] = deployment.application_instance_id
else
deployment = deployment_manager.link_deployment_id(decoded_id_token: decoded_token)
env['atomic.validated.application_instance_id'] = deployment.application_instance_id
end
elsif env.dig('oauth_state', 'application_instance_id').present?
env['atomic.validated.application_instance_id'] = env['oauth_state']['application_instance_id']
elsif is_admin?(request)
admin_app_key = AtomicTenant.admin_subdomain
admin_app = Application.find_by(key: admin_app_key)
raise Exceptions::NoAdminApp if admin_app.nil?
app_instances = admin_app.application_instances
raise Exceptions::NonUniqueAdminApp if app_instances.count > 1
raise Exceptions::NoAdminApp if app_instances.empty?
if instance = app_instances.first
env['atomic.validated.application_instance_id'] = instance.id
end
elsif canvas_migration_hook?(request)
app_instance = AtomicTenant::CanvasContentMigration.decode(encoded_token(request))
env['atomic.validated.application_instance_id'] = app_instance.id
elsif encoded_token(request).present?
token = encoded_token(request)
decoded_token = AtomicTenant::JwtToken.decode(token, validate: false)
if decoded_token.present? && decoded_token.first.present? && app_instance_id = decoded_token.first['application_instance_id']
env['atomic.validated.application_instance_id'] = app_instance_id
end
end
rescue StandardError => e
Rails.logger.error("Error in current app instance middleware: #{e}, #{e.backtrace}")
end
@app.call(env)
end
|