Class: Supabase::Auth::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/supabase/auth/client.rb

Overview

Client for Supabase Auth (GoTrue) API. Handles authentication flows including sign-up, sign-in, session management, OAuth, OTP, MFA, and identity management.

Direct Known Subclasses

Async::Client

Constant Summary collapse

STORAGE_KEY =
"supabase.auth.token"
EXPIRY_MARGIN =
10
JWKS_TTL =

10 minutes

600
ALG_TO_DIGEST =

Explicit asymmetric algorithm-to-digest mapping (reference table).

{
  "RS256" => "SHA256", "RS384" => "SHA384", "RS512" => "SHA512",
  "ES256" => "SHA256", "ES384" => "SHA384", "ES512" => "SHA512",
  "PS256" => "SHA256", "PS384" => "SHA384", "PS512" => "SHA512"
}.freeze
SUPPORTED_ALGORITHMS =

Full set of algorithms accepted by ‘get_claims`, matching the PyJWT defaults that supabase-py relies on via `get_algorithm_by_name`. EdDSA / Ed25519 verification additionally requires the optional `rbnacl` gem at runtime; the algorithm name is still accepted here.

%w[
  HS256 HS384 HS512
  RS256 RS384 RS512
  ES256 ES256K ES384 ES512
  PS256 PS384 PS512
  EdDSA Ed25519
].freeze
DEFAULT_OPTIONS =
{
  auto_refresh_token: true,
  persist_session: true,
  detect_session_in_url: true,
  flow_type: "implicit"
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, headers: {}, **options) ⇒ Client

Returns a new instance of Client.

Parameters:

  • url (String)

    GoTrue server URL

  • headers (Hash) (defaults to: {})

    HTTP headers to include with every request

  • options (Hash)

    configuration options

Options Hash (**options):

  • :auto_refresh_token (Boolean) — default: true

    automatically refresh tokens

  • :persist_session (Boolean) — default: true

    persist session to storage

  • :flow_type (String) — default: "implicit"

    OAuth flow type (“implicit” or “pkce”)

  • :storage (SupportedStorage)

    custom storage backend

  • :http_client (Faraday::Connection)

    custom HTTP client

  • :logger (#warn)

    optional logger; if nil, auto-refresh failures fall back to Kernel#warn ($stderr).



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/supabase/auth/client.rb', line 55

def initialize(url:, headers: {}, **options)
  opts = DEFAULT_OPTIONS.merge(options)
  @url = url
  @headers = Constants::DEFAULT_HEADERS.merge(headers)
  @auto_refresh_token = opts[:auto_refresh_token]
  @persist_session = opts[:persist_session]
  @detect_session_in_url = opts[:detect_session_in_url]
  @flow_type = opts[:flow_type].to_s
  @storage_key = opts[:storage_key] || STORAGE_KEY
  @storage = opts[:storage] || MemoryStorage.new
  @http_client = opts[:http_client]
  @verify = opts.fetch(:verify, true)
  @proxy = opts[:proxy]
  @timeout = opts[:timeout]
  @logger = opts[:logger]

  @current_session = nil
  @jwks = { "keys" => [] }
  @jwks_cached_at = nil
  @state_change_emitters = {}
  @refresh_token_timer = nil
  @network_retries = 0

  @api = Api.new(url: @url, headers: @headers, http_client: @http_client, verify: @verify, proxy: @proxy, timeout: @timeout)
  @admin = AdminApi.new(url: @url, headers: @headers, http_client: @http_client, verify: @verify, proxy: @proxy, timeout: @timeout)
  @mfa = MFAApi.new(self)
end

Instance Attribute Details

#adminObject (readonly)

Returns the value of attribute admin.



43
44
45
# File 'lib/supabase/auth/client.rb', line 43

def admin
  @admin
end

#headersObject (readonly)

Returns the value of attribute headers.



43
44
45
# File 'lib/supabase/auth/client.rb', line 43

def headers
  @headers
end

#loggerObject (readonly)

Returns the value of attribute logger.



43
44
45
# File 'lib/supabase/auth/client.rb', line 43

def logger
  @logger
end

#mfaObject (readonly)

Returns the value of attribute mfa.



43
44
45
# File 'lib/supabase/auth/client.rb', line 43

def mfa
  @mfa
end

#urlObject (readonly)

Returns the value of attribute url.



43
44
45
# File 'lib/supabase/auth/client.rb', line 43

def url
  @url
end

Instance Method Details

#_auto_refresh_token=(value) ⇒ Object



816
817
818
# File 'lib/supabase/auth/client.rb', line 816

def _auto_refresh_token=(value)
  @auto_refresh_token = value
end

#_call_refresh_token(refresh_token) ⇒ Object



898
899
900
901
902
903
904
905
906
907
# File 'lib/supabase/auth/client.rb', line 898

def _call_refresh_token(refresh_token)
  raise Errors::AuthSessionMissing unless refresh_token && !refresh_token.empty?

  response = _refresh_access_token(refresh_token)
  raise Errors::AuthSessionMissing unless response.session

  _save_session(response.session)
  _notify_all_subscribers("TOKEN_REFRESHED", response.session)
  response.session
end

#_flow_typeObject

— Internal accessors for test access —



792
793
794
# File 'lib/supabase/auth/client.rb', line 792

def _flow_type
  @flow_type
end

#_flow_type=(value) ⇒ Object



796
797
798
# File 'lib/supabase/auth/client.rb', line 796

def _flow_type=(value)
  @flow_type = value
end

#_get_url_for_provider(url, provider, params = {}) ⇒ Object



748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'lib/supabase/auth/client.rb', line 748

def _get_url_for_provider(url, provider, params = {})
  params = params.dup
  if @flow_type == "pkce"
    code_verifier = Helpers.generate_pkce_verifier
    code_challenge = Helpers.generate_pkce_challenge(code_verifier)
    @storage.set_item("#{@storage_key}-code-verifier", code_verifier)
    code_challenge_method = code_verifier == code_challenge ? "plain" : "s256"
    params["code_challenge"] = code_challenge
    params["code_challenge_method"] = code_challenge_method
  end

  params["provider"] = provider
  query = URI.encode_www_form(params)
  ["#{url}?#{query}", params]
end

#_is_implicit_grant_flow(url) ⇒ Object

— PKCE helpers —



742
743
744
745
746
# File 'lib/supabase/auth/client.rb', line 742

def _is_implicit_grant_flow(url)
  parsed = URI.parse(url)
  params = URI.decode_www_form(parsed.query || "").to_h
  params.key?("access_token") || params.key?("error_description")
end

#_jwksObject



808
809
810
# File 'lib/supabase/auth/client.rb', line 808

def _jwks
  @jwks
end

#_list_factorsObject



931
932
933
# File 'lib/supabase/auth/client.rb', line 931

def _list_factors
  mfa.list_factors
end

#_log_refresh_error(context, error) ⇒ Object

Log an auto-refresh failure. Used by both ‘_start_auto_refresh_token` and `_recover_and_refresh` so the diverged-from-py contract (“any refresh error is logged with class + message”) is enforced in one place. Falls back to Kernel#warn when no logger is injected.



