<commit_before># frozen_string_literal: true

class UsersController < ApplicationController

  helper PaginableHelper
  helper PermsHelper
  include ConditionalUserMailer
  after_action :verify_authorized
  respond_to :html

  ##
  # GET - List of all users for an organisation
  # Displays number of roles[was project_group], name, email, and last sign in
  def admin_index
    authorize User
    if current_user.can_super_admin?
      @users = User.page(1)
    else
      @users = current_user.org.users.page(1)
    end
  end

  ##
  # GET - Displays the permissions available to the selected user
  # Permissions which the user already has are pre-selected
  # Selecting new permissions and saving calls the admin_update_permissions action
  def admin_grant_permissions
    user = User.find(params[:id])
    authorize user

    # Super admin can grant any Perm, org admins can only grant Perms they
    # themselves have access to
    if current_user.can_super_admin?
      perms = Perm.all
    else
      perms = current_user.perms
    end

    render json: {
      "user" => {
        "id" => user.id,
        "html" => render_to_string(partial: "users/admin_grant_permissions",
                                   locals: { user: user, perms: perms },
                                   formats: [:html])
      }
    }.to_json
  end

  ##
  # POST - updates the permissions for a user
  # redirects to the admin_index action
  # should add validation that the perms given are current perms of the current_user
  def admin_update_permissions
    @user = User.find(params[:id])
    authorize @user
    perms_ids = params[:perm_ids].blank? ? [] : params[:perm_ids].map(&:to_i)
    perms = Perm.where(id: perms_ids)
    privileges_changed = false
    current_user.perms.each do |perm|
      if @user.perms.include? perm
        if ! perms.include? perm
          @user.perms.delete(perm)
          if perm.id == Perm.use_api.id
            @user.remove_token!
          end
          privileges_changed = true
        end
      else
        if perms.include? perm
          @user.perms << perm
          if perm.id == Perm.use_api.id
            @user.keep_or_generate_token!
            privileges_changed = true
          end
        end
      end
    end

    if @user.save
      if privileges_changed
        deliver_if(recipients: @user, key: "users.admin_privileges") do |r|
          UserMailer.admin_privileges(r).deliver_now
        end
      end
      render(json: {
        code: 1,
        msg: success_message(perms.first, _("saved")),
        current_privileges: render_to_string(partial: "users/current_privileges",
                                             locals: { user: @user }, formats: [:html])
        })
    else
      render(json: { code: 0, msg: failure_message(@user, _("updated")) })
    end
  end

  def update_email_preferences
    prefs = params[:prefs]
    authorize User
    pref = current_user.pref
    # does user not have prefs?
    if pref.blank?
      pref = Pref.new
      pref.settings = {}
      pref.user = current_user
    end
    pref.settings[:email] = booleanize_hash(prefs)
    pref.save

    # Include active tab in redirect path
    redirect_to "#{edit_user_registration_path}\#notification-preferences",<commit_msg>Change success message on permission change<commit_after># frozen_string_literal: true

class UsersController < ApplicationController

  helper PaginableHelper
  helper PermsHelper
  include ConditionalUserMailer
  after_action :verify_authorized
  respond_to :html

  ##
  # GET - List of all users for an organisation
  # Displays number of roles[was project_group], name, email, and last sign in
  def admin_index
    authorize User
    if current_user.can_super_admin?
      @users = User.page(1)
    else
      @users = current_user.org.users.page(1)
    end
  end

  ##
  # GET - Displays the permissions available to the selected user
  # Permissions which the user already has are pre-selected
  # Selecting new permissions and saving calls the admin_update_permissions action
  def admin_grant_permissions
    user = User.find(params[:id])
    authorize user

    # Super admin can grant any Perm, org admins can only grant Perms they
    # themselves have access to
    if current_user.can_super_admin?
      perms = Perm.all
    else
      perms = current_user.perms
    end

    render json: {
      "user" => {
        "id" => user.id,
        "html" => render_to_string(partial: "users/admin_grant_permissions",
                                   locals: { user: user, perms: perms },
                                   formats: [:html])
      }
    }.to_json
  end

  ##
  # POST - updates the permissions for a user
  # redirects to the admin_index action
  # should add validation that the perms given are current perms of the current_user
  def admin_update_permissions
    @user = User.find(params[:id])
    authorize @user
    perms_ids = params[:perm_ids].blank? ? [] : params[:perm_ids].map(&:to_i)
    perms = Perm.where(id: perms_ids)
    privileges_changed = false
    current_user.perms.each do |perm|
      if @user.perms.include? perm
        if ! perms.include? perm
          @user.perms.delete(perm)
          if perm.id == Perm.use_api.id
            @user.remove_token!
          end
          privileges_changed = true
        end
      else
        if perms.include? perm
          @user.perms << perm
          if perm.id == Perm.use_api.id
            @user.keep_or_generate_token!
            privileges_changed = true
          end
        end
      end
    end

    if @user.save
      if privileges_changed
        deliver_if(recipients: @user, key: "users.admin_privileges") do |r|
          UserMailer.admin_privileges(r).deliver_now
        end
      end
      render(json: {
        code: 1,
        msg: _("Successfully saved permissions"),
        current_privileges: render_to_string(partial: "users/current_privileges",
                                             locals: { user: @user }, formats: [:html])
        })
    else
      render(json: { code: 0, msg: failure_message(@user, _("updated")) })
    end
  end

  def update_email_preferences
    prefs = params[:prefs]
    authorize User
    pref = current_user.pref
    # does user not have prefs?
    if pref.blank?
      pref = Pref.new
      pref.settings = {}
      pref.user = current_user
    end
    pref.settings[:email] = booleanize_hash(prefs)
    pref.save

    # Include active tab in redirect path
    redirect_to "#{edit_user_registration_path}\#notification-preferences",
{'fraction_non_alphanumeric': 0.08352385307117817, 'fraction_numerical': 0.0012193263222069807, 'mean_word_length': 2.3275862068965516, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1668554', 'n_tokens_mistral': 1973, 'n_tokens_neox': 1936, 'n_words': 531}