闭社主体 forked from https://github.com/tootsuite/mastodon
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.

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