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.

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