The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

82 lines
2.4 KiB

  1. # frozen_string_literal: true
  2. module Omniauthable
  3. extend ActiveSupport::Concern
  4. TEMP_EMAIL_PREFIX = 'change@me'
  5. TEMP_EMAIL_REGEX = /\Achange@me/
  6. included do
  7. def omniauth_providers
  8. Devise.omniauth_configs.keys
  9. end
  10. def email_verified?
  11. email && email !~ TEMP_EMAIL_REGEX
  12. end
  13. end
  14. class_methods do
  15. def find_for_oauth(auth, signed_in_resource = nil)
  16. # EOLE-SSO Patch
  17. auth.uid = (auth.uid[0][:uid] || auth.uid[0][:user]) if auth.uid.is_a? Hashie::Array
  18. identity = Identity.find_for_oauth(auth)
  19. # If a signed_in_resource is provided it always overrides the existing user
  20. # to prevent the identity being locked with accidentally created accounts.
  21. # Note that this may leave zombie accounts (with no associated identity) which
  22. # can be cleaned up at a later date.
  23. user = signed_in_resource ? signed_in_resource : identity.user
  24. user = create_for_oauth(auth) if user.nil?
  25. if identity.user.nil?
  26. identity.user = user
  27. identity.save!
  28. end
  29. user
  30. end
  31. def create_for_oauth(auth)
  32. # Check if the user exists with provided email if the provider gives us a
  33. # verified email. If no verified email was provided or the user already
  34. # exists, we assign a temporary email and ask the user to verify it on
  35. # the next step via Auth::ConfirmationsController.finish_signup
  36. user = User.new(user_params_from_auth(auth))
  37. user.account.avatar_remote_url = auth.info.image if auth.info.image =~ /\A#{URI.regexp(%w(http https))}\z/
  38. user.skip_confirmation!
  39. user.save!
  40. user
  41. end
  42. private
  43. def user_params_from_auth(auth)
  44. email_is_verified = auth.info.email && (auth.info.verified || auth.info.verified_email)
  45. email = auth.info.email if email_is_verified && !User.exists?(email: auth.info.email)
  46. {
  47. email: email ? email : "#{TEMP_EMAIL_PREFIX}-#{auth.uid}-#{auth.provider}.com",
  48. password: Devise.friendly_token[0, 20],
  49. account_attributes: {
  50. username: ensure_unique_username(auth.uid),
  51. display_name: [auth.info.first_name, auth.info.last_name].join(' '),
  52. },
  53. }
  54. end
  55. def ensure_unique_username(starting_username)
  56. username = starting_username
  57. i = 0
  58. while Account.exists?(username: username)
  59. i += 1
  60. username = "#{starting_username}_#{i}"
  61. end
  62. username
  63. end
  64. end
  65. end