module Mks module Auth class UsersController < ApplicationController skip_before_action :authenticate, raise: false, only: %i[login] before_action :set_user, only: %i[update user_roles save_selected_roles] def index @users = ApplicationModule.find_by(code: app_code).users render json: @users end def roles user = User.find(params[:id]) render json: user.roles end # A method to fetch all roles, with roles of # a user marked as selected def user_roles all_roles = UserRole.joins(:application_module).where(mks_auth_application_modules: { code: app_code }) roles = all_roles.map { |r| { id: r.id, name: r.name, selected: @user.roles.include?(r) } } render json: roles end def save_selected_roles @user.roles.delete_all selected = save_selected_roles_params['roles'].select { |r| r['selected'] }.map{ |r| r['id'] } roles = UserRole.where(id: selected) @user.roles << roles render json: { success: true } end def create @user = User.new(user_params) app_module = ApplicationModule.find_by(code: app_code) @user.application_module_id = app_module.id if @user.save response = { success: true, message: 'User saved successfully' } else errors = Mks::Common::Util.error_messages @user, 'User' response = { success: false, errors: errors } end render json: response end def update if @user.update(user_params) response = { success: true, message: 'User updated successfully' } else errors = Mks::Common::Util.error_messages @user, 'User' response = { success: false, errors: errors } end render json: response end def login user = User.find_by(email: auth_params[:email]) if user.authenticate(auth_params[:password]) && user.has_module(auth_params[:app_module]) jwt = TokenAuth.issue(user.to_token_payload) render json: { jwt: jwt } else render json: {}, status: 400 end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:first_name, :last_name, :email, :password) end def auth_params params.require(:auth).permit(:email, :password, :app_module) end def save_selected_roles_params params.permit(roles: %i[id selected]) end end end end