signup.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Service::User::Signup < Service::Base
  3. attr_reader :user_data, :resend
  4. def initialize(user_data:, resend: false)
  5. super()
  6. @user_data = user_data
  7. @resend = resend
  8. @path = {
  9. signup: 'desktop/signup/verify/',
  10. taken: 'desktop/reset-password/verify/'
  11. }
  12. end
  13. def execute
  14. Service::CheckFeatureEnabled.new(name: 'user_create_account').execute
  15. if resend
  16. user = ::User.find_by(email: user_data[:email].downcase)
  17. # The result is always positive to avoid leaking of existing user accounts.
  18. return true if !user || user.verified == true
  19. else
  20. PasswordPolicy.new(user_data[:password]).valid!
  21. return true if user_with_email_exists!
  22. user = create_user
  23. end
  24. result = ::User.signup_new_token(user)
  25. raise TokenGenerationError if !result || !result[:token]
  26. result[:url] = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#{@path[:signup]}#{result[:token].token}"
  27. NotificationFactory::Mailer.notification(
  28. template: 'signup',
  29. user: user,
  30. objects: result,
  31. )
  32. true
  33. end
  34. class TokenGenerationError < StandardError
  35. def initialize
  36. super(__('The token could not be generated.'))
  37. end
  38. end
  39. private
  40. def user_with_email_exists!
  41. existing_user = User.find_by(email: user_data[:email].downcase.strip)
  42. return false if existing_user.blank?
  43. result = User.password_reset_new_token(existing_user.email)
  44. result[:url] = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#{@path[:taken]}#{result[:token].token}"
  45. NotificationFactory::Mailer.notification(
  46. template: 'signup_taken_reset',
  47. user: existing_user,
  48. objects: result
  49. )
  50. true
  51. end
  52. def create_user
  53. user = User.new(user_data)
  54. user.role_ids = Role.signup_role_ids
  55. user.source = 'signup'
  56. user.skip_ensure_uniq_email = true
  57. user.validate!
  58. UserInfo.ensure_current_user_id do
  59. user.save!
  60. end
  61. user
  62. end
  63. end