920
921
922
923
924
925
926
927
928
929
# File 'lib/supabase/auth/client.rb', line 920

def _log_refresh_error(context, error)
  msg = "[Supabase::Auth] refresh failed in #{context}: #{error.class}: #{error.message}"
  if @logger.respond_to?(:warn)
    @logger.warn(msg)
  else
    Kernel.warn(msg)
  end
rescue StandardError
  # Never let logging itself break the refresh loop.
end

#_notify_all_subscribers(event, session) ⇒ Object



985
986
987
988
989
# File 'lib/supabase/auth/client.rb', line 985

def _notify_all_subscribers(event, session)
  @state_change_emitters.each_value do |sub|
    sub.callback&.call(event, session)
  end
end

#_recover_and_refreshObject



850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
# File 'lib/supabase/auth/client.rb', line 850

def _recover_and_refresh
  raw_session = @storage.get_item(@storage_key)
  current_session = _get_valid_session(raw_session)

  unless current_session
    _remove_session if raw_session
    return
  end

  time_now = Time.now.round.to_i
  expires_at = current_session.expires_at
  expires_at = expires_at.to_i if expires_at

  if expires_at && expires_at < time_now + EXPIRY_MARGIN
    refresh_token = current_session.refresh_token
    if @auto_refresh_token && refresh_token
      @network_retries += 1
      begin
        _call_refresh_token(refresh_token)
        @network_retries = 0
      rescue Errors::AuthRetryableError => e
        _log_refresh_error("recover_and_refresh", e)
        if @network_retries < Constants::MAX_RETRIES
          if @refresh_token_timer
            @refresh_token_timer.cancel
          end
          @refresh_token_timer = Timer.new(
            (200 * (Constants::RETRY_INTERVAL ** (@network_retries - 1))) / 1000.0
          ) { _recover_and_refresh }
          @refresh_token_timer.start
          return
        end
      rescue StandardError => e
        # Non-retryable failure: log once, do NOT reschedule (no infinite loop).
        _log_refresh_error("recover_and_refresh", e)
      end
    end
    _remove_session
    return
  end

  # Session still valid — restore it
  if @persist_session
    _save_session(current_session)
  end
  _notify_all_subscribers("SIGNED_IN", current_session)
