|
| 1 | +class Admin::UsersController < ApplicationController |
| 2 | + before_action :ensure_admin! |
| 3 | + before_action :set_user, only: [ :show, :edit, :update, :destroy, :toggle_role ] |
| 4 | + |
| 5 | + def index |
| 6 | + @users = User.with_attached_avatar_image.order(:created_at) |
| 7 | + @users = @users.where(role: params[:role]) if params[:role].present? |
| 8 | + @users = @users.where("full_name ILIKE ? OR email ILIKE ?", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present? |
| 9 | + @users = @users.page(params[:page]).per(10) |
| 10 | + end |
| 11 | + |
| 12 | + def show |
| 13 | + end |
| 14 | + |
| 15 | + def new |
| 16 | + @user = User.new |
| 17 | + end |
| 18 | + |
| 19 | + def create |
| 20 | + @user = User.new(user_params) |
| 21 | + @user.password = SecureRandom.hex(8) if @user.password.blank? |
| 22 | + |
| 23 | + if @user.save |
| 24 | + UserMailer.welcome_email(@user, @user.password).deliver_later if Rails.env.production? |
| 25 | + redirect_to admin_user_path(@user), notice: "User was successfully created." |
| 26 | + else |
| 27 | + render :new, status: :unprocessable_entity |
| 28 | + end |
| 29 | + end |
| 30 | + |
| 31 | + def edit |
| 32 | + end |
| 33 | + |
| 34 | + def update |
| 35 | + user_update_params = user_params |
| 36 | + user_update_params.delete(:password) if user_update_params[:password].blank? |
| 37 | + |
| 38 | + if @user.update(user_update_params) |
| 39 | + redirect_to admin_user_path(@user), notice: "User was successfully updated." |
| 40 | + else |
| 41 | + render :edit, status: :unprocessable_entity |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + def destroy |
| 46 | + if @user == current_user |
| 47 | + redirect_to admin_users_path, alert: "You cannot delete your own account." |
| 48 | + return |
| 49 | + end |
| 50 | + |
| 51 | + @user.destroy |
| 52 | + redirect_to admin_users_path, notice: "User was successfully deleted." |
| 53 | + end |
| 54 | + |
| 55 | + def toggle_role |
| 56 | + new_role = @user.admin? ? "user" : "admin" |
| 57 | + |
| 58 | + if @user == current_user && new_role == "user" |
| 59 | + redirect_to admin_users_path, alert: "You cannot remove admin access from your own account." |
| 60 | + return |
| 61 | + end |
| 62 | + |
| 63 | + @user.update(role: new_role) |
| 64 | + redirect_to admin_users_path, notice: "User role updated to #{new_role.humanize}." |
| 65 | + end |
| 66 | + |
| 67 | + private |
| 68 | + |
| 69 | + def set_user |
| 70 | + @user = User.find(params[:id]) |
| 71 | + end |
| 72 | + |
| 73 | + def user_params |
| 74 | + params.require(:user).permit(:full_name, :email, :password, :password_confirmation, :role, :avatar_url, :avatar_image) |
| 75 | + end |
| 76 | +end |
0 commit comments