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.

56 lines
1.7 KiB

  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. if user_params[:email].present?
  15. user = self.resource = find_user_from_params
  16. prompt_for_sign_in_token(user) if user&.external_or_valid_password?(user_params[:password])
  17. elsif session[:attempt_user_id]
  18. user = self.resource = User.find_by(id: session[:attempt_user_id])
  19. return if user.nil?
  20. if session[:attempt_user_updated_at] != user.updated_at.to_s
  21. restart_session
  22. elsif user_params.key?(:sign_in_token_attempt)
  23. authenticate_with_sign_in_token_attempt(user)
  24. end
  25. end
  26. end
  27. def authenticate_with_sign_in_token_attempt(user)
  28. if valid_sign_in_token_attempt?(user)
  29. on_authentication_success(user, :sign_in_token)
  30. else
  31. on_authentication_failure(user, :sign_in_token, :invalid_sign_in_token)
  32. flash.now[:alert] = I18n.t('users.invalid_sign_in_token')
  33. prompt_for_sign_in_token(user)
  34. end
  35. end
  36. def prompt_for_sign_in_token(user)
  37. if user.sign_in_token_expired?
  38. user.generate_sign_in_token && user.save
  39. UserMailer.sign_in_token(user, request.remote_ip, request.user_agent, Time.now.utc.to_s).deliver_later!
  40. end
  41. set_attempt_session(user)
  42. @body_classes = 'lighter'
  43. set_locale { render :sign_in_token }
  44. end
  45. end