<commit_before># frozen_string_literal: true

class APIKeysController < ApplicationController
  before_action :authenticate_user!
  before_action :set_key, except: [:index, :new, :create, :mine]
  before_action :verify_admin, except: [:owner_edit, :owner_update, :owner_revoke, :mine]
  before_action :verify_ownership, only: [:owner_edit, :owner_update, :owner_revoke]

  def index
    @keys = APIKey.all
  end

  def revoke_write_tokens
    if APIToken.where(api_key: @key).destroy_all
      flash[:success] = "Successfully removed all write tokens belonging to #{@key.app_name}."
    else
      flash[:danger] = 'Failed to revoke all API write tokens - tokens need to be removed manually.'
    end
    redirect_to url_for(controller: :api_keys, action: :index)
  end

  def new
    @key = APIKey.new
    @key.key = Digest::SHA256.hexdigest("#{rand(0..9e9)}#{Time.now}")
  end

  def create
    @key = APIKey.new(key_params)
    @key.save!
    flash[:success] = "Successfully registered API key #{@key.key}"
    redirect_to :admin_new_key
  end

  def edit; end

  def update
    if @key.update key_params
      flash[:success] = 'Successfully updated.'
      redirect_to url_for(controller: :api_keys, action: :index)<commit_msg>Security++(tm): Better random API keys<commit_after># frozen_string_literal: true

class APIKeysController < ApplicationController
  before_action :authenticate_user!
  before_action :set_key, except: [:index, :new, :create, :mine]
  before_action :verify_admin, except: [:owner_edit, :owner_update, :owner_revoke, :mine]
  before_action :verify_ownership, only: [:owner_edit, :owner_update, :owner_revoke]

  def index
    @keys = APIKey.all
  end

  def revoke_write_tokens
    if APIToken.where(api_key: @key).destroy_all
      flash[:success] = "Successfully removed all write tokens belonging to #{@key.app_name}."
    else
      flash[:danger] = 'Failed to revoke all API write tokens - tokens need to be removed manually.'
    end
    redirect_to url_for(controller: :api_keys, action: :index)
  end

  def new
    @key = APIKey.new
    @key.key = SecureRandom.hex 32
  end

  def create
    @key = APIKey.new(key_params)
    @key.save!
    flash[:success] = "Successfully registered API key #{@key.key}"
    redirect_to :admin_new_key
  end

  def edit; end

  def update
    if @key.update key_params
      flash[:success] = 'Successfully updated.'
      redirect_to url_for(controller: :api_keys, action: :index)
{'fraction_non_alphanumeric': 0.10839445802770986, 'fraction_numerical': 0.0032599837000814994, 'mean_word_length': 4.082815734989648, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6524850', 'n_tokens_mistral': 819, 'n_tokens_neox': 797, 'n_words': 216}