Exemple #1
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'])
Exemple #2
0
def create_account(email,
                   username=None,
                   first_name=None,
                   last_name=None,
                   superuser=None,
                   groups=None,
                   password=None,
                   active=True,
                   organization=None):
    """
    Create a new user within the CommonsShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    username = username if username else email

    groups = groups if groups else []
    groups = Group.objects.in_bulk(
        *groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(username,
                                          email,
                                          first_name=first_name,
                                          last_name=last_name,
                                          password=password)
    else:
        u = User.objects.create_user(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the CommonsShare role group
    u.groups.add(Group.objects.get(name='CommonsShare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    user_profile = get_profile(u)

    if organization:
        user_profile.organization = organization
        user_profile.save()

        dict_items = 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()

    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
Exemple #3
0
def create_account(
        email, username=None, first_name=None, last_name=None, superuser=None, groups=None,
        password=None, active=True, organization=None, middle_name=None):
    """
    Create a new user within the HydroShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    try:
        user = User.objects.get(Q(username__iexact=username))
        raise ValidationError("User with provided username already exists.")
    except User.DoesNotExist:
        pass
    try:
        # we chose to follow current email practices with case insensitive emails
        user = User.objects.get(Q(email__iexact=email))
        raise ValidationError("User with provided email already exists.")
    except User.DoesNotExist:
        pass
    groups = groups if groups else []
    groups = Group.objects.in_bulk(*groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password
        )
    else:
        u = User.objects.create_user(
            username, email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the Hydroshare role group
    u.groups.add(Group.objects.get(name='Hydroshare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    user_profile = get_profile(u)

    if organization:
        user_profile.organization = organization
        user_profile.save()

        dict_items = 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()

    if middle_name:
        user_profile.middle_name = middle_name
        user_profile.save()

    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
Exemple #4
0
def create_account(email,
                   username=None,
                   first_name=None,
                   last_name=None,
                   superuser=None,
                   groups=None,
                   password=None,
                   active=True,
                   organization=None,
                   middle_name=None):
    """
    Create a new user within the HydroShare system.

    Returns: The user that was created

    """

    from django.contrib.auth.models import User, Group
    from hs_access_control.models import UserAccess
    from hs_labels.models import UserLabels

    try:
        user = User.objects.get(Q(username__iexact=username))
        raise ValidationError("User with provided username already exists.")
    except User.DoesNotExist:
        pass
    try:
        # we chose to follow current email practices with case insensitive emails
        user = User.objects.get(Q(email__iexact=email))
        raise ValidationError("User with provided email already exists.")
    except User.DoesNotExist:
        pass
    groups = groups if groups else []
    groups = Group.objects.in_bulk(
        *groups) if groups and isinstance(groups[0], int) else groups

    if superuser:
        u = User.objects.create_superuser(username,
                                          email,
                                          first_name=first_name,
                                          last_name=last_name,
                                          password=password)
    else:
        u = User.objects.create_user(
            username,
            email,
            first_name=first_name,
            last_name=last_name,
            password=password,
        )

    u.is_staff = False
    if not active:
        u.is_active = False
    u.save()

    u.groups = groups

    # make the user a member of the Hydroshare role group
    u.groups.add(Group.objects.get(name='Hydroshare Author'))

    user_access = UserAccess(user=u)
    user_access.save()
    user_labels = UserLabels(user=u)
    user_labels.save()
    user_profile = get_profile(u)

    if organization:
        user_profile.organization = organization
        user_profile.save()

        dict_items = 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()

    if middle_name:
        user_profile.middle_name = middle_name
        user_profile.save()

    # create default UserQuota object for the new user
    uq = UserQuota.objects.create(user=u)
    uq.save()
    return u
Exemple #5
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'])