예제 #1
0
def metadata_element_pre_create_handler(sender, **kwargs):
    """Select proper form class based on element_name.

    This handler is executed only when a metadata element is added as part of editing a resource
    """
    element_name = kwargs['element_name']
    request = kwargs['request']
    if element_name == "subject":   # keywords
        element_form = SubjectsForm(data=request.POST)
    elif element_name == "description":   # abstract
        element_form = AbstractValidationForm(request.POST)
    elif element_name == "creator":
        try:
            post_data_dict = Party.get_post_data_with_identifiers(request=request)
        except Exception as ex:
            return {'is_valid': False, 'element_data_dict': None,
                    "errors": {"identifiers": [str(ex)]}}

        element_form = CreatorValidationForm(post_data_dict)

    elif element_name == "contributor":
        try:
            post_data_dict = Party.get_post_data_with_identifiers(request=request)
        except Exception as ex:
            return {'is_valid': False, 'element_data_dict': None,
                    "errors": {"identifiers": [str(ex)]}}
        element_form = ContributorValidationForm(post_data_dict)

    elif element_name == "citation":
        return {'is_valid': True, 'element_data_dict': {'value': request.POST.get('content').strip()}}

    elif element_name == 'relation':
        element_form = RelationValidationForm(request.POST)
    elif element_name == 'source':
        element_form = SourceValidationForm(request.POST)
    elif element_name == 'rights':
        element_form = RightsValidationForm(request.POST)
    elif element_name == 'language':
        element_form = LanguageValidationForm(request.POST)
    elif element_name == 'date':
        element_form = ValidDateValidationForm(request.POST)
    elif element_name == 'fundingagency':
        element_form = FundingAgencyValidationForm(request.POST)
    elif element_name == 'coverage':
        if 'type' in request.POST:
            if request.POST['type'].lower() == 'point' or request.POST['type'].lower() == 'box':
                element_form = CoverageSpatialForm(data=request.POST)
            else:
                element_form = CoverageTemporalForm(data=request.POST)
        else:
            element_form = CoverageTemporalForm(data=request.POST)
    elif element_name == 'identifier':
        element_form = IdentifierForm(data=request.POST)
    else:
        raise Exception("Invalid metadata element name:{}".format(element_name))

    if element_form.is_valid():
        return {'is_valid': True, 'element_data_dict': element_form.cleaned_data}
    else:
        return {'is_valid': False, 'element_data_dict': None, "errors": element_form.errors}
예제 #2
0
def metadata_element_pre_create_handler(sender, **kwargs):
    """Select proper form class based on element_name.

    This handler is executed only when a metadata element is added as part of editing a resource
    """
    element_name = kwargs['element_name']
    request = kwargs['request']
    if element_name == "subject":   # keywords
        element_form = SubjectsForm(data=request.POST)
    elif element_name == "description":   # abstract
        element_form = AbstractValidationForm(request.POST)
    elif element_name == "creator":
        try:
            post_data_dict = Party.get_post_data_with_identifiers(request=request)
        except Exception as ex:
            return {'is_valid': False, 'element_data_dict': None,
                    "errors": {"identifiers": [ex.message]}}

        element_form = CreatorValidationForm(post_data_dict)

    elif element_name == "contributor":
        try:
            post_data_dict = Party.get_post_data_with_identifiers(request=request)
        except Exception as ex:
            return {'is_valid': False, 'element_data_dict': None,
                    "errors": {"identifiers": [ex.message]}}
        element_form = ContributorValidationForm(post_data_dict)
    elif element_name == 'relation':
        element_form = RelationValidationForm(request.POST)
    elif element_name == 'source':
        element_form = SourceValidationForm(request.POST)
    elif element_name == 'rights':
        element_form = RightsValidationForm(request.POST)
    elif element_name == 'language':
        element_form = LanguageValidationForm(request.POST)
    elif element_name == 'date':
        element_form = ValidDateValidationForm(request.POST)
    elif element_name == 'fundingagency':
        element_form = FundingAgencyValidationForm(request.POST)
    elif element_name == 'coverage':
        if 'type' in request.POST:
            if request.POST['type'].lower() == 'point' or request.POST['type'].lower() == 'box':
                element_form = CoverageSpatialForm(data=request.POST)
            else:
                element_form = CoverageTemporalForm(data=request.POST)
        else:
            element_form = CoverageTemporalForm(data=request.POST)
    elif element_name == 'identifier':
        element_form = IdentifierForm(data=request.POST)
    else:
        raise Exception("Invalid metadata element name:{}".format(element_name))

    if element_form.is_valid():
        return {'is_valid': True, 'element_data_dict': element_form.cleaned_data}
    else:
        return {'is_valid': False, 'element_data_dict': None, "errors": element_form.errors}
