aces / cbrain

CBRAIN is a flexible Ruby on Rails framework for accessing and processing of large data on high-performance computing infrastructures.
GNU General Public License v3.0
70 stars 43 forks source link

Push keys #1388

Closed natacha-beck closed 2 months ago

prioux commented 2 months ago

The changes are really complicated... can you simpliify this a bit?

prioux commented 2 months ago

Suggestion. I cleaned up the original code at the same time. Not tested.

  def push_keys #:nodoc:
    @user = User.find(params[:id])
    cb_error "You don't have permission to update this user.", :redirect => user_path(@user) unless edit_permission?(@user)

    # Prep all info
    push_bids        = params[:push_keys_to].presence
    bourreau_to_push = Bourreau.find_all_accessible_by_user(@user).where(:id => push_bids).to_a
    ssh_key          = @user.ssh_key rescue nil

    # Validate things
    cb_error "No servers selected.",        :redirect => user_path(@user) if bourreau_to_push.empty?
    cb_error "No user SSH key exists yet.", :redirect => user_path(@user) if ! ssh_key

    # Get key for user
    pub_key  = ssh_key.public_key
    priv_key = ssh_key.send(:private_key, "I Know What I Am Doing")

    # Push to each bourreau
    ok_names = []; err_names = []
    bourreau_to_push.each do |bourreau|
      command          = RemoteCommand.new(:command           => 'push_ssh_keys',
                                           :requester_user_id => @user.id,
                                           :ssh_key_pub       => pub_key,
                                           :ssh_key_priv      => priv_key,
                                          )
      answer = bourreau.send_command(command) rescue nil
      if answer&.command_execution_status == 'OK'
        ok_names << bourreau.name
      else
        err_names << bourreau.name
      end
    end

    respond_to do |format|
      format.html {
        flash[:notice] = "Pushed user SSH key to #{ok_names.join(", ")}.\n"     if ok_names.present?
        flash[:error]  = "Could not push SSH key to #{err_names.join(", ")}.\n" if err_names.present?
        redirect_to :action => :show
      }
      format.json {
        status = 'OK'
        status = 'Mixed'   if (ok_names.present? && err_names.present?)
        status = 'Failed'  if (ok_names.blank?   && err_names.present?)
        render :json => { :status => status, :pushed_ok => ok_names, :push_failed => err_names }
      }
    end
  end