end

#_refresh_access_token(refresh_token) ⇒ Object



909
910
911
912
913
914
# File 'lib/supabase/auth/client.rb', line 909

def _refresh_access_token(refresh_token)
  data = _request("POST", "token",
                  body: { refresh_token: refresh_token },
                  params: { "grant_type" => "refresh_token" })
  Helpers.parse_auth_response(data)
end

#_remove_sessionObject



935
936
937
938
939
940
941
942
943
944
# File 'lib/supabase/auth/client.rb', line 935

def _remove_session
  if @persist_session
    @storage.remove_item(@storage_key)
  end
  @current_session = nil
  if @refresh_token_timer
    @refresh_token_timer.cancel
    @refresh_token_timer = nil
  end
end

#_request(method, path, jwt: nil, body: nil, params: {}, headers: {}, redirect_to: nil, xform: nil) ⇒ Object



991
992
993
994
# File 'lib/supabase/auth/client.rb', line 991

def _request(method, path, jwt: nil, body: nil, params: {}, headers: {}, redirect_to: nil, xform: nil)
  @api._request(method, path, jwt: jwt, body: body, params: params, headers: headers,
                               redirect_to: redirect_to, xform: xform)
end

#_save_session(session) ⇒ Object



946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# File 'lib/supabase/auth/client.rb', line 946

def _save_session(session)
  @current_session = session

  expire_at = session.expires_at
  if expire_at
    time_now = Time.now.round.to_i
    expire_in = expire_at - time_now
    refresh_duration_before_expires = expire_in > EXPIRY_MARGIN ? EXPIRY_MARGIN : 0.5
    value = (expire_in - refresh_duration_before_expires) * 1000
    _start_auto_refresh_token(value)
  end

  if @persist_session && session.expires_at
    @storage.set_item(@storage_key, JSON.generate(_serialize_session(session)))
  end
end

#_serialize_session(value) ⇒ Object