예제 #3
0
def update_user_profile(request):
    user = request.user
    old_email = user.email
    user_form = UserForm(request.POST, instance=user)
    user_profile = UserProfile.objects.filter(user=user).first()

    # create a dict of identifier names and links for the identifiers field of the  UserProfile
    try:
        post_data_dict = Party.get_post_data_with_identifiers(request=request,
                                                              as_json=False)
        identifiers = post_data_dict.get('identifiers', {})
    except Exception as ex:
        messages.error(request, "Update failed. {}".format(ex.message))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])

    dict_items = request.POST['organization'].split(";")
    for dict_item in dict_items:
        # Update Dictionaries
        try:
            University.objects.get(name=dict_item)
        except ObjectDoesNotExist:
            new_term = UncategorizedTerm(name=dict_item)
            new_term.save()
        except MultipleObjectsReturned:
            pass

    profile_form = UserProfileForm(post_data_dict,
                                   request.FILES,
                                   instance=user_profile)
    try:
        with transaction.atomic():
            if user_form.is_valid() and profile_form.is_valid():
                user_form.save()
                profile = profile_form.save(commit=False)
                profile.user = request.user
                profile.identifiers = identifiers
                profile.save()
                messages.success(
                    request, "Your profile has been successfully updated.")
                # if email was updated, reset to old email and send confirmation
                # email to the user's new email - email will be updated upon confirmation
                if old_email != user.email:
                    new_email = user.email
                    user.email = old_email
                    user.save()
                    # send a confirmation email to the new email address
                    send_verification_mail_for_email_update(
                        request, user, new_email, "email_verify")
                    info(
                        request,
                        _("A verification email has been sent to your new email with "
                          "a link for updating your email. If you "
                          "do not receive this email please check your "
                          "spam folder as sometimes the confirmation email "
                          "gets flagged as spam. If you entered an incorrect "
                          "email address, please request email update again. ")
                    )
                    # send an email to the old address notifying the email change
                    message = """Dear {}
                    <p>HydroShare received a request to change the email address associated with
                    HydroShare account {} from {} to {}. You are receiving this email to the old
                    email address as a precaution. If this is correct you may ignore this email
                    and click on the link in the email sent to the new address to confirm this change.</p>
                    <p>If you did not originate this request, there is a danger someone else has
                    accessed your account. You should log into HydroShare, change your password,
                    and set the email address to the correct address. If you are unable to do this
                    contact [email protected]
                    <p>Thank you</p>
                    <p>The HydroShare Team</p>
                    """.format(user.first_name, user.username, user.email,
                               new_email)
                    send_mail(subject="Change of HydroShare email address.",
                              message=message,
                              html_message=message,
                              from_email=settings.DEFAULT_FROM_EMAIL,
                              recipient_list=[old_email],
                              fail_silently=True)
            else:
                errors = {}
                if not user_form.is_valid():
                    errors.update(user_form.errors)

                if not profile_form.is_valid():
                    errors.update(profile_form.errors)

                msg = ' '.join([err[0] for err in errors.values()])
                messages.error(request, msg)

    except Exception as ex:
        messages.error(request, ex.message)

    return HttpResponseRedirect(request.META['HTTP_REFERER'])
