Module: BetterAuth::SocialProviders::Base

Defined in:
lib/better_auth/social_providers/base.rb

Class Method Summary collapse

Class Method Details

.access_token(tokens) ⇒ Object



170
171
172
# File 'lib/better_auth/social_providers/base.rb', line 170

def access_token(tokens)
  tokens[:access_token] || tokens["access_token"] || tokens[:accessToken] || tokens["accessToken"]
end

.apply_profile_mapping(user, profile, options) ⇒ Object



240
241
242
# File 'lib/better_auth/social_providers/base.rb', line 240

def apply_profile_mapping(user, profile, options)
  user.merge(options[:map_profile_to_user]&.call(profile) || {})
end

.authorization_url(endpoint, params) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/better_auth/social_providers/base.rb', line 16

def authorization_url(endpoint, params)
  uri = URI(endpoint)
  query = URI.decode_www_form(uri.query.to_s)
  params.compact.each do |key, value|
    next if value == ""

    query << [key.to_s, Array(value).join(" ")]
  end
  uri.query = URI.encode_www_form(query)
  uri.to_s
end

.decode_jwt_payload(token) ⇒ Object



253
254
255
256
257
258
259
260
# File 'lib/better_auth/social_providers/base.rb', line 253

def decode_jwt_payload(token)
  _header, payload, _signature = token.to_s.split(".", 3)
  return {} unless payload

  JSON.parse(Base64.urlsafe_decode64(padded_base64(payload)))
rescue JSON::ParserError, ArgumentError
  {}
end

.fetch_jwks(endpoint) ⇒ Object



284
285
286
287
288
# File 'lib/better_auth/social_providers/base.rb', line 284

def fetch_jwks(endpoint)
  return nil if endpoint.to_s.empty?

  get_json(endpoint)
end

.fetch_user_info(endpoint, tokens, method: :get, headers: {}, body: nil) ⇒ Object



137
138
139
140
141
142
# File 'lib/better_auth/social_providers/base.rb', line 137

def (endpoint, tokens, method: :get, headers: {}, body: nil)
  resolved_headers = resolve_hash(headers, tokens, {})
  resolved_body = resolve_hash(body || {}, tokens, {})
  resolved_headers = {"Authorization" => "Bearer #{access_token(tokens)}"}.merge(resolved_headers)
  (method == :post) ? post_json(endpoint, resolved_body, resolved_headers) : get_json(endpoint, resolved_headers)
end

.get_bytes(url, headers = {}) ⇒ Object



119
120
121
122
123
124
125
126
127
# File 'lib/better_auth/social_providers/base.rb', line 119

def get_bytes(url, headers = {})
  uri = URI(url)
  request = Net::HTTP::Get.new(uri)
  headers.each { |key, value| request[key.to_s] = value.to_s }
  response = request_json(uri, request)
  response.is_a?(Net::HTTPSuccess) ? response.body.to_s : nil
rescue URI::InvalidURIError, SocketError, SystemCallError
  nil
end

.get_json(url, headers = {}) ⇒ Object



112
113
114
115
116
117
# File 'lib/better_auth/social_providers/base.rb', line 112

def get_json(url, headers = {})
  uri = URI(url)
  request = Net::HTTP::Get.new(uri)
  headers.each { |key, value| request[key.to_s] = value.to_s }
  parse_response(request_json(uri, request))
end

.id_token(tokens) ⇒ Object



174
175
176
# File 'lib/better_auth/social_providers/base.rb', line 174

def id_token(tokens)
  tokens[:id_token] || tokens["id_token"] || tokens[:idToken] || tokens["idToken"]
end

.normalize_options(options) ⇒ Object



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
# File 'lib/better_auth/social_providers/base.rb', line 194