Recursively dump a Session (and nested User / Identity / Factor structs) to a Hash that JSON.generate accepts. Mirrors py’s ‘session.model_dump_json()` — every Struct member is preserved (not just a hand-picked allow-list), so custom upstream fields round-trip through storage without being silently dropped.



968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
# File 'lib/supabase/auth/client.rb', line 968

def _serialize_session(value)
  case value
  when Struct
    value.to_h.each_with_object({}) do |(key, member_value), acc|
      acc[key] = _serialize_session(member_value)
    end
  when Hash
    value.each_with_object({}) { |(k, v), acc| acc[k] = _serialize_session(v) }
  when Array
    value.map { |item| _serialize_session(item) }
  when Time, Date, DateTime
    value.iso8601
  else
    value
  end
end

#_start_auto_refresh_token(value = nil) ⇒ Object



820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
# File 'lib/supabase/auth/client.rb', line 820

def _start_auto_refresh_token(value = nil)
  if @refresh_token_timer
    @refresh_token_timer.cancel
    @refresh_token_timer = nil
  end

  return nil if value.nil? || value <= 0 || !@auto_refresh_token

  @refresh_token_timer = Timer.new(value / 1000.0) do
    @network_retries += 1
    begin
      session = get_session
      if session
        _call_refresh_token(session.refresh_token)
        @network_retries = 0
      end
    rescue Errors::AuthRetryableError => e
      _log_refresh_error("auto_refresh", e)
      if @network_retries < Constants::MAX_RETRIES
        _start_auto_refresh_token(200 * (Constants::RETRY_INTERVAL ** (@network_retries - 1)))
      end
    rescue StandardError => e
      # Non-retryable failure: log once, do NOT reschedule (no infinite loop).
      _log_refresh_error("auto_refresh", e)
    end
  end
  @refresh_token_timer.start
  nil
end

#_storageObject



800
801
802
# File 'lib/supabase/auth/client.rb', line 800

def _storage
  @storage
end

#_storage_keyObject



804
805
806
# File 'lib/supabase/auth/client.rb', line 804

def _storage_key
  @storage_key
end

#_urlObject



812
813
814
# File 'lib/supabase/auth/client.rb', line 812

def _url
  @url
end

#exchange_code_for_session(params) ⇒ Types::AuthResponse

Exchange an authorization code for a session (PKCE flow).

Parameters:

  • params (Hash)

    (:auth_code, optional :code_verifier, :redirect_to)

Returns:



767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
# File 'lib/supabase/auth/client.rb', line 767

def exchange_code_for_session(params)
  code_verifier = params[:code_verifier] || params["code_verifier"] ||
                  @storage.get_item("#{@storage_key}-code-verifier")

  data = _request("POST", "token",
                  body: {
                    auth_code: params[:auth_code] || params["auth_code"],
                    code_verifier: code_verifier
                  },
                  params: { "grant_type" => "pkce" },
                  redirect_to: params[:redirect_to] || params["redirect_to"])
  response = Helpers.parse_auth_response(data)

  @storage.remove_item("#{@storage_key}-code-verifier")

  if response.session
    _save_session(response.session)
    _notify_all_subscribers("SIGNED_IN", response.session)
  end

  response
end

#get_claims(jwt: nil, jwks: nil) ⇒ Types::ClaimsResponse?

Get JWT claims from the current session. Validates symmetric JWTs via get_user, asymmetric JWTs via JWKS endpoint.

Returns:

Raises:



689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/supabase/auth/client.rb', line 689

def get_claims(jwt: nil, jwks: nil)
  token = jwt
  unless token
    session = get_session
    return nil unless session
    token = session.access_token
  end

  decoded = Helpers.decode_jwt(token)
  payload = decoded[:payload]
  header = decoded[:header]
  signature = decoded[:signature]
  raw_header = decoded[:raw]["header"]
  raw_payload = decoded[:raw]["payload"]

  Helpers.validate_exp(payload["exp"])

  # If symmetric algorithm (no kid or HS256), fallback to get_user
  if !header["kid"] || header["alg"] == "HS256"
    get_user(token)
    return Types::ClaimsResponse.new(claims: payload, headers: header, signature: signature)
  end

  # Mirror PyJWT's `get_algorithm_by_name` — reject unknown algs with the
  # same message py would raise.
  raise Errors::AuthInvalidJwtError, "Algorithm not supported" unless SUPPORTED_ALGORITHMS.include?(header["alg"])

  # Asymmetric JWT — signature verification ONLY, matching py exactly:
  # py calls algorithm.verify() (gotrue_client.py:1272-1282) after the
  # manual validate_exp above, so no claim validation (exp/nbf) happens
  # here — the jwt gem's defaults are explicitly switched off.
  jwk_data = _fetch_jwks(header["kid"], jwks || { "keys" => [] })
  jwk_set = JWT::JWK::Set.new({ "keys" => [jwk_data] })

  begin
    JWT.decode(
      token, nil, true,
      {
        algorithms: [header["alg"]],
        jwks: jwk_set,
        verify_expiration: false,
        verify_not_before: false
      }
    )
  rescue JWT::DecodeError => e
    raise Errors::AuthInvalidJwtError, "Invalid JWT signature: #{e.message}"
  end

  Types::ClaimsResponse.new(claims: payload, headers: header, signature: signature)
end

#get_sessionTypes::Session?

Get the current session, refreshing it if necessary.

Returns:



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/supabase/auth/client.rb', line 284

def get_session
  current_session = nil
  if @persist_session
    maybe_session = @storage.get_item(@storage_key)
    current_session = _get_valid_session(maybe_session)
    _remove_session unless current_session
  else
    current_session = @current_session
  end
  return nil unless current_session

  time_now = Time.now.round.to_i
  has_expired = current_session.expires_at ? current_session.expires_at <= time_now + EXPIRY_MARGIN : false

  if has_expired
    _call_refresh_token(current_session.refresh_token)
  else
    current_session
  end
end

#get_user(jwt = nil) ⇒ Types::UserResponse?

Get the current user. Uses session token if jwt is nil.

Parameters:

  • jwt (String, nil) (defaults to: nil)

    optional access token

Returns:



308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/supabase/auth/client.rb', line 308

def get_user(jwt = nil)
  unless jwt
    session = get_session
    return nil unless session
    jwt = session.access_token
  end
  access_token = jwt
  return nil unless access_token

  data = _request("GET", "user", jwt: access_token)
  Helpers.parse_user_response(data)
end

#get_user_identitiesTypes::IdentitiesResponse

Get identities linked to the current user.

Returns:

Raises:



324
325
326
327
328
329
330
331
# File 'lib/supabase/auth/client.rb', line 324

def get_user_identities
  session = get_session
  raise Errors::AuthSessionMissing unless session

  user_response = get_user(session.access_token)
  identities = user_response&.user&.identities || []
  Types::IdentitiesResponse.new(identities: identities)
end

#init(url: nil) ⇒ Object Also known as: bootstrap

Initialize the client, optionally from a URL or from storage. Equivalent to supabase-py’s ‘client.initialize(url=…)` — `initialize` is the Ruby constructor name, so this rb port uses `#init` instead. An alias `bootstrap` is provided for callers who prefer a verb that doesn’t read as a constructor.

Parameters:

  • url (String, nil) (defaults to: nil)

    optional redirect URL to initialize from



