Class: Supabase::Auth::Client
- Inherits:
-
Object
- Object
- Supabase::Auth::Client
- 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
Constant Summary collapse
- STORAGE_KEY =
"supabase.auth.token"- EXPIRY_MARGIN =
10- JWKS_TTL =
10 minutes
600- ALG_TO_DIGEST =
Explicit algorithm-to-digest mapping; Python uses PyJWT’s dynamic get_algorithm_by_name (F-008).
{ "RS256" => "SHA256", "RS384" => "SHA384", "RS512" => "SHA512", "ES256" => "SHA256", "ES384" => "SHA384", "ES512" => "SHA512", "PS256" => "SHA256", "PS384" => "SHA384", "PS512" => "SHA512" }.freeze
- DEFAULT_OPTIONS =
{ auto_refresh_token: true, persist_session: true, detect_session_in_url: true, flow_type: "implicit" }.freeze
Instance Attribute Summary collapse
-
#admin ⇒ Object
readonly
Returns the value of attribute admin.
-
#headers ⇒ Object
readonly
Returns the value of attribute headers.
-
#mfa ⇒ Object
readonly
Returns the value of attribute mfa.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Instance Method Summary collapse
- #_auto_refresh_token=(value) ⇒ Object
- #_call_refresh_token(refresh_token) ⇒ Object
-
#_flow_type ⇒ Object
— Internal accessors for test access —.
- #_flow_type=(value) ⇒ Object
- #_get_url_for_provider(url, provider, params = {}) ⇒ Object
-
#_is_implicit_grant_flow(url) ⇒ Object
— PKCE helpers —.
- #_jwks ⇒ Object
- #_list_factors ⇒ Object
- #_notify_all_subscribers(event, session) ⇒ Object
- #_recover_and_refresh ⇒ Object
- #_refresh_access_token(refresh_token) ⇒ Object
- #_remove_session ⇒ Object
- #_request(method, path, jwt: nil, body: nil, params: {}, headers: {}, redirect_to: nil, xform: nil) ⇒ Object
- #_save_session(session) ⇒ Object
-
#_serialize_session(value) ⇒ Object
Recursively dump a Session (and nested User / Identity / Factor structs) to a Hash that JSON.generate accepts.
- #_start_auto_refresh_token(value = nil) ⇒ Object
- #_storage ⇒ Object
- #_storage_key ⇒ Object
- #_url ⇒ Object
-
#exchange_code_for_session(params) ⇒ Types::AuthResponse
Exchange an authorization code for a session (PKCE flow).
-
#get_claims(jwt: nil, jwks: nil) ⇒ Types::ClaimsResponse?
Get JWT claims from the current session.
-
#get_session ⇒ Types::Session?
Get the current session, refreshing it if necessary.
-
#get_user(jwt = nil) ⇒ Types::UserResponse?
Get the current user.
-
#get_user_identities ⇒ Types::IdentitiesResponse
Get identities linked to the current user.
-
#init(url: nil) ⇒ Object
(also: #bootstrap)
Initialize the client, optionally from a URL or from storage.
-
#initialize(url:, headers: {}, **options) ⇒ Client
constructor
A new instance of Client.
-
#initialize_from_storage ⇒ Object
Recover session from storage and refresh if needed.
-
#initialize_from_url(url) ⇒ nil
Initialize session from an OAuth redirect URL.
-
#link_identity(credentials) ⇒ Types::OAuthResponse
Link an OAuth identity to the current user.
-
#on_auth_state_change {|event, session| ... } ⇒ Types::Subscription
Subscribe to auth state changes.
-
#reauthenticate ⇒ Object
Reauthenticate the current user (requires active session).
-
#refresh_session(refresh_token = nil) ⇒ Types::AuthResponse
Refresh the current session using a refresh token.
-
#resend(credentials) ⇒ Object
Resend an OTP or magic link.
-
#reset_password_email(email:, **options) ⇒ Object
Alias for #reset_password_for_email.
-
#reset_password_for_email(email, options = {}) ⇒ Object
Send a password reset email.
-
#set_session(access_token, refresh_token) ⇒ Types::AuthResponse
Set session from existing access and refresh tokens.
-
#sign_in_anonymously(credentials = nil) ⇒ Types::AuthResponse
Sign in anonymously (creates an anonymous user).
-
#sign_in_with_id_token(credentials) ⇒ Types::AuthResponse
Sign in with a third-party ID token (e.g., Google, Apple).
-
#sign_in_with_oauth(credentials) ⇒ Types::OAuthResponse
Sign in with OAuth provider.
-
#sign_in_with_otp(credentials) ⇒ Types::AuthOtpResponse
Sign in with OTP (magic link for email, SMS for phone).
-
#sign_in_with_password(credentials) ⇒ Types::AuthResponse
Sign in with email/phone and password.
-
#sign_in_with_sso(credentials) ⇒ Types::SSOResponse
Sign in with SSO (SAML).
-
#sign_out(options = {}) ⇒ Object
Sign out the current user.
-
#sign_up(credentials) ⇒ Types::AuthResponse
Sign up a new user with email/phone and password.
-
#unlink_identity(identity) ⇒ Object
Unlink an identity from the current user.
-
#update_user(attributes, options = {}) ⇒ Types::UserResponse
Update the current user’s attributes.
-
#verify_otp(params) ⇒ Types::AuthResponse
Verify an OTP token.
Constructor Details
#initialize(url:, headers: {}, **options) ⇒ Client
Returns a new instance of Client.
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 |
# File 'lib/supabase/auth/client.rb', line 40 def initialize(url:, headers: {}, **) opts = DEFAULT_OPTIONS.merge() @url = url @headers = 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] @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
#admin ⇒ Object (readonly)
Returns the value of attribute admin.
30 31 32 |
# File 'lib/supabase/auth/client.rb', line 30 def admin @admin end |
#headers ⇒ Object (readonly)
Returns the value of attribute headers.
30 31 32 |
# File 'lib/supabase/auth/client.rb', line 30 def headers @headers end |
#mfa ⇒ Object (readonly)
Returns the value of attribute mfa.
30 31 32 |
# File 'lib/supabase/auth/client.rb', line 30 def mfa @mfa end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
30 31 32 |
# File 'lib/supabase/auth/client.rb', line 30 def url @url end |
Instance Method Details
#_auto_refresh_token=(value) ⇒ Object
789 790 791 |
# File 'lib/supabase/auth/client.rb', line 789 def _auto_refresh_token=(value) @auto_refresh_token = value end |
#_call_refresh_token(refresh_token) ⇒ Object
867 868 869 870 871 872 873 874 875 876 |
# File 'lib/supabase/auth/client.rb', line 867 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_type ⇒ Object
— Internal accessors for test access —
765 766 767 |
# File 'lib/supabase/auth/client.rb', line 765 def _flow_type @flow_type end |
#_flow_type=(value) ⇒ Object
769 770 771 |
# File 'lib/supabase/auth/client.rb', line 769 def _flow_type=(value) @flow_type = value end |
#_get_url_for_provider(url, provider, params = {}) ⇒ Object
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
# File 'lib/supabase/auth/client.rb', line 721 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 —
715 716 717 718 719 |
# File 'lib/supabase/auth/client.rb', line 715 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 |
#_jwks ⇒ Object
781 782 783 |
# File 'lib/supabase/auth/client.rb', line 781 def _jwks @jwks end |
#_list_factors ⇒ Object
885 886 887 |
# File 'lib/supabase/auth/client.rb', line 885 def _list_factors mfa.list_factors end |
#_notify_all_subscribers(event, session) ⇒ Object
939 940 941 942 943 |
# File 'lib/supabase/auth/client.rb', line 939 def _notify_all_subscribers(event, session) @state_change_emitters.each_value do |sub| sub.callback&.call(event, session) end end |
#_recover_and_refresh ⇒ Object
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 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 |
# File 'lib/supabase/auth/client.rb', line 821 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 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 # Swallow other errors 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
878 879 880 881 882 883 |
# File 'lib/supabase/auth/client.rb', line 878 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_session ⇒ Object
889 890 891 892 893 894 895 896 897 898 |
# File 'lib/supabase/auth/client.rb', line 889 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
945 946 947 948 |
# File 'lib/supabase/auth/client.rb', line 945 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
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 |
# File 'lib/supabase/auth/client.rb', line 900 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.
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
# File 'lib/supabase/auth/client.rb', line 922 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
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 |
# File 'lib/supabase/auth/client.rb', line 793 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 if @network_retries < Constants::MAX_RETRIES _start_auto_refresh_token(200 * (Constants::RETRY_INTERVAL ** (@network_retries - 1))) end rescue StandardError # Swallow other errors end end @refresh_token_timer.start nil end |
#_storage ⇒ Object
773 774 775 |
# File 'lib/supabase/auth/client.rb', line 773 def _storage @storage end |
#_storage_key ⇒ Object
777 778 779 |
# File 'lib/supabase/auth/client.rb', line 777 def _storage_key @storage_key end |
#_url ⇒ Object
785 786 787 |
# File 'lib/supabase/auth/client.rb', line 785 def _url @url end |
#exchange_code_for_session(params) ⇒ Types::AuthResponse
Exchange an authorization code for a session (PKCE flow).
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
# File 'lib/supabase/auth/client.rb', line 740 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.
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 |
# File 'lib/supabase/auth/client.rb', line 675 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 # Asymmetric JWT - verify via JWKS using the jwt gem's decode jwk_data = _fetch_jwks(header["kid"], jwks || { "keys" => [] }) jwk_set = JWT::JWK::Set.new({ "keys" => [jwk_data] }) raise Errors::AuthInvalidJwtError, "Unsupported algorithm: #{header["alg"]}" unless ALG_TO_DIGEST[header["alg"]] begin JWT.decode(token, nil, true, { algorithms: [header["alg"]], jwks: jwk_set }) rescue JWT::DecodeError => e raise Errors::AuthInvalidJwtError, "Invalid JWT signature: #{e.}" end Types::ClaimsResponse.new(claims: payload, headers: header, signature: signature) end |
#get_session ⇒ Types::Session?
Get the current session, refreshing it if necessary.
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
# File 'lib/supabase/auth/client.rb', line 265 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.
289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'lib/supabase/auth/client.rb', line 289 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_identities ⇒ Types::IdentitiesResponse
Get identities linked to the current user.
305 306 307 308 309 310 311 312 |
# File 'lib/supabase/auth/client.rb', line 305 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.
76 77 78 79 80 81 82 |
# File 'lib/supabase/auth/client.rb', line 76 def init(url: nil) if url && _is_implicit_grant_flow(url) initialize_from_url(url) else initialize_from_storage end end |
#initialize_from_storage ⇒ Object
Recover session from storage and refresh if needed.
86 87 88 |
# File 'lib/supabase/auth/client.rb', line 86 def initialize_from_storage _recover_and_refresh end |
#initialize_from_url(url) ⇒ nil
Initialize session from an OAuth redirect URL.
659 660 661 662 663 664 665 666 667 668 669 670 |
# File 'lib/supabase/auth/client.rb', line 659 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_identity(credentials) ⇒ Types::OAuthResponse
Link an OAuth identity to the current user.
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 |
# File 'lib/supabase/auth/client.rb', line 601 def link_identity(credentials) provider = credentials[:provider] || credentials["provider"] = credentials[:options] || credentials["options"] || {} redirect_to = [:redirect_to] scopes = [:scopes] params = ([: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.
640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
# File 'lib/supabase/auth/client.rb', line 640 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 |
#reauthenticate ⇒ Object
Reauthenticate the current user (requires active session).
541 542 543 544 545 546 547 |
# File 'lib/supabase/auth/client.rb', line 541 def reauthenticate session = get_session raise Errors::AuthSessionMissing unless session data = _request("GET", "reauthenticate", jwt: session.access_token) Helpers.parse_auth_response(data) end |
#refresh_session(refresh_token = nil) ⇒ Types::AuthResponse
Refresh the current session using a refresh token.
365 366 367 368 369 370 371 372 373 374 |
# File 'lib/supabase/auth/client.rb', line 365 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.
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'lib/supabase/auth/client.rb', line 511 def resend(credentials) phone = credentials[:phone] || credentials["phone"] email = credentials[:email] || credentials["email"] type = credentials[:type] || credentials["type"] = credentials[:options] || credentials["options"] || {} captcha_token = [:captcha_token] email_redirect_to = [: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
Alias for #reset_password_for_email.
565 566 567 |
# File 'lib/supabase/auth/client.rb', line 565 def reset_password_email(email:, **) reset_password_for_email(email, ) end |
#reset_password_for_email(email, options = {}) ⇒ Object
Send a password reset email. Does not require an active session.
552 553 554 555 556 557 558 559 560 |
# File 'lib/supabase/auth/client.rb', line 552 def reset_password_for_email(email, = {}) redirect_to = [:redirect_to] captcha_token = [: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.
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/supabase/auth/client.rb', line 320 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).
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 |
# File 'lib/supabase/auth/client.rb', line 399 def sign_in_anonymously(credentials = nil) _remove_session credentials ||= { options: {} } = credentials[:options] || credentials["options"] || {} data_attr = [:data] || {} captcha_token = [: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).
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
# File 'lib/supabase/auth/client.rb', line 424 def sign_in_with_id_token(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"] = credentials[:options] || credentials["options"] || {} captcha_token = [: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.
493 494 495 496 497 498 499 500 501 502 503 504 505 506 |
# File 'lib/supabase/auth/client.rb', line 493 def sign_in_with_oauth(credentials) _remove_session provider = credentials[:provider] || credentials["provider"] = credentials[:options] || credentials["options"] || {} redirect_to = [:redirect_to] scopes = [:scopes] params = ([: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).
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
# File 'lib/supabase/auth/client.rb', line 185 def sign_in_with_otp(credentials) _remove_session email = credentials[:email] || credentials["email"] phone = credentials[:phone] || credentials["phone"] = credentials[:options] || credentials["options"] || {} unless email || phone raise Errors::AuthInvalidCredentialsError, "An email or phone number is required" end email_redirect_to = [:email_redirect_to] should_create_user = .key?(:should_create_user) ? [:should_create_user] : true data_attr = [:data] channel = [:channel] || "sms" captcha_token = [: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.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/supabase/auth/client.rb', line 147 def sign_in_with_password(credentials) _remove_session email = credentials[:email] || credentials["email"] phone = credentials[:phone] || credentials["phone"] password = credentials[:password] || credentials["password"] = credentials[:options] || credentials["options"] || {} data_attr = [:data] || {} captcha_token = [: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).
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
# File 'lib/supabase/auth/client.rb', line 456 def sign_in_with_sso(credentials) _remove_session domain = credentials[:domain] || credentials["domain"] provider_id = credentials[:provider_id] || credentials["provider_id"] = credentials[:options] || credentials["options"] || {} redirect_to = [:redirect_to] captcha_token = [:captcha_token] skip_http_redirect = .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.
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
# File 'lib/supabase/auth/client.rb', line 379 def sign_out( = {}) scope = [:scope] || ["scope"] || "global" session = get_session if session begin @admin.sign_out(session.access_token, scope) rescue Errors::AuthApiError # Suppress API errors from admin sign_out end 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.
100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 |
# File 'lib/supabase/auth/client.rb', line 100 def sign_up(credentials) _remove_session email = credentials[:email] || credentials["email"] phone = credentials[:phone] || credentials["phone"] password = credentials[:password] || credentials["password"] = credentials[:options] || credentials["options"] || {} redirect_to = [:redirect_to] || [:email_redirect_to] user_data = [:data] || {} channel = [:channel] || "sms" captcha_token = [:captcha_token] 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_identity(identity) ⇒ Object
Unlink an identity from the current user.
627 628 629 630 631 632 633 |
# File 'lib/supabase/auth/client.rb', line 627 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.
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
# File 'lib/supabase/auth/client.rb', line 573 def update_user(attributes, = {}) session = get_session raise Errors::AuthSessionMissing unless session redirect_to = [: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.
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
# File 'lib/supabase/auth/client.rb', line 230 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"] = params[:options] || params["options"] || {} captcha_token = [: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 = [: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 |