def normalize_options(options)
  normalized = options.dup
  {
    clientId: :client_id,
    clientSecret: :client_secret,
    clientKey: :client_key,
    disableDefaultScope: :disable_default_scope,
    mapProfileToUser: :map_profile_to_user,
    getUserInfo: :get_user_info,
    verifyIdToken: :verify_id_token,
    refreshAccessToken: :refresh_access_token,
    disableIdTokenSignIn: :disable_id_token_sign_in,
    disableImplicitSignUp: :disable_implicit_sign_up,
    disableSignUp: :disable_sign_up,
    authorizationEndpoint: :authorization_endpoint,
    tokenEndpoint: :token_endpoint,
    userInfoEndpoint: :user_info_endpoint,
    emailsEndpoint: :emails_endpoint,
    redirectURI: :redirect_uri,
    jwksEndpoint: :jwks_endpoint,
    appBundleIdentifier: :app_bundle_identifier,
    profilePhotoSize: :profile_photo_size,
    disableProfilePhoto: :disable_profile_photo,
    tenantId: :tenant_id
  }.each do |camel, snake|
    normalized[snake] = normalized[camel] if normalized.key?(camel) && !normalized.key?(snake)
  end
  normalized
end

.normalize_tokens(tokens, now: Time.now) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/better_auth/social_providers/base.rb', line 153

def normalize_tokens(tokens, now: Time.now)
  data = stringify_keys(tokens || {})
  result = {}
  result["accessToken"] = data["accessToken"] || data["access_token"] if data["accessToken"] || data["access_token"]
  result["refreshToken"] = data["refreshToken"] || data["refresh_token"] if data["refreshToken"] || data["refresh_token"]
  result["idToken"] = data["idToken"] || data["id_token"] if data["idToken"] || data["id_token"]
  result["tokenType"] = data["tokenType"] || data["token_type"] if data["tokenType"] || data["token_type"]
  scope = data["scope"] || data["scopes"]
  result["scope"] = Array(scope).join(",").tr(" ", ",").split(",").reject(&:empty?).join(",") if scope
  result["accessTokenExpiresAt"] = time_from(data["accessTokenExpiresAt"] || data["access_token_expires_at"]) if data["accessTokenExpiresAt"] || data["access_token_expires_at"]
  result["refreshTokenExpiresAt"] = time_from(data["refreshTokenExpiresAt"] || data["refresh_token_expires_at"]) if data["refreshTokenExpiresAt"] || data["refresh_token_expires_at"]
  result["accessTokenExpiresAt"] ||= now + data["expires_in"].to_i if data["expires_in"]
  result["refreshTokenExpiresAt"] ||= now + data["refresh_token_expires_in"].to_i if data["refresh_token_expires_in"]
  data.each { |key, value| result[key] = value unless result.key?(key) || %w[access_token refresh_token id_token token_type expires_in refresh_token_expires_in scopes].include?(key) }
  result
end

.oauth_provider(id:, name:, client_id:, authorization_endpoint:, token_endpoint:, profile_map:, client_secret: nil, user_info_endpoint: nil, scopes: [], scope_separator: " ", pkce: false, auth_params: {}, token_params: {}, user_info_method: :get, user_info_headers: {}, user_info_body: nil, **options) ⇒ Object



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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/better_auth/social_providers/base.rb', line 28