예제 #4
0
def metadata_element_pre_update_handler(sender, **kwargs):
    """Select proper form class based on element_name.

    This handler is executed only when a metadata element is added as part of editing a resource
    """
    element_name = kwargs['element_name'].lower()
    request = kwargs['request']
    repeatable_elements = {'creator': CreatorValidationForm,
                           'contributor': ContributorValidationForm,
                           'relation': RelationValidationForm,
                           'source': SourceValidationForm
                           }

    if element_name == 'title':
        element_form = TitleValidationForm(request.POST)
    elif element_name == "description":   # abstract
        element_form = AbstractValidationForm(request.POST)
    elif element_name == "fundingagency":
        element_form = FundingAgencyValidationForm(request.POST)
    elif element_name in repeatable_elements:
        # since element_name is a repeatable element (e.g creator) and data for the element
        # is displayed on the landing page using formset, the data coming from a single element
        # form in the request for update needs to be parsed to match with element field names
        element_validation_form = repeatable_elements[element_name]
        form_data = {}
        for field_name in element_validation_form().fields:
            if element_name.lower() == "creator" or element_name.lower() == "contributor":
                try:
                    post_data_dict = Party.get_post_data_with_identifiers(request=request)
                except Exception as ex:
                    return {'is_valid': False, 'element_data_dict': None,
                            "errors": {"identifiers": [ex.message]}}

                # for creator or contributor who is not a hydroshare user the 'description'
                # key might be missing in the POST form data
                if field_name == 'description':
                    matching_key = [key for key in request.POST if '-'+field_name in key]
                    if matching_key:
                        matching_key = matching_key[0]
                    else:
                        continue
                elif field_name == 'identifiers':
                    matching_key = 'identifiers'
                else:
                    matching_key = [key for key in request.POST if '-'+field_name in key][0]

                form_data[field_name] = post_data_dict[matching_key]
            else:
                matching_key = [key for key in request.POST if '-'+field_name in key][0]
                form_data[field_name] = request.POST[matching_key]

        element_form = element_validation_form(form_data)
    elif element_name == 'rights':
        element_form = RightsValidationForm(request.POST)
    elif element_name == 'language':
        element_form = LanguageValidationForm(request.POST)
    elif element_name == 'date':
        element_form = ValidDateValidationForm(request.POST)
    elif element_name == 'coverage':
        if 'type' in request.POST:
            element_form = CoverageSpatialForm(data=request.POST)
        else:
            element_form = CoverageTemporalForm(data=request.POST)
    elif element_name == 'identifier':
        element_form = IdentifierForm(data=request.POST)
    else:
        raise Exception("Invalid metadata element name:{}".format(element_name))

    if element_form.is_valid():
        return {'is_valid': True, 'element_data_dict': element_form.cleaned_data}
    else:
        # TODO: need to return form errors
        return {'is_valid': False, 'element_data_dict': None}
예제 #5
0
 def clean_identifiers(self):
     data = self.cleaned_data['identifiers']
     return Party.validate_identifiers(data)
예제 #6
0
 def clean_identifiers(self):
     data = self.cleaned_data['identifiers']
     return Party.validate_identifiers(data)
예제 #7
0
def metadata_element_pre_update_handler(sender, **kwargs):
    """Select proper form class based on element_name.

    This handler is executed only when a metadata element is added as part of editing a resource
    """
    element_name = kwargs['element_name'].lower()
    request = kwargs['request']
    repeatable_elements = {'creator': CreatorValidationForm,
                           'contributor': ContributorValidationForm,
                           'relation': RelationValidationForm,
                           'source': SourceValidationForm
                           }

    if element_name == 'title':
        element_form = TitleValidationForm(request.POST)
    elif element_name == "description":   # abstract
        element_form = AbstractValidationForm(request.POST)
    elif element_name == "fundingagency":
        element_form = FundingAgencyValidationForm(request.POST)
    elif element_name in repeatable_elements:
        # since element_name is a repeatable element (e.g creator) and data for the element
        # is displayed on the landing page using formset, the data coming from a single element
        # form in the request for update needs to be parsed to match with element field names
        element_validation_form = repeatable_elements[element_name]
        form_data = {}
        for field_name in element_validation_form().fields:
            if element_name.lower() == "creator" or element_name.lower() == "contributor":
                try:
                    post_data_dict = Party.get_post_data_with_identifiers(request=request)
                except Exception as ex:
                    return {'is_valid': False, 'element_data_dict': None,
                            "errors": {"identifiers": [ex.message]}}

                # for creator or contributor who is not a hydroshare user the 'description'
                # key might be missing in the POST form data
                if field_name == 'description':
                    matching_key = [key for key in request.POST if '-'+field_name in key]
                    if matching_key:
                        matching_key = matching_key[0]
                    else:
                        continue
                elif field_name == 'identifiers':
                    matching_key = 'identifiers'
                else:
                    matching_key = [key for key in request.POST if '-'+field_name in key][0]

                form_data[field_name] = post_data_dict[matching_key]
            else:
                matching_key = [key for key in request.POST if '-'+field_name in key][0]
                form_data[field_name] = request.POST[matching_key]

        element_form = element_validation_form(form_data)
    elif element_name == 'rights':
        element_form = RightsValidationForm(request.POST)
    elif element_name == 'language':
        element_form = LanguageValidationForm(request.POST)
    elif element_name == 'date':
        element_form = ValidDateValidationForm(request.POST)
    elif element_name == 'coverage':
        if 'type' in request.POST:
            element_form = CoverageSpatialForm(data=request.POST)
        else:
            element_form = CoverageTemporalForm(data=request.POST)
    elif element_name == 'identifier':
        element_form = IdentifierForm(data=request.POST)
    else:
        raise Exception("Invalid metadata element name:{}".format(element_name))

    if element_form.is_valid():
        return {'is_valid': True, 'element_data_dict': element_form.cleaned_data}
    else:
        return {'is_valid': False, 'element_data_dict': None, "errors": element_form.errors}