90
91
92
93
94
95
96
# File 'lib/supabase/auth/client.rb', line 90

def init(url: nil)
  if url && _is_implicit_grant_flow(url)
    initialize_from_url(url)
  else
    initialize_from_storage
  end
end

#initialize_from_storageObject

Recover session from storage and refresh if needed.



100
101
102
# File 'lib/supabase/auth/client.rb', line 100

def initialize_from_storage
  _recover_and_refresh
end

#initialize_from_url(url) ⇒ nil

Initialize session from an OAuth redirect URL.

Parameters:

  • url (String)

    the redirect URL containing auth tokens or error

Returns:

  • (nil)

Raises:



673
674
675
676
677
678
679
680
681
682
683
684
# File 'lib/supabase/auth/client.rb', line 673

def initialize_from_url(url)
  if _is_implicit_grant_flow(url)
    session, redirect_type = _get_session_from_url(url)
    _save_session(session)
    _notify_all_subscribers("SIGNED_IN", session)
    _notify_all_subscribers("PASSWORD_RECOVERY", session) if redirect_type == "recovery"
  end
  nil
rescue StandardError => e
  _remove_session
  raise e
end

Link an OAuth identity to the current user.

Parameters:

  • credentials (Hash)

    (:provider, optional :options)

Returns:

Raises:



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'lib/supabase/auth/client.rb', line 618

def link_identity(credentials)
  provider = credentials[:provider] || credentials["provider"]
  options = credentials[:options] || credentials["options"] || {}
  redirect_to = options[:redirect_to]
  scopes = options[:scopes]
  params = (options[:query_params] || {}).dup
  params["redirect_to"] = redirect_to if redirect_to
  params["scopes"] = scopes if scopes
  params["skip_http_redirect"] = "true"

  url = "user/identities/authorize"
  _, query = _get_url_for_provider(url, provider, params)

  session = get_session
  raise Errors::AuthSessionMissing unless session

  link_identity = _request("GET", url, params: query, jwt: session.access_token, xform: ->(data) { Helpers.parse_link_identity_response(data) })
  Types::OAuthResponse.new(provider: provider, url: link_identity.url)
end

#on_auth_state_change {|event, session| ... } ⇒ Types::Subscription

Subscribe to auth state changes.

Yields:

  • (event, session)

    called when auth state changes

Yield Parameters:

  • event (String)

    event type (SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, etc.)

  • session (Types::Session, nil)

    current session

Returns:



654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/supabase/auth/client.rb', line 654

def on_auth_state_change(&callback)
  id = SecureRandom.uuid

  unsubscribe = -> { @state_change_emitters.delete(id) }

  subscription = Types::Subscription.new(
    id: id,
    callback: callback,
    unsubscribe: unsubscribe
  )
  @state_change_emitters[id] = subscription

  subscription
end

#reauthenticateObject

Reauthenticate the current user (requires active session).

Raises:



558
559
560
561
562
563
564
# File 'lib/supabase/auth/client.rb', line 558

def reauthenticate
  session = get_session
  raise Errors::AuthSessionMissing unless session

  _request("GET", "reauthenticate", jwt: session.access_token)
  Types::AuthResponse.new(user: nil, session: nil)
end

#refresh_session(refresh_token = nil) ⇒ Types::AuthResponse

Refresh the current session using a refresh token.

Parameters:

  • refresh_token (String, nil) (defaults to: nil)

    optional refresh token (uses current session’s if nil)

Returns:

Raises:



384
385
386
387
388
389
390
391
392
393
# File 'lib/supabase/auth/client.rb', line 384

def refresh_session(refresh_token = nil)
  unless refresh_token
    session = get_session
    refresh_token = session.refresh_token if session
  end
  raise Errors::AuthSessionMissing unless refresh_token

  session = _call_refresh_token(refresh_token)
  Types::AuthResponse.new(session: session, user: session.user)
end

#resend(credentials) ⇒ Object

Resend an OTP or magic link.

Parameters:

  • credentials (Hash)

    (:email or :phone, :type)

Raises:



528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/supabase/auth/client.rb', line 528

def resend(credentials)
  phone = credentials[:phone] || credentials["phone"]
  email = credentials[:email] || credentials["email"]
  type = credentials[:type] || credentials["type"]
  options = credentials[:options] || credentials["options"] || {}
  captcha_token = options[:captcha_token]
  email_redirect_to = options[:email_redirect_to]

  unless email || phone
    raise Errors::AuthInvalidCredentialsError,
          "An email or phone number is required"
  end

  body = {
    type: type,
    gotrue_meta_security: { captcha_token: captcha_token }
  }
  # Match Python: email takes priority; only one of email/phone is sent
  if email
    body[:email] = email
  else
    body[:phone] = phone
  end

  data = _request("POST", "resend", body: body, redirect_to: email ? email_redirect_to : nil)
  Helpers.parse_auth_otp_response(data)
