Module: BetterAuth::SocialProviders::Base

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

Class Method Summary collapse

Class Method Details

.access_token(tokens) ⇒ Object



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

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

.apply_profile_mapping(user, profile, options) ⇒ Object



264
265
266
# File 'lib/better_auth/social_providers/base.rb', line 264

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

.authorization_url(endpoint, params) ⇒ Object



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

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

.basic_auth_headers(client_id, client_secret) ⇒ Object



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

def basic_auth_headers(client_id, client_secret)
  {"Authorization" => "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"}
end

.decode_jwt_payload(token) ⇒ Object



277
278
279
280
281
282
283
284
# File 'lib/better_auth/social_providers/base.rb', line 277

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



308
309
310
311
312
# File 'lib/better_auth/social_providers/base.rb', line 308

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



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

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



125
126
127
128
129
130
131
132
133
# File 'lib/better_auth/social_providers/base.rb', line 125

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



118
119
120
121
122
123
# File 'lib/better_auth/social_providers/base.rb', line 118

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



194
195
196
# File 'lib/better_auth/social_providers/base.rb', line 194

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

.normalize_options(options) ⇒ Object



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

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,
    userPoolId: :user_pool_id,
    requireClientSecret: :require_client_secret,
    configId: :config_id,
    loginUrl: :login_url
  }.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



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

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, require_code_verifier: false, auth_params: {}, token_params: {}, token_authentication: :post, user_info_method: :get, user_info_headers: {}, user_info_body: nil, **options) ⇒ Object



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
93
94
95
96
97
98
# File 'lib/better_auth/social_providers/base.rb', line 29

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, require_code_verifier: false, auth_params: {}, token_params: {}, token_authentication: :post, 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))
  primary_id = primary_client_id(client_id)
  {
    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)
      raise Error, "codeVerifier is required for #{name}" if require_code_verifier && verifier.to_s.empty?

      selected_scopes = selected_scopes(scopes, opts, data)
      params = {
        client_id: primary_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|
      token_form = {
        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))
      post_token_form(
        option(opts, :token_endpoint, :tokenEndpoint) || token_endpoint,
        token_form,
        client_id: primary_id,
        client_secret: client_secret,
        authentication: token_authentication
      )
    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_id,
        client_secret: client_secret,
        authentication: token_authentication
      )
    end,
    verify_id_token: opts[:verify_id_token],
    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



210
211
212
# File 'lib/better_auth/social_providers/base.rb', line 210

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

.padded_base64(value) ⇒ Object



342
343
344
# File 'lib/better_auth/social_providers/base.rb', line 342

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

.parse_response(response) ⇒ Object



327
328
329
330
331
332
333
334
335
336
# File 'lib/better_auth/social_providers/base.rb', line 327

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



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

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

.post_form(url, form) ⇒ Object



105
106
107
# File 'lib/better_auth/social_providers/base.rb', line 105

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

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



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

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



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

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

.post_token_form(token_endpoint, form, client_id:, client_secret: nil, authentication: :post, headers: {}) ⇒ Object



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

def post_token_form(token_endpoint, form, client_id:, client_secret: nil, authentication: :post, headers: {})
  case authentication&.to_sym
  when :basic
    post_form_json(token_endpoint, form.compact, basic_auth_headers(client_id, client_secret).merge(headers))
  else
    post_form_json(token_endpoint, {
      client_id: client_id,
      client_secret: client_secret
    }.merge(form), headers)
  end
end

.primary_client_id(client_id) ⇒ Object

Raises:



257
258
259
260
261
262
# File 'lib/better_auth/social_providers/base.rb', line 257

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)


273
274
275
# File 'lib/better_auth/social_providers/base.rb', line 273

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: {}, authentication: :post) ⇒ Object



150
151
152
153
154
155
# File 'lib/better_auth/social_providers/base.rb', line 150

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

.request_json(uri, request) ⇒ Object



338
339
340
# File 'lib/better_auth/social_providers/base.rb', line 338

def request_json(uri, request)
  HTTPClient.request(uri, request)
end

.resolve_hash(value, data, options) ⇒ Object



268
269
270
271
# File 'lib/better_auth/social_providers/base.rb', line 268

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



248
249
250
251
252
253
254
255
# File 'lib/better_auth/social_providers/base.rb', line 248

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



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

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

.time_from(value) ⇒ Object



318
319
320
321
322
323
324
325
# File 'lib/better_auth/social_providers/base.rb', line 318

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



198
199
200
201
202
203
204
205
206
207
208
# File 'lib/better_auth/social_providers/base.rb', line 198

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



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/better_auth/social_providers/base.rb', line 286

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, Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError
  nil
end