예제 #8
0
def update_user_profile(request):
    user = request.user
    old_email = user.email
    user_form = UserForm(request.POST, instance=user)
    user_profile = UserProfile.objects.filter(user=user).first()

    # create a dict of identifier names and links for the identifiers field of the  UserProfile
    try:
        post_data_dict = Party.get_post_data_with_identifiers(request=request, as_json=False)
        identifiers = post_data_dict.get('identifiers', {})
    except Exception as ex:
        messages.error(request, "Update failed. {}".format(ex.message))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])

    dict_items = request.POST['organization'].split(";")
    for dict_item in dict_items:
        # Update Dictionaries
        try:
            University.objects.get(name=dict_item)
        except ObjectDoesNotExist:
            new_term = UncategorizedTerm(name=dict_item)
            new_term.save()
        except MultipleObjectsReturned:
            pass

    profile_form = UserProfileForm(post_data_dict, request.FILES, instance=user_profile)
    try:
        with transaction.atomic():
            if user_form.is_valid() and profile_form.is_valid():
                user_form.save()
                profile = profile_form.save(commit=False)
                profile.user = request.user
                profile.identifiers = identifiers
                profile.save()
                messages.success(request, "Your profile has been successfully updated.")
                # if email was updated, reset to old email and send confirmation
                # email to the user's new email - email will be updated upon confirmation
                if old_email != user.email:
                    new_email = user.email
                    user.email = old_email
                    user.save()
                    # send a confirmation email to the new email address
                    send_verification_mail_for_email_update(request, user, new_email, "email_verify")
                    info(request, _("A verification email has been sent to your new email with "
                                    "a link for updating your email. If you "
                                    "do not receive this email please check your "
                                    "spam folder as sometimes the confirmation email "
                                    "gets flagged as spam. If you entered an incorrect "
                                    "email address, please request email update again. "
                                    ))
                    # send an email to the old address notifying the email change
                    message = """Dear {}
                    <p>HydroShare received a request to change the email address associated with
                    HydroShare account {} from {} to {}. You are receiving this email to the old
                    email address as a precaution. If this is correct you may ignore this email
                    and click on the link in the email sent to the new address to confirm this change.</p>
                    <p>If you did not originate this request, there is a danger someone else has
                    accessed your account. You should log into HydroShare, change your password,
                    and set the email address to the correct address. If you are unable to do this
                    contact [email protected]
                    <p>Thank you</p>
                    <p>The HydroShare Team</p>
                    """.format(user.first_name, user.username, user.email, new_email)
                    send_mail(subject="Change of HydroShare email address.",
                              message=message,
                              html_message=message,
                              from_email= settings.DEFAULT_FROM_EMAIL, recipient_list=[old_email],
                              fail_silently=True)
            else:
                errors = {}
                if not user_form.is_valid():
                    errors.update(user_form.errors)

                if not profile_form.is_valid():
                    errors.update(profile_form.errors)

                msg = ' '.join([err[0] for err in errors.values()])
                messages.error(request, msg)

    except Exception as ex:
        messages.error(request, ex.message)

    return HttpResponseRedirect(request.META['HTTP_REFERER'])