end

#reset_password_email(email:, **options) ⇒ Object

Parameters:

  • email (String)

    user email

  • options (Hash)

    optional :redirect_to



582
583
584
# File 'lib/supabase/auth/client.rb', line 582

def reset_password_email(email:, **options)
  reset_password_for_email(email, options)
end

#reset_password_for_email(email, options = {}) ⇒ Object

Send a password reset email. Does not require an active session.

Parameters:

  • email (String)

    user email

  • options (Hash) (defaults to: {})

    optional :redirect_to



569
570
571
572
573
574
575
576
577
# File 'lib/supabase/auth/client.rb', line 569

def reset_password_for_email(email, options = {})
  redirect_to = options[:redirect_to]
  captcha_token = options[:captcha_token]
  body = {
    email: email,
    gotrue_meta_security: { captcha_token: captcha_token }
  }
  _request("POST", "recover", body: body, redirect_to: redirect_to)
end

#set_session(access_token, refresh_token) ⇒ Types::AuthResponse

Set session from existing access and refresh tokens.

Parameters:

  • access_token (String)

    JWT access token

  • refresh_token (String)

    refresh token

Returns:

Raises:



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/supabase/auth/client.rb', line 339

def set_session(access_token, refresh_token)
  time_now = Time.now.round.to_i
  expires_at = time_now
  has_expired = true
  session = nil

  if access_token && access_token.split(".").length > 1
    payload = Helpers.decode_jwt(access_token)[:payload]
    exp = payload["exp"]
    if exp
      expires_at = exp.to_i
      has_expired = expires_at <= time_now
    end
  end

  if has_expired
    raise Errors::AuthSessionMissing unless refresh_token && !refresh_token.empty?

    response = _refresh_access_token(refresh_token)
    return Types::AuthResponse.new unless response.session

    session = response.session
  else
    user_response = get_user(access_token)
    raise Errors::UserDoesntExist, access_token if user_response.nil?

    session = Types::Session.new(
      access_token: access_token,
      refresh_token: refresh_token,
      token_type: "bearer",
      expires_in: expires_at - time_now,
      expires_at: expires_at,
      user: user_response.user
    )
  end

  _save_session(session)
  _notify_all_subscribers("TOKEN_REFRESHED", session)
  Types::AuthResponse.new(session: session, user: session.user)
end

#sign_in_anonymously(credentials = nil) ⇒ Types::AuthResponse

Sign in anonymously (creates an anonymous user).

Returns:



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/supabase/auth/client.rb', line 416

def (credentials = nil)
  _remove_session

  credentials ||= { options: {} }
  options = credentials[:options] || credentials["options"] || {}
  data_attr = options[:data] || {}
  captcha_token = options[:captcha_token]

  data = _request("POST", "signup", body: {
    data: data_attr,
    gotrue_meta_security: { captcha_token: captcha_token }
  })
  response = Helpers.parse_auth_response(data)

  if response.session
    _save_session(response.session)
    _notify_all_subscribers("SIGNED_IN", response.session)
  end

  response
end

#sign_in_with_id_token(credentials) ⇒ Types::AuthResponse

Sign in with a third-party ID token (e.g., Google, Apple).

Parameters:

  • credentials (Hash)

    (:provider, :token, optional :nonce)

Returns:



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/supabase/auth/client.rb', line 441

def (credentials)
  _remove_session

  provider = credentials[:provider] || credentials["provider"]
  token = credentials[:token] || credentials["token"]
  access_token = credentials[:access_token] || credentials["access_token"]
  nonce = credentials[:nonce] || credentials["nonce"]
  options = credentials[:options] || credentials["options"] || {}
  captcha_token = options[:captcha_token]

  body = {
    provider: provider,
    id_token: token,
    access_token: access_token,
    nonce: nonce,
    gotrue_meta_security: { captcha_token: captcha_token }
  }

  data = _request("POST", "token", body: body, params: { "grant_type" => "id_token" })
  response = Helpers.parse_auth_response(data)

  if response.session
    _save_session(response.session)
    _notify_all_subscribers("SIGNED_IN", response.session)
  end

  response
end

#sign_in_with_oauth(credentials) ⇒ Types::OAuthResponse

Sign in with OAuth provider. Returns URL to redirect the user to.

Parameters:

  • credentials (Hash)

    (:provider, optional :options)

Returns:



510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/supabase/auth/client.rb', line 510