def oauth_provider(id:, name:, client_id:, authorization_endpoint:, token_endpoint:, profile_map:, client_secret: nil, user_info_endpoint: nil, scopes: [], scope_separator: " ", pkce: false, auth_params: {}, token_params: {}, user_info_method: :get, user_info_headers: {}, user_info_body: nil, **options)
  opts = normalize_options(options.merge(client_id: client_id, client_secret: client_secret))
  {
    id: id,
    name: name,
    client_id: client_id,
    client_secret: client_secret,
    options: opts,
    create_authorization_url: lambda do |data|
      verifier = value(data, :code_verifier, :codeVerifier)
      selected_scopes = selected_scopes(scopes, opts, data)
      params = {
        client_id: primary_client_id(client_id),
        redirect_uri: opts[:redirect_uri] || value(data, :redirect_uri, :redirectURI),
        response_type: "code",
        scope: selected_scopes.empty? ? nil : selected_scopes.join(scope_separator),
        state: value(data, :state),
        code_challenge: (pkce && verifier) ? pkce_challenge(verifier) : nil,
        code_challenge_method: (pkce && verifier) ? "S256" : nil,
        login_hint: value(data, :loginHint, :login_hint),
        prompt: opts[:prompt]
      }.merge(resolve_hash(auth_params, data, opts))
      authorization_url(option(opts, :authorization_endpoint, :authorizationEndpoint) || authorization_endpoint, params)
    end,
    validate_authorization_code: lambda do |data|
      post_form_json(option(opts, :token_endpoint, :tokenEndpoint) || token_endpoint, {
        client_id: primary_client_id(client_id),
        client_secret: client_secret,
        code: value(data, :code),
        code_verifier: value(data, :code_verifier, :codeVerifier),
        grant_type: "authorization_code",
        redirect_uri: opts[:redirect_uri] || value(data, :redirect_uri, :redirectURI)
      }.merge(resolve_hash(token_params, data, opts)))
    end,
    refresh_access_token: opts[:refresh_access_token] || lambda do |refresh_token|
      refresh_access_token(
        option(opts, :token_endpoint, :tokenEndpoint) || token_endpoint,
        refresh_token,
        client_id: primary_client_id(client_id),
        client_secret: client_secret
      )
    end,
    verify_id_token: opts[:verify_id_token] || lambda do |token, _nonce = nil|
      return false if opts[:disable_id_token_sign_in]

      !decode_jwt_payload(token).empty?
    end,
    get_user_info: lambda do |tokens|
      custom = opts[:get_user_info]
      profile = if custom
        custom.call(tokens)
      elsif 
        (, tokens, method: , headers: , body: )
      else
        decode_jwt_payload(id_token(tokens))
      end
      return nil unless profile
      return profile if provider_user_info?(profile)

      mapped = profile_map.call(profile)
      user_map = opts[:map_profile_to_user]&.call(profile) || {}
      {user: mapped.merge(user_map), data: profile}
    end
  }
end

.option(options, *keys) ⇒ Object



190
191
192
# File 'lib/better_auth/social_providers/base.rb', line 190

def option(options, *keys)
  value(options, *keys)
end

.padded_base64(value) ⇒ Object



320
321
322
# File 'lib/better_auth/social_providers/base.rb', line 320

def padded_base64(value)
  value + ("=" * ((4 - value.length % 4) % 4))
end

.parse_response(response) ⇒ Object



303
304
305
306
307
308
309
310
311
312
# File 'lib/better_auth/social_providers/base.rb', line 303

def parse_response(response)
  return nil unless response.is_a?(Net::HTTPSuccess)

  body = response.body.to_s
  return {} if body.empty?

  JSON.parse(body)
rescue JSON::ParserError
  URI.decode_www_form(body).to_h
end

.pkce_challenge(verifier) ⇒ Object



94
95
96
97
# File 'lib/better_auth/social_providers/base.rb', line 94

def pkce_challenge(verifier)
  digest = OpenSSL::Digest.digest("SHA256", verifier.to_s)
  Base64.urlsafe_encode64(digest, padding: false)
end

.post_form(url, form) ⇒ Object



99
100
101
# File 'lib/better_auth/social_providers/base.rb', line 99

def post_form(url, form)
  post_form_json(url, form)
end

.post_form_json(url, form, headers = {}) ⇒ Object



103
104
105
106
107
108
109
110
# File 'lib/better_auth/social_providers/base.rb', line 103

def post_form_json(url, form, headers = {})
  uri = URI(url)
  request = Net::HTTP::Post.new(uri)
  request.set_form_data(form.compact.transform_keys(&:to_s))
  request["Accept"] = "application/json"
  headers.each { |key, value| request[key.to_s] = value.to_s }
  parse_response(request_json(uri, request))
end

.post_json(url, body = {}, headers = {}) ⇒ Object



129
130
131
132
133
134
135
# File 'lib/better_auth/social_providers/base.rb', line 129

def post_json(url, body = {}, headers = {})
  uri = URI(url)
  request = Net::HTTP::Post.new(uri)
  headers.each { |key, value| request[key.to_s] = value.to_s }
  request.set_form_data(body.compact.transform_keys(&:to_s))
  parse_response(request_json(uri, request))
end

.primary_client_id(client_id) ⇒ Object

Raises:



233
234
235
236
237
238
# File 'lib/better_auth/social_providers/base.rb', line 233

