| 1 |
|
defmodule WalletAuth.Commands.Logout do |
| 2 |
|
@moduledoc """ |
| 3 |
|
Logout command: revokes session and all associated refresh tokens. |
| 4 |
|
|
| 5 |
|
Emits `AuthSessionRevoked` and audit event. |
| 6 |
|
""" |
| 7 |
|
|
| 8 |
|
alias WalletAuth.Session.SessionStore |
| 9 |
|
alias WalletAuth.Token.TokenStore |
| 10 |
|
alias WalletAuth.Events.AuthSessionRevoked |
| 11 |
|
alias WalletObservability.AuditEvent |
| 12 |
|
|
| 13 |
|
@doc """ |
| 14 |
|
Logs out by revoking the session and all refresh tokens for that session. |
| 15 |
|
|
| 16 |
|
Returns `:ok` or `{:error, :not_found}`. |
| 17 |
|
""" |
| 18 |
|
@spec execute(session_id :: String.t(), revoked_by :: String.t(), keyword()) :: |
| 19 |
|
:ok | {:error, :not_found} |
| 20 |
:-( |
def execute(session_id, revoked_by, opts \\ []) do |
| 21 |
:-( |
correlation_id = Keyword.get(opts, :correlation_id, WalletSharedKernel.Correlation.new_correlation_id()) |
| 22 |
|
|
| 23 |
:-( |
case SessionStore.revoke(session_id) do |
| 24 |
|
{:ok, revoked_session} -> |
| 25 |
:-( |
:ok = TokenStore.revoke_session(session_id) |
| 26 |
|
|
| 27 |
:-( |
audit = AuditEvent.build(:auth, "logout", "session", session_id, :success, |
| 28 |
|
actor_id: revoked_by, |
| 29 |
|
correlation_id: correlation_id |
| 30 |
|
) |
| 31 |
:-( |
:telemetry.execute([:wallet_auth, :audit], %{}, audit) |
| 32 |
|
|
| 33 |
:-( |
event = AuthSessionRevoked.build(session_id, revoked_session.sub, revoked_by, correlation_id: correlation_id) |
| 34 |
:-( |
emit_event(event) |
| 35 |
|
:ok |
| 36 |
|
|
| 37 |
:-( |
{:error, :not_found} -> |
| 38 |
|
{:error, :not_found} |
| 39 |
|
end |
| 40 |
|
end |
| 41 |
|
|
| 42 |
:-( |
defp emit_event(event) do |
| 43 |
:-( |
pubsub = Application.get_env(:wallet_auth, :pubsub, WalletWeb.PubSub) |
| 44 |
:-( |
apply(Phoenix.PubSub, :broadcast, [pubsub, "wallet_auth:events", {:domain_event, event}]) |
| 45 |
|
rescue |
| 46 |
:-( |
_ -> :ok |
| 47 |
|
end |
| 48 |
|
end |