def (credentials)
  _remove_session

  provider = credentials[:provider] || credentials["provider"]
  options = credentials[:options] || credentials["options"] || {}
  redirect_to = options[:redirect_to]
  scopes = options[:scopes]
  params = (options[:query_params] || {}).dup
  params["redirect_to"] = redirect_to if redirect_to
  params["scopes"] = scopes if scopes

  url_with_qs, _ = _get_url_for_provider("#{@url}/authorize", provider, params)
  Types::OAuthResponse.new(provider: provider, url: url_with_qs)
end

#sign_in_with_otp(credentials) ⇒ Types::AuthOtpResponse

Sign in with OTP (magic link for email, SMS for phone).

Parameters:

  • credentials (Hash)

    (:email or :phone, optional :options)

Returns:

Raises:



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/supabase/auth/client.rb', line 204

def (credentials)
  _remove_session

  email = credentials[:email] || credentials["email"]
  phone = credentials[:phone] || credentials["phone"]
  options = credentials[:options] || credentials["options"] || {}

  unless email || phone
    raise Errors::AuthInvalidCredentialsError,
          "An email or phone number is required"
  end

  email_redirect_to = options[:email_redirect_to]
  should_create_user = options.key?(:should_create_user) ? options[:should_create_user] : true
  data_attr = options[:data]
  channel = options[:channel] || "sms"
  captcha_token = options[:captcha_token]

  if email
    body = {
      email: email,
      data: data_attr,
      create_user: should_create_user,
      gotrue_meta_security: { captcha_token: captcha_token }
    }
    data = _request("POST", "otp", body: body, redirect_to: email_redirect_to)
    return Helpers.parse_auth_otp_response(data)
  end

  if phone
    body = {
      phone: phone,
      data: data_attr,
      create_user: should_create_user,
      channel: channel,
      gotrue_meta_security: { captcha_token: captcha_token }
    }
    data = _request("POST", "otp", body: body)
    return Helpers.parse_auth_otp_response(data)
  end
end

#sign_in_with_password(credentials) ⇒ Types::AuthResponse

Sign in with email/phone and password.

Parameters:

  • credentials (Hash)

    sign-in credentials (:email or :phone, and :password)

Returns:

Raises:



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/supabase/auth/client.rb', line 166

def (credentials)
  _remove_session

  email = credentials[:email] || credentials["email"]
  phone = credentials[:phone] || credentials["phone"]
  password = credentials[:password] || credentials["password"]
  options = credentials[:options] || credentials["options"] || {}
  data_attr = options[:data] || {}
  captcha_token = options[:captcha_token]

  unless (email || phone) && password
    raise Errors::AuthInvalidCredentialsError,
          "An email or phone number and password are required"
  end

  body = {
    password: password,
    data: data_attr,
    gotrue_meta_security: { captcha_token: captcha_token }
  }
  body[:email] = email if email
  body[:phone] = phone if phone

  data = _request("POST", "token", body: body, params: { "grant_type" => "password" })
  response = Helpers.parse_auth_response(data)

  if response.session
    _save_session(response.session)
    _notify_all_subscribers("SIGNED_IN", response.session)
  end

  response
end

#sign_in_with_sso(credentials) ⇒ Types::SSOResponse

Sign in with SSO (SAML).

Parameters:

  • credentials (Hash)

    (:domain or :provider_id, optional :options)

Returns:

Raises:



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/supabase/auth/client.rb', line 473

def (credentials)
  _remove_session

  domain = credentials[:domain] || credentials["domain"]
  provider_id = credentials[:provider_id] || credentials["provider_id"]
  options = credentials[:options] || credentials["options"] || {}
  redirect_to = options[:redirect_to]
  captcha_token = options[:captcha_token]
  skip_http_redirect = options.fetch(:skip_http_redirect, true)

  if domain
    data = _request("POST", "sso", body: {
      domain: domain,
      skip_http_redirect: skip_http_redirect,
      gotrue_meta_security: { captcha_token: captcha_token },
      redirect_to: redirect_to
    })
    return Helpers.parse_sso_response(data)
  end

  if provider_id
    data = _request("POST", "sso", body: {
      provider_id: provider_id,
      skip_http_redirect: skip_http_redirect,
      gotrue_meta_security: { captcha_token: captcha_token },
      redirect_to: redirect_to
    })
    return Helpers.parse_sso_response(data)
  end

  raise Errors::AuthInvalidCredentialsError,
        "You must provide either a domain or provider_id"
end

#sign_out(options = {}) ⇒ Object

Sign out the current user.

Parameters:

  • options (Hash) (defaults to: {})

    sign-out options

Options Hash (options):

  • :scope (String) — default: "global"

    sign-out scope: “global”, “local”, or “others”



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/supabase/auth/client.rb', line 398

