sign_in_token_authentication_concern.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # frozen_string_literal: true
  2. module SignInTokenAuthenticationConcern
  3. extend ActiveSupport::Concern
  4. included do
  5. prepend_before_action :authenticate_with_sign_in_token, if: :sign_in_token_required?, only: [:create]
  6. end
  7. def sign_in_token_required?
  8. find_user&.suspicious_sign_in?(request.remote_ip)
  9. end
  10. def valid_sign_in_token_attempt?(user)
  11. Devise.secure_compare(user.sign_in_token, user_params[:sign_in_token_attempt])
  12. end
  13. def authenticate_with_sign_in_token
  14. user = self.resource = find_user
  15. if user_params[:sign_in_token_attempt].present? && session[:attempt_user_id]
  16. authenticate_with_sign_in_token_attempt(user)
  17. elsif user.present? && user.external_or_valid_password?(user_params[:password])
  18. prompt_for_sign_in_token(user)
  19. end
  20. end
  21. def authenticate_with_sign_in_token_attempt(user)
  22. if valid_sign_in_token_attempt?(user)
  23. session.delete(:attempt_user_id)
  24. remember_me(user)
  25. sign_in(user)
  26. else
  27. flash.now[:alert] = I18n.t('users.invalid_sign_in_token')
  28. prompt_for_sign_in_token(user)
  29. end
  30. end
  31. def prompt_for_sign_in_token(user)
  32. if user.sign_in_token_expired?
  33. user.generate_sign_in_token && user.save
  34. UserMailer.sign_in_token(user, request.remote_ip, request.user_agent, Time.now.utc.to_s).deliver_later!
  35. end
  36. set_locale do
  37. session[:attempt_user_id] = user.id
  38. @body_classes = 'lighter'
  39. render :sign_in_token
  40. end
  41. end
  42. end