def primary_client_id(client_id)
  value = Array(client_id).first
  raise Error, "CLIENT_ID_AND_SECRET_REQUIRED" if value.to_s.empty?

  value
end

.provider_user_info?(value) ⇒ Boolean

Returns:

  • (Boolean)


249
250
251
# File 'lib/better_auth/social_providers/base.rb', line 249

def provider_user_info?(value)
  value.is_a?(Hash) && (value.key?(:user) || value.key?("user"))
end

.refresh_access_token(token_endpoint, refresh_token, client_id:, client_secret: nil, extra_params: {}) ⇒ Object



144
145
146
147
148
149
150
151
# File 'lib/better_auth/social_providers/base.rb', line 144

def refresh_access_token(token_endpoint, refresh_token, client_id:, client_secret: nil, extra_params: {})
  normalize_tokens(post_form_json(token_endpoint, {
    client_id: client_id,
    client_secret: client_secret,
    grant_type: "refresh_token",
    refresh_token: refresh_token
  }.merge(extra_params || {})))
end

.request_json(uri, request) ⇒ Object



314
315
316
317
318
# File 'lib/better_auth/social_providers/base.rb', line 314

def request_json(uri, request)
  Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 5) do |http|
    http.request(request)
  end
end

.resolve_hash(value, data, options) ⇒ Object



244
245
246
247
# File 'lib/better_auth/social_providers/base.rb', line 244

def resolve_hash(value, data, options)
  resolved = value.respond_to?(:call) ? value.call(data, options) : value
  (resolved || {}).compact
end

.selected_scopes(defaults, options, data) ⇒ Object



224
225
226
227
228
229
230
231
# File 'lib/better_auth/social_providers/base.rb', line 224

def selected_scopes(defaults, options, data)
  scopes = options[:disable_default_scope] ? [] : Array(defaults).dup
  scopes.concat(Array(options[:scope])) if options[:scope]
  scopes.concat(Array(options[:scopes])) if options[:scopes]
  request_scopes = value(data, :scopes)
  scopes.concat(Array(request_scopes)) if request_scopes
  scopes
end

.stringify_keys(hash) ⇒ Object



290
291
292
# File 'lib/better_auth/social_providers/base.rb', line 290

def stringify_keys(hash)
  hash.each_with_object({}) { |(key, value), memo| memo[key.to_s] = value }
end

.time_from(value) ⇒ Object



294
295
296
297
298
299
300
301
# File 'lib/better_auth/social_providers/base.rb', line 294

def time_from(value)
  return value if value.is_a?(Time)
  return nil if value.nil? || value.to_s.empty?

  Time.parse(value.to_s)
rescue ArgumentError
  nil
end

.value(hash, *keys) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
# File 'lib/better_auth/social_providers/base.rb', line 178

def value(hash, *keys)
  return nil unless hash

  keys.each do |key|
    return hash[key] if hash.respond_to?(:key?) && hash.key?(key)

    string_key = key.to_s
    return hash[string_key] if hash.respond_to?(:key?) && hash.key?(string_key)
  end
  nil
end

.verify_jwt_with_jwks(token, jwks:, jwks_endpoint:, algorithms:, issuers:, audience:, nonce: nil, max_age: 3600) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/better_auth/social_providers/base.rb', line 262

def verify_jwt_with_jwks(token, jwks:, jwks_endpoint:, algorithms:, issuers:, audience:, nonce: nil, max_age: 3600)
  jwks_payload = jwks.respond_to?(:call) ? jwks.call : jwks
  jwks_payload ||= fetch_jwks(jwks_endpoint)
  return nil unless jwks_payload

  options = {
    algorithms: algorithms,
    jwks: JWT::JWK::Set.new(stringify_keys(jwks_payload)),
    aud: audience,
    verify_aud: true
  }
  options[:iss] = issuers if issuers
  options[:verify_iss] = true if issuers
  payload, = JWT.decode(token.to_s, nil, true, options)
  return nil if nonce && payload["nonce"] != nonce
  return nil if max_age && payload["iat"] && payload["iat"].to_i < Time.now.to_i - max_age.to_i

  payload
rescue JWT::DecodeError, JSON::ParserError, ArgumentError, OpenSSL::PKey::PKeyError
  nil
end