Ejemplo n.º 1
0
def _notify_visualisation_access_request(request, dataset, dataset_url,
                                         contact_email, goal):

    message = f"""
An access request has been sent to the data visualisation owner and secondary contact to process.

There is no need to action this ticket until a further notification is received.

Data visualisation: {dataset.name} ({dataset_url})

Requestor {request.user.email}
People finder link: {get_people_url(request.user.get_full_name())}

Requestor’s response to why access is needed:
{goal}

Data visualisation owner: {dataset.enquiries_contact.email}

Secondary contact: {dataset.secondary_enquiries_contact.email}

If access has not been granted to the requestor within 5 working days, this will trigger an update to this Zendesk ticket to resolve the request.
    """

    ticket_reference = create_support_request(
        request.user,
        request.user.email,
        message,
        subject=f"Data visualisation access request received - {dataset.name}",
        tag='visualisation-access-request',
    )

    give_access_url = request.build_absolute_uri(
        reverse(
            "visualisations:users-give-access",
            args=[dataset.visualisation_template.gitlab_project_id],
        ))
    give_access_token = generate_token({
        'email': request.user.email,
        'ticket': ticket_reference
    }).decode('utf-8')

    for contact in set([
            dataset.enquiries_contact.email,
            dataset.secondary_enquiries_contact.email
    ]):
        send_email(
            settings.NOTIFY_VISUALISATION_ACCESS_REQUEST_TEMPLATE_ID,
            contact,
            personalisation={
                "visualisation_name": dataset.name,
                "visualisation_url": dataset_url,
                "user_email": contact_email,
                "goal": goal,
                "people_url": get_people_url(request.user.get_full_name()),
                "give_access_url":
                f"{give_access_url}?token={give_access_token}",
            },
        )

    return ticket_reference
Ejemplo n.º 2
0
 def form_valid(self, form):
     form_data = form.cleaned_data
     contacts = {form_data["to_user"].email}
     if form_data["copy_sender"]:
         contacts.add(self.request.user.email)
     for contact in contacts:
         send_email(
             settings.NOTIFY_SHARE_EXPLORER_QUERY_TEMPLATE_ID,
             contact,
             personalisation={
                 "sharer_first_name": self.request.user.first_name,
                 "message": form_data["message"],
             },
         )
     return HttpResponseRedirect(
         reverse(
             "explorer:share_query_confirmation",
             args=(form_data["to_user"].id,),
         )
         + f"?{urlencode(self.request.GET)}"
     )
Ejemplo n.º 3
0
    def send_notifications():
        user_notification_ids = list(
            UserNotification.objects.filter(email_id=None).values_list(
                "id", flat=True))

        for user_notification_id in user_notification_ids:
            try:
                with transaction.atomic():
                    user_notification = UserNotification.objects.select_for_update(
                    ).get(id=user_notification_id)
                    user_notification.refresh_from_db()
                    if user_notification.email_id is not None:
                        # This means another task has updated the email_id field since
                        # the filter above was executed
                        continue

                    change = get_change_item(
                        user_notification.notification.related_object,
                        user_notification.notification.changelog_id,
                    )

                    if not change:
                        logger.error("get_change_item returned None")

                    change_date = change["change_date"]

                    if (change["previous_table_structure"] !=
                            change["table_structure"]) or (
                                change["previous_table_name"] !=
                                change["table_name"]):
                        template_id = settings.NOTIFY_DATASET_NOTIFICATIONS_COLUMNS_TEMPLATE_ID
                    elif change["previous_data_hash"] != change["data_hash"]:
                        template_id = settings.NOTIFY_DATASET_NOTIFICATIONS_ALL_DATA_TEMPLATE_ID

                    email_address = user_notification.subscription.user.email
                    dataset_name = user_notification.subscription.dataset.name
                    dataset_url = (os.environ["APPLICATION_ROOT_DOMAIN"] +
                                   user_notification.subscription.dataset.
                                   get_absolute_url())
                    manage_subscriptions_url = os.environ[
                        "APPLICATION_ROOT_DOMAIN"] + reverse(
                            "datasets:email_preferences")
                    logger.info(
                        "Sending notification about dataset %s changing structure at %s to user %s",
                        dataset_name,
                        change_date,
                        email_address,
                    )
                    try:
                        email_id = send_email(
                            template_id,
                            email_address,
                            personalisation={
                                "change_date":
                                change_date.strftime("%d/%m/%Y - %H:%M:%S"),
                                "dataset_name":
                                dataset_name,
                                "dataset_url":
                                dataset_url,
                                "manage_subscriptions_url":
                                manage_subscriptions_url,
                                "summary":
                                change["summary"],
                            },
                        )
                    except EmailSendFailureException:
                        logger.exception("Failed to send email")
                    else:
                        user_notification.email_id = email_id
                        user_notification.save(update_fields=["email_id"])
            except IntegrityError as e:
                logger.error("Exception when sending notifications: %s", e)
Ejemplo n.º 4
0
def visualisation_users_give_access_html_POST(request, gitlab_project, token_data):
    branches = _visualisation_branches(gitlab_project)
    application_template = _application_template(gitlab_project)

    email_address = request.POST['email-address'].strip().lower()

    def error(email_address_error):
        return _render_visualisation(
            request,
            'visualisation_users_give_access.html',
            gitlab_project,
            application_template,
            branches,
            current_menu_item='users-give-access',
            template_specific_context={
                'email_address': email_address,
                'email_address_error': email_address_error,
                'application_template': application_template,
            },
        )

    if not email_address:
        return error('Enter the user\'s email address')

    try:
        EmailValidator()(email_address)
    except ValidationError:
        return error(
            'Enter the user\'s email address in the correct format, like [email protected]'
        )

    User = get_user_model()

    try:
        user = User.objects.get(email=email_address)
    except User.DoesNotExist:
        return error('The user must have previously visisted Data Workspace')

    content_type_id = ContentType.objects.get_for_model(user).pk

    try:
        with transaction.atomic():
            ApplicationTemplateUserPermission.objects.create(
                user=user, application_template=application_template
            )
            LogEntry.objects.log_action(
                user_id=request.user.pk,
                content_type_id=content_type_id,
                object_id=user.id,
                object_repr=force_str(user),
                action_flag=CHANGE,
                change_message=f'Added visualisation {application_template} permission',
            )
    except IntegrityError:
        return error(f'{user.get_full_name()} already has access')

    if email_address == token_data.get("email", "").strip().lower():
        update_zendesk_ticket(
            token_data["ticket"],
            comment=f"Access granted by {request.user.email}",
            status="solved",
        )

    catalogue_item = VisualisationCatalogueItem.objects.get(
        visualisation_template=application_template
    )

    if catalogue_item.published:
        send_email(
            settings.NOTIFY_VISUALISATION_ACCESS_GRANTED_TEMPLATE_ID,
            email_address,
            personalisation={
                "visualisation_name": catalogue_item.name,
                "enquiries_contact_email": catalogue_item.enquiries_contact.email,
            },
        )

    messages.success(
        request,
        f'{user.get_full_name()} now has view access to {gitlab_project["name"]}',
    )
    return redirect(
        'visualisations:users-give-access', gitlab_project_id=gitlab_project['id']
    )