def sign_out(options = {})
  scope = options[:scope] || options["scope"] || "global"

  begin
    session = get_session
    @admin.sign_out(session.access_token, scope) if session
  rescue Errors::AuthApiError
    # Suppress API errors from get_session/admin.sign_out so logout always clears local state.
  end

  unless scope == "others"
    _remove_session
    _notify_all_subscribers("SIGNED_OUT", nil)
  end
end

#sign_up(credentials) ⇒ Types::AuthResponse

Sign up a new user with email/phone and password.

Parameters:

  • credentials (Hash)

    sign-up credentials

Options Hash (credentials):

  • :email (String)

    user email

  • :phone (String)

    user phone number

  • :password (String)

    user password

  • :options (Hash)

    additional options (data, captcha_token, redirect_to, channel)

Returns:

Raises:



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/supabase/auth/client.rb', line 114

def (credentials)
  _remove_session

  email = credentials[:email] || credentials["email"]
  phone = credentials[:phone] || credentials["phone"]
  password = credentials[:password] || credentials["password"]
  options = credentials[:options] || credentials["options"] || {}
  redirect_to = options[:redirect_to] || options[:email_redirect_to]
  user_data = options[:data] || {}
  channel = options[:channel] || "sms"
  captcha_token = options[:captcha_token]

  if password.nil? && (email || phone)
    raise Errors::AuthInvalidCredentialsError,
          "Sign up requires a password; for passwordless sign-in use sign_in_with_otp"
  end

  if email
    body = {
      email: email,
      password: password,
      data: user_data,
      gotrue_meta_security: { captcha_token: captcha_token }
    }
  elsif phone
    body = {
      phone: phone,
      password: password,
      data: user_data,
      channel: channel,
      gotrue_meta_security: { captcha_token: captcha_token }
    }
  else
    raise Errors::AuthInvalidCredentialsError,
          "You must provide either an email or phone number and a password"
  end

  data = _request("POST", "signup", body: body, redirect_to: redirect_to)
  response = Helpers.parse_auth_response(data)

  if response.session
    _save_session(response.session)
    _notify_all_subscribers("SIGNED_IN", response.session)
  end

  response
end

Unlink an identity from the current user.

Parameters:

Raises:



641
642
643
644
645
646
647
# File 'lib/supabase/auth/client.rb', line 641

def unlink_identity(identity)
  session = get_session
  raise Errors::AuthSessionMissing unless session

  identity_id = identity.respond_to?(:identity_id) ? identity.identity_id : identity[:identity_id]
  _request("DELETE", "user/identities/#{identity_id}", jwt: session.access_token)
end

#update_user(attributes, options = {}) ⇒ Types::UserResponse

Update the current user’s attributes.

Parameters:

  • attributes (Hash)

    user attributes to update (e.g., email, password, data)

Returns:

Raises:



590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/supabase/auth/client.rb', line 590

def update_user(attributes, options = {})
  session = get_session
  raise Errors::AuthSessionMissing unless session

  redirect_to = options[:email_redirect_to]
  data = _request("PUT", "user", jwt: session.access_token, body: attributes, redirect_to: redirect_to)
  response = Helpers.parse_user_response(data)

  updated_session = Types::Session.new(
    access_token: session.access_token,
    refresh_token: session.refresh_token,
    token_type: session.token_type,
    expires_in: session.expires_in,
    expires_at: session.expires_at,
    provider_token: session.provider_token,
    provider_refresh_token: session.provider_refresh_token,
    user: response.user
  )
  _save_session(updated_session)
  _notify_all_subscribers("USER_UPDATED", updated_session)

  response
end

#verify_otp(params) ⇒ Types::AuthResponse

Verify an OTP token.

Parameters:

  • params (Hash)

    verification params (:type, :token, :email or :phone)

Returns:



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/supabase/auth/client.rb', line 249

def verify_otp(params)
  _remove_session

  type = params[:type] || params["type"]
  phone = params[:phone] || params["phone"]
  email = params[:email] || params["email"]
  token = params[:token] || params["token"]
  token_hash = params[:token_hash] || params["token_hash"]
  options = params[:options] || params["options"] || {}
  captcha_token = options[:captcha_token]

  body = {
    type: type,
    gotrue_meta_security: { captcha_token: captcha_token }
  }
  body[:token] = token if token
  body[:phone] = phone if phone
  body[:email] = email if email
  body[:token_hash] = token_hash if token_hash

  redirect_to = options[:redirect_to]

  data = _request("POST", "verify", body: body, redirect_to: redirect_to)
  response = Helpers.parse_auth_response(data)

  if response.session
    _save_session(response.session)
    _notify_all_subscribers("SIGNED_IN", response.session)
  end

  response
end