class UsersController < ApplicationController def create return head :unprocessable_entity if request.remote_ip.blank? return head :forbidden if ip_address_banned? user = nil User.transaction do user = User.create!(inheritance_code: SecureRandom.uuid, role: :guest) attach_ip_address!(user) end render json: { code: user.inheritance_code, user: user.slice(:id, :name, :inheritance_code, :role) }, status: :created end def verify return head :unprocessable_entity if request.remote_ip.blank? return head :forbidden if ip_address_banned? user = User.find_by(inheritance_code: params[:code]) return render json: { valid: false } unless user return head :forbidden if user.banned? attach_ip_address!(user) render json: { valid: true, user: user.slice(:id, :name, :inheritance_code, :role) } end def renew return head :unauthorized unless current_user user = current_user user.inheritance_code = SecureRandom.uuid user.save! render json: { code: user.inheritance_code } end def me user = User.find_by(inheritance_code: params[:code]) return head :not_found unless user render json: user.slice(:id, :name, :inheritance_code, :role) end def update user = current_user return head :unauthorized if user&.id != params[:id].to_i name = params[:name] return head :bad_request if name.blank? if user.update(name:) render json: user.slice(:id, :name, :inheritance_code, :role), status: :ok else render json: user.errors, status: :unprocessable_entity end end private def attach_ip_address! user ip_bin = IPAddr.new(request.remote_ip).hton ip_address = IpAddress.create_or_find_by!(ip_address: ip_bin) UserIp.create_or_find_by!(user:, ip_address:) end def ip_address_banned? ip_address = IpAddress.find_by(ip_address: IPAddr.new(request.remote_ip).hton) return false unless ip_address ip_address.banned? end end