Thursday, September 19, 2024 11:51:17 PM
> settings

Customize


Authenticate

> user_aliases_controller.rb
# frozen_string_literal: true

class UserAliasesController < DashboardController
  def create
    sanitized_params = alias_params

    target = extract_community_or_server(sanitized_params)
    return render json: {}, status: :not_found if target.nil?

    # This was a nice side effect of the design. This can be community_id or server_id
    server_or_community = target.class.to_s.downcase

    user_alias = current_user.id_aliases.create!(
      "#{server_or_community}_id" => target.id,
      value: sanitized_params[:value]
    )

    render json: {id: user_alias.uuid}, status: :ok
  end

  def update
    sanitized_params = alias_params

    user_alias = current_user.id_aliases.where(uuid: sanitized_params[:id]).first
    return render json: {}, status: :not_found if user_alias.nil?

    target = extract_community_or_server(sanitized_params)
    return render json: {}, status: :not_found if target.nil?

    # Reset both targets in case the user decided to switch 
    user_alias.server_id = nil
    user_alias.community_id = nil

    # This was a nice side effect of the design. This can be community_id or server_id
    server_or_community = target.class.to_s.downcase
    user_alias.update!(
      "#{server_or_community}_id" => target.id,
      value: sanitized_params[:value]
    )

    render json: {}, status: :ok
  end

  def destroy
    # A rare instance where I don't really care about security here.
    # What are they gonna do? Delete their own aliases? ;)
    current_user.id_aliases.where(uuid: params[:id]).first&.destroy
    render json: {}, status: :ok
  end

  private

  def alias_params
    params.require(:user_alias).permit(:id, :type, :value, target: {})
  end

  def extract_community_or_server(data)
    target_id = data.dig(:target, :id)

    case data[:type]
    when "community"
      Community.find_by_community_id(target_id)
    when "server"
      Server.find_by_server_id(target_id)
    else
      nil
    end
  end
end
All opinions represented herein are my own
- © 2024 itsthedevman
- build 3c15a1b