users_controller.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. class UsersController < ApplicationController
  2. before_action :set_user, only: [:show, :edit, :update, :destroy]
  3. before_action :check_permission, only: [:edit, :update]
  4. def index
  5. respond_to do |format|
  6. @users = current_user.school ? current_user.school.users : User.all
  7. format.json
  8. format.html
  9. end
  10. end
  11. def show
  12. end
  13. def new
  14. end
  15. def edit
  16. end
  17. def update
  18. if @user.update(user_params)
  19. flash[:success] = 'Profile updated'
  20. redirect_to @user
  21. else
  22. render :edit
  23. end
  24. end
  25. private
  26. # Use callbacks to share common setup or constraints between actions.
  27. def set_user
  28. @user = User.find(params[:id])
  29. end
  30. # Only allow certain attributes to be updated over the web.
  31. def user_params
  32. allowed = [:login, :email, :password, :password_confirmation,
  33. :phone, :picture]
  34. if can_administer?
  35. allowed += [:gender, :birth_date, :name]
  36. end
  37. if current_user.admin?
  38. allowed += [:admin]
  39. end
  40. params.require(:user).permit(*allowed)
  41. end
  42. # Confirms the correct user.
  43. def check_permission
  44. redirect_to(root_url) unless can_edit?
  45. end
  46. def can_edit?
  47. current_user?(@user) || can_administer?
  48. end
  49. def can_administer?
  50. current_user.is_administrator_at?(@user.school) || current_user.admin?
  51. end
  52. end