Class: CommandTower::Workflows::Impersonation::StopWorkflow

Inherits:
ApplicationWorkflow show all
Defined in:
app/workflows/command_tower/workflows/impersonation/stop_workflow.rb

Constant Summary

Constants inherited from ApplicationWorkflow

ApplicationWorkflow::ALLOWED_RETRY_STRATEGIES, ApplicationWorkflow::InvalidTransactionResult, ApplicationWorkflow::TransactionFailure

Instance Method Summary collapse

Methods inherited from ApplicationWorkflow

call, call_from_job, continuation_max_attempts, declared_retry_strategy, mark_impersonation_activity!, retry_strategy, validate_retry_strategy!

Methods included from Impersonation::ActivityDeclaration

included

Methods included from Logging::LifecycleDeclaration

included

Methods included from Execution::ContextAccess

#audit, #execution_context, #log_debug, #log_error, #log_info, #log_warn, #publish_event

Methods included from Transactional

#fail_transaction!, #transaction

Instance Method Details

#call(actor:, impersonation_session_id:, token_expires_at: nil) ⇒ Object



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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/workflows/command_tower/workflows/impersonation/stop_workflow.rb', line 9

def call(actor:, impersonation_session_id:, token_expires_at: nil)
  session_id = impersonation_session_id.to_s.strip
  if session_id.empty?
    return failure(
      errors: [CommandTower::Errors::Auth::ImpersonationSessionMissingError.new],
      http_status: :unprocessable_entity
    )
  end

  ended = CommandTower::Services::Impersonation::End.call(
    session_id:,
    reason: "manual",
    actor_user_id: actor.id
  )
  unless ended.success?
    return failure(
      errors: ended.errors,
      http_status: CommandTower::Workflows::Impersonation::ErrorMapping.http_status_for(ended.errors.first)
    )
  end

  session = ended.data[:session]
  if session.nil? || session.actor_user_id != actor.id
    return failure(
      errors: [CommandTower::Errors::Auth::ImpersonationSessionMissingError.new],
      http_status: :unprocessable_entity
    )
  end

  if ended.data[:ended]
    target = User.find_by(id: session.target_user_id)
    if target
      audit(
        :impersonation_ended,
        subject: target,
        affected_user: target,
        changes: { reason: { from: nil, to: "manual" } },
        metadata: { impersonation_session_id: session.id },
        attribution_mode: CommandTower::Current.impersonation_active ? nil : :admin_direct
      )
    end
  end

  token = CommandTower::Jwt::LoginCreate.call(user: actor).token
  expires_at = token_expires_at.presence || CommandTower.config.jwt.ttl.from_now.to_time.to_s

  success(
    payload: { message: "impersonation_ended" },
    http_status: :ok,
    response_effects: {
      set_token: { token:, expires_at: }
    }
  )
end