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.

93 lines
2.8 KiB

  1. # frozen_string_literal: true
  2. module Omniauthable
  3. extend ActiveSupport::Concern
  4. TEMP_EMAIL_PREFIX = 'change@me'
  5. TEMP_EMAIL_REGEX = /\A#{TEMP_EMAIL_PREFIX}/.freeze
  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)
  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. strategy = Devise.omniauth_configs[auth.provider.to_sym].strategy
  38. assume_verified = strategy&.security&.assume_email_is_verified
  39. email_is_verified = auth.info.verified || auth.info.verified_email || assume_verified
  40. email = auth.info.verified_email || auth.info.email
  41. email = nil unless email_is_verified
  42. user = User.find_by(email: email) if email_is_verified
  43. return user unless user.nil?
  44. user = User.new(user_params_from_auth(email, auth))
  45. user.account.avatar_remote_url = auth.info.image if auth.info.image =~ /\A#{URI.regexp(%w(http https))}\z/
  46. user.skip_confirmation!
  47. user.save!
  48. user
  49. end
  50. private
  51. def user_params_from_auth(email, auth)
  52. {
  53. email: email || "#{TEMP_EMAIL_PREFIX}-#{auth.uid}-#{auth.provider}.com",
  54. password: Devise.friendly_token[0, 20],
  55. agreement: true,
  56. external: true,
  57. account_attributes: {
  58. username: ensure_unique_username(auth.uid),
  59. display_name: auth.info.full_name || [auth.info.first_name, auth.info.last_name].join(' '),
  60. },
  61. }
  62. end
  63. def ensure_unique_username(starting_username)
  64. username = starting_username
  65. i = 0
  66. while Account.exists?(username: username, domain: nil)
  67. i += 1
  68. username = "#{starting_username}_#{i}"
  69. end
  70. username
  71. end
  72. end
  73. end