def q_customization_delete(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) customization_id = request.POST.get("customization_id") try: customization = QModelCustomization.objects.get(id=customization_id) except QModelCustomization.DoesNotExist: msg = u"Unable to locate customization w/ id '%s'" % customization_id return HttpResponseBadRequest(msg) if customization.is_default: msg = u"You cannot delete the default customization." return HttpResponseBadRequest(msg) delete_customization_set(customization) try: customization.refresh_from_db() msg = "Error deleting customization" messages.add_message(request, messages.ERROR, msg) except QModelCustomization.DoesNotExist: msg = "You have successfully deleted this customization." messages.add_message(request, messages.INFO, msg) return JsonResponse({"msg": msg})
def q_proxy(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) url = request.POST.get("url") response_format = request.POST.get("response_format", "HTTP") if urlparse(url).netloc not in VALID_DOMAINS: return HttpResponseBadRequest("invalid proxy url '{0}'".format(url)) try: response = urllib2.urlopen(url) content = response.read() except urllib2.URLError as e: return HttpResponseBadRequest("unable to reach url '{0}': {1}".format(url, e)) if response_format.upper() == "HTTP": return HttpResponse(content) elif response_format.upper() == "JSON": json_content = json.loads(content) return JsonResponse(json_content) else: return HttpResponseBadRequest("unknown response_format: '{0}'".format(response_format))
def q_proxy(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) url = request.POST.get("url") response_format = request.POST.get("response_format", "HTTP") if urlparse(url).netloc not in VALID_DOMAINS: return HttpResponseBadRequest("invalid proxy url '{0}'".format(url)) try: response = urlopen(url) content = response.read() except URLError as e: return HttpResponseBadRequest("unable to reach url '{0}': {1}".format( url, e)) if response_format.upper() == "HTTP": return HttpResponse(content) elif response_format.upper() == "JSON": json_content = json.loads(content) return JsonResponse(json_content) else: return HttpResponseBadRequest( "unknown response_format: '{0}'".format(response_format))
def q_validate(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) old_value = request.POST.get('old_value') new_value = request.POST.get('new_value') validator_name = request.POST.get('validator') if not validator_name: msg = "missing validator name" return HttpResponseBadRequest(msg) try: validator = getattr(q_utils, validator_name) except AttributeError: msg = "invalid validator name" return HttpResponseBadRequest(msg) try: is_valid = validator(new_value) if is_valid is not False: return JsonResponse(True, safe=False) except ValidationError: pass return JsonResponse(False, safe=False)
def q_send_email_confirmation(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) username = request.POST.get("username") try: user = User.objects.get(username=username) except User.DoesNotExist: msg = "Unable to locate user '{0}'.".format(username) messages.add_message(request, messages.ERROR, msg) return HttpResponseBadRequest(msg) current_user = request.user if not current_user.is_superuser and current_user.username != username: msg = "You do not have authority to validate this user's email." messages.add_message(request, messages.ERROR, msg) return HttpResponseBadRequest(msg) try: send_email_confirmation(request, user) except Exception as e: msg = "Error sending confirmation email." messages.add_message(request, messages.ERROR, msg) return HttpResponseBadRequest(msg) return JsonResponse({})
def q_realization_remove_relationship_value(request): # check the request was valid... valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) target_index = request.POST.get("target_index") target_key = request.POST.get("target_key") property_key = request.POST.get("key") session_key = get_key_from_request(request) cached_realizations_key = "{0}_realizations".format(session_key) cached_realizations = get_cached_object(request.session, cached_realizations_key) if not cached_realizations: msg = "unable to locate cached_realizations" return HttpResponseBadRequest(msg) # do some sanity checks... # check the realization to remove from exists... property_realization = get_property_realization_by_key(property_key, cached_realizations) if not property_realization: msg = "unable to find a QPropertyRealization with a key of '{0}'".format(property_key) return HttpResponseBadRequest(msg) # check that the target to remove exists... target_realizations = property_realization.relationship_values(manager="allow_unsaved_relationship_values_manager").filter_potentially_unsaved(key=target_key) if len(target_realizations) != 1: msg = "unable to find a QModelProxy with a key of '{0}'".format(target_key) return HttpResponseBadRequest(msg) target_realization = target_realizations[0] # check that it makes sense to remove this target... if property_realization.relationship_values(manager="allow_unsaved_relationship_values_manager").count() <= property_realization.cardinality_min: msg = "you have cannot remove this many QModelRealizations from this this QPropertyRealization" return HttpResponseBadRequest(msg) # check the user has permission to modify the realization... current_user = request.user project = cached_realizations.project if project.authenticated: if not current_user.is_authenticated() or not is_member_of(current_user, project): msg = "{0} does not have permission to modify a realization".format(current_user) return HttpResponseForbidden(msg) # ...okay, sanity checks are over # now remove the target... property_realization.relationship_values(manager="allow_unsaved_relationship_values_manager").remove_potentially_unsaved(target_realization) if target_realization.is_existing: target_realization.delete() request.session[cached_realizations_key] = cached_realizations # finally return a success msg... msg = "Successfully removed object" return JsonResponse({"msg": msg})
def q_realization_add_relationship_value(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) target_proxy_id = request.POST.get("target_proxy_id") property_key = request.POST.get("key") session_key = get_key_from_request(request) cached_realizations_key = "{0}_realizations".format(session_key) cached_realizations = get_cached_object(request.session, cached_realizations_key) if not cached_realizations: msg = "unable to locate cached_realizations" raise QError(msg) property = get_property_realization_by_fn( lambda r: r.get_key() == property_key, cached_realizations ) if not property: raise QError("unable to find property w/ key='{0}'".format(property_key)) target_proxy = QModelProxy.objects.get(id=target_proxy_id) new_model_realization = get_new_realizations( project=cached_realizations.project, ontology=cached_realizations.ontology, model_proxy=target_proxy, key=target_proxy.name, ) # double-check that adding this model to this property makes sense... assert target_proxy in property.proxy.relationship_target_models.all() assert property.get_cardinality_max() == '*' or property.relationship_values(manager="allow_unsaved_relationship_values_manager").count() < int(property.get_cardinality_max()) # add the model... property.relationship_values(manager="allow_unsaved_relationship_values_manager").add_potentially_unsaved(new_model_realization) with allow_unsaved_fk(QModel, ["relationship_property"]): # in theory, Django doesn't store unsaved relationship # the custom manager above gets around this for the m2m relationship (property to model) and it is what I ought to use # however, in order to work my way up the realization hierarchy I need access to the reverse of that relationship # which is a fk relationship; hence this extra bit of code (which only exists so that "model_realizations.py#QRealization.get_parent_model_realization" works) new_model_realization.relationship_property = property # re-cache the changed realizations... request.session[cached_realizations_key] = cached_realizations # and return a serialized version of that model... new_model_realization_serialization = serialize_new_realizations(new_model_realization) return JsonResponse(new_model_realization_serialization)
def q_project_join_request(request, project_name=None): """ processes a join request :param request: :param project_name: :return: """ valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) try: project = QProject.objects.get(name=project_name) except QProject.DoesNotExist: msg = u"Unable to locate project '%s'" % project_name return HttpResponseBadRequest(msg) if not project.is_active: msg = u"This project has been disabled." return HttpResponseBadRequest(msg) user_id = request.POST.get("user_id") try: user = User.objects.get(pk=user_id) except User.DoesNotExist: msg = u"Unable to locate user" return HttpResponseBadRequest(msg) was_already_pending = False if is_pending_of(user, project): was_already_pending = True if project_join_request(project, user, site=request.current_site): msg = "Your request has been sent to the project administrator for review" if was_already_pending: msg += " again.<p><em>You have sent this request before. Please contact the project administrator [<a href='mailto:{email}'>{email}</a>] if things are moving too slowly</em>.</p>".format( email=project.email ) else: msg += "." messages.add_message(request, messages.INFO, msg) else: msg = "Error sending project join request." messages.add_message(request, messages.ERROR, msg) return JsonResponse({"msg": msg})
def q_realization_remove_relationship_value(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) target_index = int(request.POST.get("target_index")) property_key = request.POST.get("key") session_key = get_key_from_request(request) cached_realizations_key = "{0}_realizations".format(session_key) cached_realizations = get_cached_object(request.session, cached_realizations_key) if not cached_realizations: msg = "unable to locate cached_realizations" raise QError(msg) property = get_property_realization_by_fn( lambda r: r.get_key() == property_key, cached_realizations ) if not property: raise QError("unable to find property w/ key='{0}'".format(property_key)) # remove the model... try: target_to_remove = property.relationship_values(manager="allow_unsaved_relationship_values_manager").all()[target_index] property.relationship_values(manager="allow_unsaved_relationship_values_manager").remove_potentially_unsaved(target_to_remove) if target_to_remove.is_existing(): target_to_remove.delete() except IndexError: raise QError("unable to find target of {0} at index {1}".format(property, target_index)) # re-cache the changed realizations... request.session[cached_realizations_key] = cached_realizations # and return a success msg... msg = "Successfully removed object" # (don't need to explicitly render this msg using Django messaging framework) # (b/c it will be obvious to the user that a model was removed since a subform will dissappear) # (and, anyway, there is no corresponding msg that is used when a model is added to a property) # messages.add_message(request, messages.SUCCESS, msg) return JsonResponse({"msg": msg})
def q_project_add_member(request, project_name=None): """ approve a project join request :param request: :param project_name: :return: """ valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) try: project = QProject.objects.get(name=project_name) except QProject.DoesNotExist: msg = u"Unable to locate project '%s'" % project_name return HttpResponseBadRequest(msg) if not project.is_active: msg = u"This project has been disabled." return HttpResponseBadRequest(msg) user_id = request.POST.get("user_id") try: user = User.objects.get(pk=user_id) except User.DoesNotExist: msg = u"Unable to locate user" return HttpResponseBadRequest(msg) if not is_admin_of(request.user, project): msg = u"This user has not requested to join this project" return HttpResponseBadRequest(msg) if not is_pending_of(user, project): msg = u"This user has not requested to join this project" return HttpResponseBadRequest(msg) if project_join(project, user, site=request.current_site): serialized_user = QProjectUserSerializer(user).data return JsonResponse(serialized_user) else: msg = "Error adding user to project." messages.add_message(request, messages.ERROR, msg) return JsonResponse({"msg": msg})
def q_customization_delete(request): # check the request was valid... valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) # check the requested customization exists... customization_id = request.POST.get("customization_id") try: customization = QModelCustomization.objects.get(id=customization_id) project = customization.project except QModelCustomization.DoesNotExist: msg = u"Unable to locate customization w/ id '%s'" % customization_id return HttpResponseBadRequest(msg) # check the user has permission to delete the customization... current_user = request.user if project.authenticated: if not current_user.is_authenticated() or not is_admin_of(current_user, project): msg = "{0} does not have permission to delete {1}".format(current_user, customization) return HttpResponseForbidden(msg) # check the customization can be deleted... if customization.is_default: msg = u"You cannot delete the default customization." return HttpResponseBadRequest(msg) # delete it! customization.delete() # make sure the customization no loner exists... try: customization.refresh_from_db() msg = "Error deleting customization" messages.add_message(request, messages.ERROR, msg) except QModelCustomization.DoesNotExist: msg = "You have successfully deleted this customization." messages.add_message(request, messages.INFO, msg) return JsonResponse({"msg": msg})
def q_load_section(request, section_type=None): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) try: section_info = SECTION_MAP[section_type] except KeyError: msg = "I don't know how to render a section w/ type '{0}'".format(section_type) return HttpResponseBadRequest(msg) model_index = request.POST.get("index") model_key = request.POST.get("key") model_scope = request.POST.get("scope") session_key = get_key_from_request(request) cached_models_key = section_info["cached_models_key"].format(session_key=session_key) cached_models = get_cached_object(request.session, cached_models_key) if not cached_models: msg = "unable to locate cached_models" raise QError(msg) get_model_fn = section_info["get_model_fn"] model = get_model_fn(model_key, cached_models) if not model: raise QError("unable to find instance w/ key='{0}'".format(model_key)) template_context = {} for context_key, context_value in section_info.get("template_context").iteritems(): form_class = context_value["class"] template_context[context_key] = form_class( instance=model, name=context_value["name"].format(safe_key=model_key.replace('-', '_')), scope_prefix=context_value["scope_prefix"].format(index=model_index) ) template = "{0}/sections/{1}".format(APP_LABEL, section_info["template"]) return render_to_response(template, template_context, context_instance=RequestContext(request))
def q_document_publish(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) model_id = request.POST.get("document_id") try: # model = QModel.objects.get(id=model_id) model = MetadataModel.objects.get(id=model_id) # except QModel.DoesNotExist: except MetadataModel.DoesNotExist: msg = u"Unable to locate model w/ id '%s'" % model_id return HttpResponseBadRequest(msg) # if not model.is_active: if not model.active: msg = u"This model has been disabled." return HttpResponseBadRequest(msg) if not model.is_document and model.is_root: msg = u"This model is not a root document." return HttpResponseBadRequest(msg) if not model.is_complete(): msg = u"This model is incomplete." return HttpResponseBadRequest(msg) publication = model.publish(force_save=True) if publication: msg = "You have successfully published this document." messages.add_message(request, messages.INFO, msg) else: msg = "Error publishing document." messages.add_message(request, messages.ERROR, msg) return JsonResponse({"msg": msg})
def q_realization_add_relationship_value(request): # check the request was valid... valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) target_proxy_id = request.POST.get("target_proxy_id") property_key = request.POST.get("key") session_key = get_key_from_request(request) cached_realizations_key = "{0}_realizations".format(session_key) cached_realizations = get_cached_object(request.session, cached_realizations_key) if not cached_realizations: msg = "unable to locate cached_realizations" return HttpResponseBadRequest(msg) # do some sanity checks... # check the realization to add to exists... property_realization = get_property_realization_by_key(property_key, cached_realizations) if not property_realization: msg = "unable to find a QPropertyRealization with a key of '{0}'".format(property_key) return HttpResponseBadRequest(msg) # check that the target to add exists... try: target_proxy = QModelProxy.objects.get(id=target_proxy_id) except QModelProxy.DoesNotExist: msg = "unable to find a QModelProxy with an id of '{0}'".format(target_proxy_id) return HttpResponseBadRequest(msg) # check that it makes sense to add this target... if target_proxy not in property_realization.proxy.relationship_target_models.all(): msg = "you are trying to add the wrong type of QModelRealization to this QPropertyRealization" return HttpResponseBadRequest(msg) if (not property_realization.is_infinite) and (property_realization.relationship_values(manager="allow_unsaved_relationship_values_manager").count() >= property_realization.cardinality_max): msg = "you have already added the maximum amount of QModelRealizations to this QPropertyRealization" return HttpResponseBadRequest(msg) # check the user has permission to modify the realization... current_user = request.user project = cached_realizations.project if project.authenticated: if not current_user.is_authenticated() or not is_member_of(current_user, project): msg = "{0} does not have permission to modify a realization".format(current_user) return HttpResponseForbidden(msg) # ...okay, sanity checks are over # now create the model... new_model_realization = get_new_realizations( project=project, ontology=target_proxy.ontology, model_proxy=target_proxy, key=target_proxy.name, ) # now add the model... property_realization.relationship_values(manager="allow_unsaved_relationship_values_manager").add_potentially_unsaved(new_model_realization) with allow_unsaved_fk(QModelRealization, ["relationship_property"]): # the custom manager above ("allow_unsaved_relationship_values_manager") lets me cope w/ an unsaved m2m relationship - it is what I ought to use # however, some fns ("QRealization.get_root_realization") needs access to the reverse of that relationship; hence this extra bit of code new_model_realization.relationship_property = property_realization request.session[cached_realizations_key] = cached_realizations # finally return a serialized version of that model... new_model_realization_serialization = serialize_realizations(new_model_realization) return JsonResponse(new_model_realization_serialization)