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.

94 lines
2.2 KiB

  1. # frozen_string_literal: true
  2. class Auth::SessionsController < Devise::SessionsController
  3. include Devise::Controllers::Rememberable
  4. layout 'auth'
  5. skip_before_action :require_no_authentication, only: [:create]
  6. skip_before_action :check_suspension, only: [:destroy]
  7. prepend_before_action :authenticate_with_two_factor, if: :two_factor_enabled?, only: [:create]
  8. def create
  9. super do |resource|
  10. remember_me(resource)
  11. flash.delete(:notice)
  12. end
  13. end
  14. def destroy
  15. super
  16. flash.delete(:notice)
  17. end
  18. protected
  19. def find_user
  20. if session[:otp_user_id]
  21. User.find(session[:otp_user_id])
  22. elsif user_params[:email]
  23. User.find_for_authentication(email: user_params[:email])
  24. end
  25. end
  26. def user_params
  27. params.require(:user).permit(:email, :password, :otp_attempt)
  28. end
  29. def after_sign_in_path_for(resource)
  30. last_url = stored_location_for(:user)
  31. if home_paths(resource).include?(last_url)
  32. root_path
  33. else
  34. last_url || root_path
  35. end
  36. end
  37. def two_factor_enabled?
  38. find_user.try(:otp_required_for_login?)
  39. end
  40. def valid_otp_attempt?(user)
  41. user.validate_and_consume_otp!(user_params[:otp_attempt]) ||
  42. user.invalidate_otp_backup_code!(user_params[:otp_attempt])
  43. rescue OpenSSL::Cipher::CipherError => _error
  44. false
  45. end
  46. def authenticate_with_two_factor
  47. user = self.resource = find_user
  48. if user_params[:otp_attempt].present? && session[:otp_user_id]
  49. authenticate_with_two_factor_via_otp(user)
  50. elsif user && user.valid_password?(user_params[:password])
  51. prompt_for_two_factor(user)
  52. end
  53. end
  54. def authenticate_with_two_factor_via_otp(user)
  55. if valid_otp_attempt?(user)
  56. session.delete(:otp_user_id)
  57. remember_me(user)
  58. sign_in(user)
  59. else
  60. flash.now[:alert] = I18n.t('users.invalid_otp_token')
  61. prompt_for_two_factor(user)
  62. end
  63. end
  64. def prompt_for_two_factor(user)
  65. session[:otp_user_id] = user.id
  66. render :two_factor
  67. end
  68. private
  69. def home_paths(resource)
  70. paths = [about_path]
  71. if single_user_mode? && resource.is_a?(User)
  72. paths << short_account_path(username: resource.account)
  73. end
  74. paths
  75. end
  76. end