Add tracking of certain important user actions. These events include: * Logins * Logouts * Failed login attempts * Account creations * Account deletions * Password reset requests * Password changes * Email address changes This is similar to the mod actions log, except for account activity related to a single user. The information tracked includes the user, the event type (login, logout, etc), the timestamp, the user's IP address, IP geolocation information, the user's browser user agent, and the user's session ID from their session cookie. This information is visible to mods only. This is done with three models. The UserEvent model tracks the event type (login, logout, password change, etc) and the user. The UserEvent is tied to a UserSession, which contains the user's IP address and browser metadata. Finally, the IpGeolocation model contains the geolocation information for IPs, including the city, country, ISP, and whether the IP is a proxy. This tracking will be used for a few purposes: * Letting users view their account history, to detect things like logins from unrecognized IPs, failed logins attempts, password changes, etc. * Rate limiting failed login attempts. * Detecting sockpuppet accounts using their login history. * Detecting unauthorized account sharing.
55 lines
1.6 KiB
Ruby
55 lines
1.6 KiB
Ruby
# A UserEvent is used to track important events related to a user's account,
|
|
# such as signups, logins, password changes, etc. A UserEvent is associated
|
|
# with a UserSession, which contains the IP and browser information associated
|
|
# with the event.
|
|
|
|
class UserEvent < ApplicationRecord
|
|
belongs_to :user
|
|
belongs_to :user_session
|
|
|
|
enum category: {
|
|
login: 0,
|
|
failed_login: 50,
|
|
logout: 100,
|
|
user_creation: 200,
|
|
user_deletion: 300,
|
|
password_reset: 400,
|
|
password_change: 500,
|
|
email_change: 600,
|
|
}
|
|
|
|
delegate :session_id, :ip_addr, :ip_geolocation, to: :user_session
|
|
delegate :country, :city, :is_proxy?, to: :ip_geolocation, allow_nil: true
|
|
|
|
def self.visible(user)
|
|
if user.is_moderator?
|
|
all
|
|
else
|
|
where(user: user)
|
|
end
|
|
end
|
|
|
|
def self.search(params)
|
|
q = search_attributes(params, :id, :created_at, :updated_at, :category, :user, :user_session)
|
|
q = q.apply_default_order(params)
|
|
q
|
|
end
|
|
|
|
concerning :ConstructorMethods do
|
|
class_methods do
|
|
# Build an event but don't save it yet. The caller is expected to update the user, which will save the event.
|
|
def build_from_request(user, category, request)
|
|
ip_addr = request.remote_ip
|
|
IpGeolocation.create_or_update!(ip_addr)
|
|
user_session = UserSession.new(session_id: request.session[:session_id], ip_addr: ip_addr, user_agent: request.user_agent)
|
|
|
|
user.user_events.build(user: user, category: category, user_session: user_session)
|
|
end
|
|
|
|
def create_from_request!(...)
|
|
build_from_request(...).save!
|
|
end
|
|
end
|
|
end
|
|
end
|