module UserPermissionsControllerMethods
  private
    def applications_and_permissions(user)
      ::Doorkeeper::Application.order(:name).all.map do |application|
        permission_for_application = user.permissions.find_by_application_id(application.id)
        permission_for_application ||= Permission.new(application: application, user: user)
        [application, permission_for_application]
      end
    end

    def translate_faux_signin_permission(raw_user_params)
      user_params = raw_user_params.dup
      if user_params[:permissions_attributes]
        user_params[:permissions_attributes].each do |index, attributes|
          attributes[:permissions] ||= []
          if attributes[:signin_permission] == "1"
            attributes[:permissions] << "signin"
          else
            has_signin = false
          end
          attributes.delete(:signin_permission)
        end
      end
      user_params
    end
end

module UserPermissionsControllerMethods
  private
    def applications_and_permissions(user)
      ::Doorkeeper::Application.order(:name).all.map do |application|
        permission_for_application = user.permissions.find_or_create_by_application_id(application.id)
        [application, permission_for_application]
      end
    end

    def translate_faux_signin_permission(raw_user_params)
      user_params = raw_user_params.dup
      if user_params[:permissions_attributes]
        user_params[:permissions_attributes].each do |index, attributes|
          attributes[:permissions] ||= []
          if attributes[:signin_permission] == "1"
            attributes[:permissions] << "signin"
          else
            has_signin = false
          end
          attributes.delete(:signin_permission)
        end
      end
      user_params
    end
end

Fix intermittent failure when editing permissions
Fix intermittent failure when editing permissions

From close inspection of the parameters from when the errors occurred,
an ID was not being supplied by the browser for the permission which
the server was trying to create.

I believe that the following happened (and I successfully reproduced):
 * The user was created/edited once, and they did not have a pre-existing permission
   for one or more application. The server therefore created it on submit.
 * The admin user clicked back (i.e. not being rendered a fresh page containing the
   new permission ID)
 * They submitted again, and the server tried to create another permission, but failed
   because it already existed.

The fix, therefore, is to always create the permission before it is
rendered to the browser, hence it always has an ID.
