2022-04-06 20:58:12 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class SuspiciousSignInDetector
|
|
|
|
IPV6_TOLERANCE_MASK = 64
|
|
|
|
IPV4_TOLERANCE_MASK = 16
|
2024-05-23 01:16:21 +02:00
|
|
|
ENABLE_SUSPICIOUS_SIGN_IN = ENV['ENABLE_SUSPICIOUS_SIGN_IN'] != 'false'
|
2022-04-06 20:58:12 +02:00
|
|
|
|
|
|
|
def initialize(user)
|
|
|
|
@user = user
|
|
|
|
end
|
|
|
|
|
|
|
|
def suspicious?(request)
|
2024-05-23 01:16:21 +02:00
|
|
|
!sufficient_security_measures? && !freshly_signed_up? && !previously_seen_ip?(request) if DISABLE_SUSPICIOUS_SIGN_IN
|
2022-04-06 20:58:12 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def sufficient_security_measures?
|
|
|
|
@user.otp_required_for_login?
|
|
|
|
end
|
|
|
|
|
|
|
|
def previously_seen_ip?(request)
|
2024-01-24 12:51:09 +01:00
|
|
|
@user.ips.exists?(['ip <<= ?', masked_ip(request)])
|
2022-04-06 20:58:12 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def freshly_signed_up?
|
|
|
|
@user.current_sign_in_at.blank?
|
|
|
|
end
|
|
|
|
|
|
|
|
def masked_ip(request)
|
|
|
|
masked_ip_addr = begin
|
|
|
|
ip_addr = IPAddr.new(request.remote_ip)
|
|
|
|
|
|
|
|
if ip_addr.ipv6?
|
|
|
|
ip_addr.mask(IPV6_TOLERANCE_MASK)
|
|
|
|
else
|
|
|
|
ip_addr.mask(IPV4_TOLERANCE_MASK)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
"#{masked_ip_addr}/#{masked_ip_addr.prefix}"
|
|
|
|
end
|
|
|
|
end
|