示例#1
0
def request_new_domain(request, form, org, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    commtrack_enabled = domain_type == 'commtrack'

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(
        name=form.cleaned_data['domain_name'],
        is_active=False,
        date_created=datetime.utcnow(),
        commtrack_enabled=commtrack_enabled,
        creating_user=current_user.username,
        secure_submissions=True,
    )

    if form.cleaned_data.get('domain_timezone'):
        new_domain.default_timezone = form.cleaned_data['domain_timezone']

    if org:
        new_domain.organization = org
        new_domain.hr_name = request.POST.get('domain_hrname', None) or new_domain.name

    if not new_user:
        new_domain.is_active = True

    # ensure no duplicate domain documents get created on cloudant
    new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save() # we need to get the name from the _id

    create_30_day_trial(new_domain)

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
示例#2
0
def confirm_domain(request, guid=None):
    error = None
    # Did we get a guid?
    if guid is None:
        error = _(
            'An account activation key was not provided.  If you think this '
            'is an error, please contact the system administrator.')

    # Does guid exist in the system?
    else:
        req = RegistrationRequest.get_by_guid(guid)
        if not req:
            error = _(
                'The account activation key "%s" provided is invalid. If you '
                'think this is an error, please contact the system '
                'administrator.') % guid

    if error is not None:
        context = {
            'message_body': error,
            'current_page': {
                'page_name': 'Account Not Activated'
            },
        }
        return render(request, 'registration/confirmation_error.html', context)

    requested_domain = Domain.get_by_name(req.domain)

    # Has guid already been confirmed?
    if requested_domain.is_active:
        assert (req.confirm_time is not None and req.confirm_ip is not None)
        messages.success(
            request, 'Your account %s has already been activated. '
            'No further validation is required.' % req.new_user_username)
        return HttpResponseRedirect(
            reverse("dashboard_default", args=[requested_domain]))

    # Set confirm time and IP; activate domain and new user who is in the
    req.confirm_time = datetime.utcnow()
    req.confirm_ip = get_ip(request)
    req.save()
    requested_domain.is_active = True
    requested_domain.save()
    requesting_user = WebUser.get_by_username(req.new_user_username)

    send_new_request_update_email(requesting_user,
                                  get_ip(request),
                                  requested_domain.name,
                                  is_confirming=True)

    messages.success(
        request,
        'Your account has been successfully activated.  Thank you for taking '
        'the time to confirm your email address: %s.' %
        (requesting_user.username))
    track_workflow(requesting_user.email, "Confirmed new project")
    track_confirmed_account_on_hubspot.delay(requesting_user)
    return HttpResponseRedirect(
        reverse("dashboard_default", args=[requested_domain]))
示例#3
0
def confirm_domain(request, guid=None):
    error = None
    # Did we get a guid?
    if guid is None:
        error = _('An account activation key was not provided.  If you think this '
                  'is an error, please contact the system administrator.')

    # Does guid exist in the system?
    else:
        req = RegistrationRequest.get_by_guid(guid)
        if not req:
            error = _('The account activation key "%s" provided is invalid. If you '
                      'think this is an error, please contact the system '
                      'administrator.') % guid

    if error is not None:
        context = {
            'message_body': error,
            'current_page': {'page_name': 'Account Not Activated'},
        }
        return render(request, 'registration/confirmation_error.html', context)

    requested_domain = Domain.get_by_name(req.domain)

    # Has guid already been confirmed?
    if requested_domain.is_active:
        assert(req.confirm_time is not None and req.confirm_ip is not None)
        messages.success(request, 'Your account %s has already been activated. '
            'No further validation is required.' % req.new_user_username)
        return HttpResponseRedirect(reverse("dashboard_default", args=[requested_domain]))

    # Set confirm time and IP; activate domain and new user who is in the
    req.confirm_time = datetime.utcnow()
    req.confirm_ip = get_ip(request)
    req.save()
    requested_domain.is_active = True
    requested_domain.save()
    requesting_user = WebUser.get_by_username(req.new_user_username)

    send_new_request_update_email(requesting_user, get_ip(request), requested_domain.name, is_confirming=True)

    messages.success(request,
            'Your account has been successfully activated.  Thank you for taking '
            'the time to confirm your email address: %s.'
        % (requesting_user.username))
    track_workflow(requesting_user.email, "Confirmed new project")
    track_confirmed_account_on_hubspot.delay(requesting_user)
    url = reverse("dashboard_default", args=[requested_domain])

    # If user already created an app (via prelogin demo), send them there
    apps = get_apps_in_domain(requested_domain.name, include_remote=False)
    if len(apps) == 1:
        app = apps[0]
        if len(app.modules) == 1 and len(app.modules[0].forms) == 1:
            url = reverse('form_source', args=[requested_domain.name, app.id, 0, 0])

    return HttpResponseRedirect(url)
示例#4
0
def request_new_domain(request, form, org, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    commtrack_enabled = domain_type == 'commtrack'

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(name=form.cleaned_data['domain_name'],
                        is_active=False,
                        date_created=datetime.utcnow(),
                        commtrack_enabled=commtrack_enabled,
                        creating_user=current_user.username)

    bootstrap_default(new_domain)

    if org:
        new_domain.organization = org
        new_domain.hr_name = request.POST.get('domain_hrname',
                                              None) or new_domain.name

    if not new_user:
        new_domain.is_active = True

    # ensure no duplicate domain documents get created on cloudant
    new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save()  # we need to get the name from the _id

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email, dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_domain_request_update_email(request.user,
                                         get_ip(request),
                                         new_domain.name,
                                         is_new_user=new_user)
示例#5
0
def confirm_domain(request, guid=None):
    error = None
    # Did we get a guid?
    if guid is None:
        error = _('An account activation key was not provided.  If you think this '
                  'is an error, please contact the system administrator.')

    # Does guid exist in the system?
    else:
        req = RegistrationRequest.get_by_guid(guid)
        if not req:
            error = _('The account activation key "%s" provided is invalid. If you '
                      'think this is an error, please contact the system '
                      'administrator.') % guid

    if error is not None:
        context = {
            'message_title': _('Account not activated'),
            'message_subtitle': _('Email not yet confirmed'),
            'message_body': error,
        }
        return render(request, 'registration/confirmation_error.html', context)

    requested_domain = Domain.get_by_name(req.domain)

    # Has guid already been confirmed?
    if requested_domain.is_active:
        assert(req.confirm_time is not None and req.confirm_ip is not None)
        messages.success(request, 'Your account %s has already been activated. '
            'No further validation is required.' % req.new_user_username)
        return HttpResponseRedirect(reverse("dashboard_default", args=[requested_domain]))

    # Set confirm time and IP; activate domain and new user who is in the
    req.confirm_time = datetime.utcnow()
    req.confirm_ip = get_ip(request)
    req.save()
    requested_domain.is_active = True
    requested_domain.save()
    requesting_user = WebUser.get_by_username(req.new_user_username)

    send_new_request_update_email(requesting_user, get_ip(request), requested_domain.name, is_confirming=True)

    messages.success(request,
            'Your account has been successfully activated.  Thank you for taking '
            'the time to confirm your email address: %s.'
        % (requesting_user.username))
    track_workflow(requesting_user.email, "Confirmed new project")
    track_confirmed_account_on_hubspot.delay(requesting_user)
    return HttpResponseRedirect(reverse("dashboard_default", args=[requested_domain]))
示例#6
0
def confirm_domain(request, guid=None):
    # Did we get a guid?
    vals = {}
    if guid is None:
        vals['message_title'] = 'Missing Activation Key'
        vals['message_subtitle'] = 'Account Activation Failed'
        vals['message_body'] = 'An account activation key was not provided. If you think this is an error, please contact the system administrator.'
        vals['is_error'] = True
        return render(request, 'registration/confirmation_complete.html', vals)

    # Does guid exist in the system?
    req = RegistrationRequest.get_by_guid(guid)
    if not req:
        vals['message_title'] = 'Invalid Activation Key'
        vals['message_subtitle'] = 'Account Activation Failed'
        vals['message_body'] = 'The account activation key "%s" provided is invalid. If you think this is an error, please contact the system administrator.'  % guid
        vals['is_error'] = True
        return render(request, 'registration/confirmation_complete.html', vals)

    # Has guid already been confirmed?
    vals['requested_domain'] = req.domain
    requested_domain = Domain.get_by_name(req.domain)
    
    _render = partial(
        render_registration_view, 
        domain_type='commtrack' if requested_domain.commtrack_enabled else None)

    if requested_domain.is_active:
        assert(req.confirm_time is not None and req.confirm_ip is not None)
        vals['message_title'] = 'Already Activated'
        vals['message_body'] = 'Your account %s has already been activated. No further validation is required.' % req.new_user_username
        vals['is_error'] = False
        return _render(request, 'registration/confirmation_complete.html', vals)

    # Set confirm time and IP; activate domain and new user who is in the
    req.confirm_time = datetime.utcnow()
    req.confirm_ip = get_ip(request)
    req.save()
    requested_domain.is_active = True
    requested_domain.save()
    requesting_user = WebUser.get_by_username(req.new_user_username)

    send_new_domain_request_update_email(requesting_user, get_ip(request), requested_domain.name, is_confirming=True)

    vals['message_title'] = 'Account Confirmed'
    vals['message_subtitle'] = 'Thank you for activating your account, %s!' % requesting_user.first_name
    vals['message_body'] = 'Your account has been successfully activated. Thank you for taking the time to confirm your email address: %s.' % requesting_user.username
    vals['is_error'] = False
    return _render(request, 'registration/confirmation_complete.html', vals)
示例#7
0
def request_new_domain(request, form, org, new_user=True, slug=''):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(name=form.cleaned_data['domain_name'],
        is_active=False,
        date_created=datetime.utcnow(),
        creating_user=current_user.username)

    if org:
        new_domain.organization = org
        if slug:
            new_domain.slug = slug

    if not new_user:
        new_domain.is_active = True

    new_domain.save()
    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save() # we need to get the name from the _id

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_domain_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
示例#8
0
 def audit_view(cls, request, user, view_func, view_kwargs, extra={}):
     """Creates an instance of a Access log."""
     try:
         audit = cls.create_audit(cls, user)
         audit.description += "View"
         if len(list(request.GET)) > 0:
             params = "&".join(f"{x}={request.GET[x]}"
                               for x in request.GET.keys())
             audit.request_path = f"{request.path}?{params}"
         else:
             audit.request_path = request.path
         audit.ip_address = get_ip(request)
         audit.user_agent = request.META.get('HTTP_USER_AGENT', '<unknown>')
         audit.view = "%s.%s" % (view_func.__module__, view_func.__name__)
         for k in STANDARD_HEADER_KEYS:
             header_item = request.META.get(k, None)
             if header_item is not None:
                 audit.headers[k] = header_item
         # it's a bit verbose to go to that extreme, TODO: need to have
         # targeted fields in the META, but due to server differences, it's
         # hard to make it universal.
         #audit.headers = request.META
         audit.session_key = request.session.session_key
         audit.extra = extra
         audit.view_kwargs = view_kwargs
         return audit
     except Exception:
         log.exception("NavigationEventAudit.audit_view error")
示例#9
0
def _publish_snapshot(request, domain, published_snapshot=None):
    snapshots = domain.snapshots()
    for snapshot in snapshots:
        if snapshot.published:
            snapshot.published = False
            if not published_snapshot or snapshot.name != published_snapshot.name:
                snapshot.save()
    if published_snapshot:
        if published_snapshot.copied_from.name != domain.name:
            messages.error(request, "Invalid snapshot")
            return False

        # cda stuff. In order to publish a snapshot, a user must have agreed to this
        published_snapshot.cda.signed = True
        published_snapshot.cda.date = datetime.datetime.utcnow()
        published_snapshot.cda.type = 'Content Distribution Agreement'
        if request.couch_user:
            published_snapshot.cda.user_id = request.couch_user.get_id
        published_snapshot.cda.user_ip = get_ip(request)

        published_snapshot.published = True
        published_snapshot.save()
        _notification_email_on_publish(domain, published_snapshot,
                                       request.couch_user)
    return True
示例#10
0
def register_user(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    assert domain_type in DOMAIN_TYPES

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)
                return redirect('registration_domain', domain_type=domain_type)
        else:
            form = NewWebUserRegistrationForm(
                initial={'domain_type': domain_type})

        context.update({'form': form, 'domain_type': domain_type})
        return render(request, 'registration/create_new_user.html', context)
示例#11
0
    def _create_new_user(self, request, username, async_signup):
        """
        This creates a new user in HQ based on information in the request.
        :param request: HttpRequest
        :param username: String (username)
        :param async_signup: AsyncSignupRequest
        :return: User, WebUser
        """
        invitation = async_signup.invitation if async_signup else None
        created_via = (USER_CHANGE_VIA_SSO_INVITE if invitation
                       else USER_CHANGE_VIA_SSO_NEW_USER)
        created_by = (CouchUser.get_by_user_id(invitation.invited_by) if invitation
                      else None)
        domain = invitation.domain if invitation else None

        new_web_user = activate_new_user(
            username=username,
            password=User.objects.make_random_password(),
            created_by=created_by,
            created_via=created_via,
            first_name=get_sso_user_first_name_from_session(request),
            last_name=get_sso_user_last_name_from_session(request),
            domain=domain,
            ip=get_ip(request),
        )
        request.sso_new_user_messages['success'].append(
            _("User account for {} created.").format(new_web_user.username)
        )
        self._process_new_user_data(request, new_web_user, async_signup)
        return User.objects.get(username=username), new_web_user
示例#12
0
    def _create_new_account(self, reg_form):
        activate_new_user(reg_form, ip=get_ip(self.request))
        new_user = authenticate(username=reg_form.cleaned_data['email'],
                                password=reg_form.cleaned_data['password'])
        web_user = WebUser.get_by_username(new_user.username)

        if 'phone_number' in reg_form.cleaned_data and reg_form.cleaned_data[
                'phone_number']:
            web_user.phone_numbers.append(
                reg_form.cleaned_data['phone_number'])
            web_user.save()

        email = new_user.email

        # registration analytics
        persona = reg_form.cleaned_data['persona']
        persona_other = reg_form.cleaned_data['persona_other']
        appcues_ab_test = toggles.APPCUES_AB_TEST.enabled(
            web_user.username, toggles.NAMESPACE_USER)

        track_workflow(email, "Requested New Account")
        track_workflow(email, "Persona Field Filled Out", {
            'personachoice': persona,
            'personaother': persona_other,
        })

        track_web_user_registration_hubspot.delay(
            web_user, {
                'buyer_persona': persona,
                'buyer_persona_other': persona_other,
                "appcues_test": "On" if appcues_ab_test else "Off",
            })

        login(self.request, new_user)
示例#13
0
def register_org(request, template="registration/org_request.html"):
    referer_url = request.GET.get('referer', '')
    if request.method == "POST":
        form = OrganizationRegistrationForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data["org_name"]
            title = form.cleaned_data["org_title"]
            email = form.cleaned_data["email"]
            url = form.cleaned_data["url"]
            location = form.cleaned_data["location"]

            org = Organization(name=name, title=title, location=location, email=email, url=url)
            org.save()

            request.couch_user.add_org_membership(org.name, is_admin=True)
            request.couch_user.save()

            send_new_request_update_email(request.couch_user, get_ip(request), org.name, entity_type="org")

            if referer_url:
                return redirect(referer_url)
            messages.info(request, render_to_string('orgs/partials/landing_notification.html',
                                                       {"org": org, "user": request.couch_user}), extra_tags="html")
            return HttpResponseRedirect(reverse("orgs_landing", args=[name]))
    else:
        form = OrganizationRegistrationForm()

    return render(request, template, {
        'form': form,
    })
示例#14
0
    def _create_new_account(self, reg_form):
        activate_new_user(reg_form, ip=get_ip(self.request))
        new_user = authenticate(username=reg_form.cleaned_data['email'],
                                password=reg_form.cleaned_data['password'])
        if 'phone_number' in reg_form.cleaned_data and reg_form.cleaned_data[
                'phone_number']:
            web_user = WebUser.get_by_username(new_user.username)
            web_user.phone_numbers.append(
                reg_form.cleaned_data['phone_number'])
            web_user.save()

        is_mobile = reg_form.cleaned_data.get('is_mobile')
        email = new_user.email

        properties = {}
        if is_mobile:
            toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST_CONTROLLER.set(email, True)
            variation = toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST.enabled(
                email, toggles.NAMESPACE_USER)
            properties = {
                "mobile_signups_test_march2018test":
                "variation" if variation else "control"
            }

        track_workflow(email, "Requested new account", properties)
        login(self.request, new_user)
示例#15
0
def register_user(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES:
        raise Http404()

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain", domain_type=domain_type)
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)
                return redirect(
                    'registration_domain', domain_type=domain_type)
        else:
            form = NewWebUserRegistrationForm(
                    initial={'domain_type': domain_type})

        context.update({
            'form': form,
            'domain_type': domain_type
        })
        return render(request, 'registration/create_new_user.html', context)
示例#16
0
def register_user(request, domain_type=None):
    domain_type = domain_type or "commcare"
    assert domain_type in DOMAIN_TYPES

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("homepage")
    else:
        if request.method == "POST":
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data["email"], password=form.cleaned_data["password"])
                login(request, new_user)
                return redirect("registration_domain", domain_type=domain_type)
        else:
            form = NewWebUserRegistrationForm(initial={"domain_type": domain_type})

        context.update({"form": form, "domain_type": domain_type})
        return render(request, "registration/create_new_user.html", context)
示例#17
0
def register_org(request, template="registration/org_request.html"):
    referer_url = request.GET.get('referer', '')
    if request.method == "POST":
        form = OrganizationRegistrationForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data["org_name"]
            title = form.cleaned_data["org_title"]
            email = form.cleaned_data["email"]
            url = form.cleaned_data["url"]
            location = form.cleaned_data["location"]

            org = Organization(name=name, title=title, location=location, email=email, url=url)
            org.save()

            request.couch_user.add_org_membership(org.name, is_admin=True)
            request.couch_user.save()

            send_new_request_update_email(request.couch_user, get_ip(request), org.name, entity_type="org")

            if referer_url:
                return redirect(referer_url)
            messages.info(request, render_to_string('orgs/partials/landing_notification.html',
                                                       {"org": org, "user": request.couch_user}), extra_tags="html")
            return HttpResponseRedirect(reverse("orgs_landing", args=[name]))
    else:
        form = OrganizationRegistrationForm()

    return render(request, template, {
        'form': form,
    })
示例#18
0
def register_user(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES:
        raise Http404()

    prefilled_email = request.GET.get('e', '')

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain", domain_type=domain_type)
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)
                track_workflow.delay(new_user.email, "Requested new account")
                meta = {
                    'HTTP_X_FORWARDED_FOR': request.META.get('HTTP_X_FORWARDED_FOR'),
                    'REMOTE_ADDR': request.META.get('REMOTE_ADDR'),
                    'opt_into_emails': form.cleaned_data['email_opt_in'],
                }
                track_created_hq_account_on_hubspot.delay(new_user, request.COOKIES, meta)
                requested_domain = form.cleaned_data['hr_name']
                if form.cleaned_data['create_domain']:
                    org = None
                    try:
                        requested_domain = request_new_domain(
                            request, form, org, new_user=True, domain_type=domain_type)
                    except NameUnavailableException:
                        context.update({
                            'error_msg': _('Project name already taken - please try another'),
                            'show_homepage_link': 1
                        })
                        return render(request, 'error.html', context)

                context = get_domain_context(form.cleaned_data['domain_type']).update({
                    'alert_message': _("An email has been sent to %s.") % request.user.username,
                    'requested_domain': requested_domain,
                    'track_domain_registration': True,
                })
                return render(request, 'registration/confirmation_sent.html', context)
        else:
            form = NewWebUserRegistrationForm(
                initial={'domain_type': domain_type, 'email': prefilled_email, 'create_domain': True})

        context.update({
            'form': form,
            'domain_type': domain_type,
        })
        return render(request, 'registration/create_new_user.html', context)
示例#19
0
 def _create_new_account(self, reg_form):
     activate_new_user(reg_form, ip=get_ip(self.request))
     new_user = authenticate(
         username=reg_form.cleaned_data['email'],
         password=reg_form.cleaned_data['password']
     )
     track_workflow(new_user.email, "Requested new account")
     login(self.request, new_user)
示例#20
0
def eula_agreement(request):
    if request.method == 'POST':
        current_user = CouchUser.from_django_user(request.user)
        current_user.eula.signed = True
        current_user.eula.date = datetime.utcnow()
        current_user.eula.user_ip = get_ip(request)
        current_user.save()

    return HttpResponseRedirect(request.POST.get('next', '/'))
示例#21
0
def eula_agreement(request):
    if request.method == 'POST':
        current_user = CouchUser.from_django_user(request.user)
        current_user.eula.signed = True
        current_user.eula.date = datetime.utcnow()
        current_user.eula.user_ip = get_ip(request)
        current_user.save()

    return HttpResponseRedirect(request.POST.get('next', '/'))
示例#22
0
def register_user(request):
    prefilled_email = request.GET.get('e', '')
    context = get_domain_context()

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])

                track_workflow(new_user.email, "Requested new account")

                login(request, new_user)

                requested_domain = form.cleaned_data['hr_name']
                if form.cleaned_data['create_domain']:
                    try:
                        requested_domain = request_new_domain(
                            request, form, is_new_user=True)
                    except NameUnavailableException:
                        context.update({
                            'current_page': {'page_name': _('Oops!')},
                            'error_msg': _('Project name already taken - please try another'),
                            'show_homepage_link': 1
                        })
                        return render(request, 'error.html', context)

                context.update({
                    'requested_domain': requested_domain,
                    'track_domain_registration': True,
                    'current_page': {'page_name': _('Confirmation Email Sent')},
                })
                return render(request, 'registration/confirmation_sent.html', context)
            context.update({'create_domain': form.cleaned_data['create_domain']})
        else:
            form = NewWebUserRegistrationForm(
                initial={'email': prefilled_email, 'create_domain': True})
            context.update({'create_domain': True})
            meta = get_meta(request)
            track_clicked_signup_on_hubspot(prefilled_email, request.COOKIES, meta)

        context.update({
            'form': form,
            'current_page': {'page_name': _('Create an Account')},
            'hide_password_feedback': settings.ENABLE_DRACONIAN_SECURITY_FEATURES,
            'is_register_user': True,
        })
        return render(request, 'registration/create_new_user.html', context)
示例#23
0
def eula_agreement(request, domain):
    domain = Domain.get_by_name(domain)
    if request.method == 'POST':
        current_user = CouchUser.from_django_user(request.user)
        current_user.eula.signed = True
        current_user.eula.date = datetime.utcnow()
        current_user.eula.type = 'End User License Agreement'
        current_user.eula.user_ip = get_ip(request)
        current_user.save()

    return HttpResponseRedirect(reverse("corehq.apps.reports.views.default", args=[domain]))
示例#24
0
def eula_agreement(request, domain):
    domain = Domain.get_by_name(domain)
    if request.method == 'POST':
        current_user = CouchUser.from_django_user(request.user)
        current_user.eula.signed = True
        current_user.eula.date = datetime.utcnow()
        current_user.eula.type = 'End User License Agreement'
        current_user.eula.user_ip = get_ip(request)
        current_user.save()

    return HttpResponseRedirect(reverse("corehq.apps.reports.views.default", args=[domain]))
示例#25
0
 def _create_new_account(self, reg_form):
     activate_new_user(reg_form, ip=get_ip(self.request))
     new_user = authenticate(username=reg_form.cleaned_data['email'],
                             password=reg_form.cleaned_data['password'])
     if 'phone_number' in reg_form.cleaned_data and reg_form.cleaned_data[
             'phone_number']:
         web_user = WebUser.get_by_username(new_user.username)
         web_user.phone_numbers.append(
             reg_form.cleaned_data['phone_number'])
         web_user.save()
     track_workflow(new_user.email, "Requested new account")
     login(self.request, new_user)
示例#26
0
 def audit_login_failed(cls, request, username, *args, **kwargs):
     '''Creates an instance of a Access log.
     '''
     audit = cls.create_audit(cls, username)
     audit.ip_address = get_ip(request)
     audit.access_type = 'login_failed'
     if username is not None:
         audit.description = "Login Failure: %s" % (username)
     else:
         audit.description = "Login Failure"
     audit.session_key = request.session.session_key
     audit.save()
示例#27
0
    def _create_new_account(self, reg_form, additional_hubspot_data=None):
        activate_new_user_via_reg_form(reg_form,
                                       created_by=None,
                                       created_via=USER_CHANGE_VIA_WEB,
                                       ip=get_ip(self.request))
        new_user = authenticate(username=reg_form.cleaned_data['email'],
                                password=reg_form.cleaned_data['password'],
                                request=self.request)
        web_user = WebUser.get_by_username(new_user.username, strict=True)

        if 'phone_number' in reg_form.cleaned_data and reg_form.cleaned_data[
                'phone_number']:
            web_user.phone_numbers.append(
                reg_form.cleaned_data['phone_number'])
            web_user.save()

        if settings.IS_SAAS_ENVIRONMENT:
            email = new_user.email

            # registration analytics
            # only do anything with this in a SAAS environment

            persona = reg_form.cleaned_data['persona']
            persona_other = reg_form.cleaned_data['persona_other']

            track_workflow(email, "Requested New Account", {
                'environment': settings.SERVER_ENVIRONMENT,
            })
            track_workflow(email, "Persona Field Filled Out", {
                'personachoice': persona,
                'personaother': persona_other,
            })

            if not additional_hubspot_data:
                additional_hubspot_data = {}
            additional_hubspot_data.update({
                'buyer_persona':
                persona,
                'buyer_persona_other':
                persona_other,
            })
            track_web_user_registration_hubspot(self.request, web_user,
                                                additional_hubspot_data)
            if not persona or (persona == 'Other' and not persona_other):
                # There shouldn't be many instances of this.
                _assert = soft_assert('@'.join(['bbuczyk', 'dimagi.com']),
                                      exponential_backoff=False)
                _assert(
                    False, "[BAD PERSONA DATA] Persona fields during "
                    "login submitted empty. User: {}".format(email))

        login(self.request, new_user)
示例#28
0
def resend_confirmation(request):
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        dom_req = None

    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    context = get_domain_context()
    default_page_name = _('Resend Confirmation Email')

    if request.method == 'POST':
        if (datetime.utcnow() - dom_req.request_time).seconds < CONFIRMATION_RESEND_LIMIT_SECONDS:
            context = {
                'message_body': _(f'Please wait at least {CONFIRMATION_RESEND_LIMIT_SECONDS} '
                                  f'seconds before requesting again.'),
                'current_page': {'page_name': default_page_name},
            }
            return render(request, 'registration/confirmation_error.html', context)
        try:
            dom_req.request_time = datetime.utcnow()
            dom_req.request_ip = get_ip(request)
            dom_req.save()
            send_domain_registration_email(dom_req.new_user_username,
                    dom_req.domain, dom_req.activation_guid,
                    request.user.get_full_name(), request.user.first_name)
        except Exception:
            context.update({
                'current_page': {'page_name': _('Oops!')},
                'error_msg': _('There was a problem with your request'),
                'show_homepage_link': 1,
            })
            return render(request, 'error.html', context)
        else:
            context.update({
                'requested_domain': dom_req.domain,
                'current_page': {'page_name': _('Confirmation Email Sent')},
            })
            return render(request, 'registration/confirmation_sent.html',
                context)

    context.update({
        'requested_domain': dom_req.domain,
        'current_page': {'page_name': default_page_name},
    })
    return render(request, 'registration/confirmation_resend.html', context)
示例#29
0
 def create_entry(cls, request, couch_user=None, is_login_page=False):
     couch_user = request.couch_user if couch_user is None else couch_user
     record = cls(
         username=couch_user.username,
         assigned_location_ids=couch_user.get_location_ids(getattr(request, 'domain', None)),
         ip_address=get_ip(request),
         url=request.path,
         get_data=request.GET,
         post_data=request.POST if not is_login_page else {},
         session_key=request.session.session_key,
     )
     record.save()
     return record.id
示例#30
0
def _handle_access_event(event_type, request, user_id):
    ip_address = ''
    agent = None
    path = ''

    if request:
        ip_address = get_ip(request)
        agent = request.META.get('HTTP_USER_AGENT', agent)
        path = request.path

    timestamp = datetime.now()
    UserAccessLog.objects.create(action=event_type, user_id=user_id, ip=ip_address,
        user_agent=agent, path=path, timestamp=timestamp)
示例#31
0
def get_user_attempt(request):
    """
    Returns access attempt record if it exists.
    Otherwise return None.
    """
    ip = get_ip(request)
    if USE_USER_AGENT:
        ua = request.META.get('HTTP_USER_AGENT', '<unknown>')

        attempts = AccessAudit.view('auditcare/login_events',
                                    key=['ip_ua', ip, ua],
                                    include_docs=True,
                                    limit=25).all()

        #attempts = AccessAttempt.objects.filter( user_agent=ua, ip_address=ip )
    else:
        attempts = AccessAudit.view('auditcare/login_events',
                                    key=['ip', ip],
                                    include_docs=True,
                                    limit=25).all()
        #attempts = AccessAttempt.objects.filter( ip_address=ip )

    attempts = sorted(attempts, key=lambda x: x.event_date, reverse=True)
    if not attempts:
        log.info("No attempts for given access, creating new attempt")
        return None

    #walk the attempts
    attempt = None
    for at in attempts:
        if at.access_type == models.ACCESS_FAILED:
            attempt = at
            break
        elif at.access_type == models.ACCESS_LOGIN:
            attempt = None
            break
        elif at.access_type == models.ACCESS_LOGOUT:
            attempt = None
            break

    if COOLOFF_TIME and attempt and datetime.utcnow(
    ) - attempt.event_date < COOLOFF_TIME:
        log.info(
            "Last login failure is still within the cooloff time, incrementing last access attempt."
        )
    else:
        log.info(
            "Last login failure is outside the cooloff time, creating new access attempt."
        )
        return None
    return attempt
示例#32
0
 def create_entry(cls, request, response, couch_user=None, is_login_page=False):
     couch_user = request.couch_user if couch_user is None else couch_user
     record = cls(
         username=couch_user.username,
         assigned_location_ids=couch_user.get_location_ids(getattr(request, 'domain', None)),
         ip_address=get_ip(request),
         url=request.path,
         get_data=request.GET,
         post_data=request.POST if not is_login_page else {},
         session_key=request.session.session_key,
         response_code=response.status_code if response else None
     )
     record.save()
     return record.id
示例#33
0
    def post(self, request, guid, *args, **kwargs):
        self.guid = guid

        if not self.active_transfer:
            raise Http404()

        if self.active_transfer.to_username != request.user.username and not request.user.is_superuser:
            return HttpResponseRedirect(reverse("no_permissions"))

        self.active_transfer.transfer_domain(ip=get_ip(request))
        messages.success(request, _("Successfully transferred ownership of project '{domain}'")
                         .format(domain=self.active_transfer.domain))

        return HttpResponseRedirect(reverse('dashboard_default', args=[self.active_transfer.domain]))
示例#34
0
    def post(self, request, guid, *args, **kwargs):
        self.guid = guid

        if not self.active_transfer:
            raise Http404()

        if self.active_transfer.to_username != request.user.username and not request.user.is_superuser:
            return HttpResponseRedirect(reverse("no_permissions"))

        self.active_transfer.transfer_domain(ip=get_ip(request))
        messages.success(request, _("Successfully transferred ownership of project '{domain}'")
                         .format(domain=self.active_transfer.domain))

        return HttpResponseRedirect(reverse('dashboard_default', args=[self.active_transfer.domain]))
示例#35
0
    def audit_logout(cls, request, user):
        '''Log a logout event'''
        audit = cls.create_audit(cls, user)
        audit.ip_address = get_ip(request)

        if user == AnonymousUser:
            audit.description = "Logout anonymous"
        elif user is None:
            audit.description = "None"
        else:
            audit.description = "Logout %s" % (user.username)
        audit.access_type = 'logout'
        audit.session_key = request.session.session_key
        audit.save()
示例#36
0
    def _create_new_account(self, reg_form, additional_hubspot_data=None):
        activate_new_user(reg_form, ip=get_ip(self.request))
        new_user = authenticate(
            username=reg_form.cleaned_data['email'],
            password=reg_form.cleaned_data['password']
        )
        web_user = WebUser.get_by_username(new_user.username, strict=True)

        if 'phone_number' in reg_form.cleaned_data and reg_form.cleaned_data['phone_number']:
            web_user.phone_numbers.append(reg_form.cleaned_data['phone_number'])
            web_user.save()

        if settings.IS_SAAS_ENVIRONMENT:
            email = new_user.email

            # registration analytics
            # only do anything with this in a SAAS environment

            persona = reg_form.cleaned_data['persona']
            persona_other = reg_form.cleaned_data['persona_other']

            track_workflow(email, "Requested New Account", {
                'environment': settings.SERVER_ENVIRONMENT,
            })
            track_workflow(email, "Persona Field Filled Out", {
                'personachoice': persona,
                'personaother': persona_other,
            })

            if not additional_hubspot_data:
                additional_hubspot_data = {}
            additional_hubspot_data.update({
                'buyer_persona': persona,
                'buyer_persona_other': persona_other,
            })
            track_web_user_registration_hubspot(
                self.request,
                web_user,
                additional_hubspot_data
            )
            if not persona or (persona == 'Other' and not persona_other):
                # There shouldn't be many instances of this.
                _assert = soft_assert('@'.join(['bbuczyk', 'dimagi.com']), exponential_backoff=False)
                _assert(
                    False,
                    "[BAD PERSONA DATA] Persona fields during "
                    "login submitted empty. User: {}".format(email)
                )

        login(self.request, new_user)
示例#37
0
 def audit_login(cls, request, user, *args, **kwargs):
     '''Creates an instance of a Access log.
     '''
     audit = cls.create_audit(cls, user)
     audit.ip_address = get_ip(request)
     ua = request.META.get('HTTP_USER_AGENT', '<unknown>')
     audit.http_accept = request.META.get('HTTP_ACCEPT', '<unknown>')
     audit.path_info = request.META.get('PATH_INFO', '<unknown>')
     audit.user_agent = ua
     audit.access_type = 'login'
     audit.description = "Login Success"
     audit.session_key = request.session.session_key
     audit.get_data = []  # [query2str(request.GET.items())]
     audit.post_data = []
     audit.save()
示例#38
0
        def wrapper(request, *args, **kwargs):
            auth = api_auth_class.is_authenticated(request)
            if auth:
                if isinstance(auth, HttpUnauthorized):
                    return auth
                try:
                    allowed_ips = request.user.api_key.apikeysettings.ip_whitelist
                except (ApiKey.DoesNotExist, ApiKeySettings.DoesNotExist):
                    allowed_ips = []
                if allowed_ips and get_ip(request) not in allowed_ips:
                    return HttpUnauthorized()
                return view(request, *args, **kwargs)

            response = HttpUnauthorized()
            return response
示例#39
0
 def create_audit(cls, request, user):
     audit = cls()
     audit.domain = get_domain(request)
     audit.path = request.path
     audit.ip_address = get_ip(request)
     audit.session_key = request.session.session_key
     audit.user_agent = request.META.get('HTTP_USER_AGENT')
     if isinstance(user, AnonymousUser):
         audit.user = None
     elif user is None:
         audit.user = None
     elif isinstance(user, User):
         audit.user = user.username
     else:
         audit.user = user
     return audit
示例#40
0
    def decorated_logout(request, *args, **kwargs):
        # share some useful information
        if func.__name__ != 'decorated_logout' and VERBOSE:
            log.info('AXES: Calling decorated logout function: %s',
                     func.__name__)
            if args: log.info('args: %s', args)
            if kwargs: log.info('kwargs: %s', kwargs)
        log.info("Function: %s", func.__name__)
        log.info("Logged logout for user %s", request.user.username)
        user = request.user
        #it's a successful login.
        ip = get_ip(request)
        ua = request.META.get('HTTP_USER_AGENT', '<unknown>')
        attempt = AccessAudit()
        attempt.doc_type = AccessAudit.__name__
        attempt.access_type = models.ACCESS_LOGOUT
        attempt.user_agent = ua
        attempt.user = user.username
        attempt.session_key = request.session.session_key
        attempt.ip_address = ip
        attempt.get_data = []  #[query2str(request.GET.items())]
        attempt.post_data = []
        attempt.http_accept = request.META.get('HTTP_ACCEPT', '<unknown>')
        attempt.path_info = request.META.get('PATH_INFO', '<unknown>')
        attempt.failures_since_start = 0
        attempt.save()

        # call the logout function
        response = func(request, *args, **kwargs)

        if func.__name__ == 'decorated_logout':
            # if we're dealing with this function itself, don't bother checking
            # for invalid login attempts.  I suppose there's a bunch of
            # recursion going on here that used to cause one failed login
            # attempt to generate 10+ failed access attempt records (with 3
            # failed attempts each supposedly)
            return response
        return response
示例#41
0
 def _attach_shared_props(doc):
     # attaches shared properties of the request to the document.
     # used on forms and errors
     doc['submit_ip'] = get_ip(request)
     doc['path'] = request.path
     
     # if you have OpenRosaMiddleware running the headers appear here
     if hasattr(request, 'openrosa_headers'):
         doc['openrosa_headers'] = request.openrosa_headers 
     
     # if you have SyncTokenMiddleware running the headers appear here
     if hasattr(request, 'last_sync_token'):
         doc['last_sync_token'] = request.last_sync_token 
     
     # a hack allowing you to specify the submit time to use
     # instead of the actual time receiver
     # useful for migrating data
     received_on = request.META.get('HTTP_X_SUBMIT_TIME')
     date_header = request.META.get('HTTP_DATE')
     if received_on:
         doc.received_on = string_to_datetime(received_on)
     if date_header:
         # comes in as:
         # Mon, 11 Apr 2011 18:24:43 GMT
         # goes out as:
         # 2011-04-11T18:24:43Z
         try:
             date = datetime.strptime(date_header, "%a, %d %b %Y %H:%M:%S GMT")
             date = datetime.strftime(date, "%Y-%m-%dT%H:%M:%SZ")
         except:
             logging.error("Receiver app: incoming submission has a date header that we can't parse: '%s'"
                 % date_header
             )
             date = date_header
         doc['date_header'] = date
     
     return doc
示例#42
0
def _publish_snapshot(request, domain, published_snapshot=None):
    snapshots = domain.snapshots()
    for snapshot in snapshots:
        if snapshot.published:
            snapshot.published = False
            if not published_snapshot or snapshot.name != published_snapshot.name:
                snapshot.save()
    if published_snapshot:
        if published_snapshot.copied_from.name != domain.name:
            messages.error(request, "Invalid snapshot")
            return False

        # cda stuff. In order to publish a snapshot, a user must have agreed to this
        published_snapshot.cda.signed = True
        published_snapshot.cda.date = datetime.datetime.utcnow()
        published_snapshot.cda.type = 'Content Distribution Agreement'
        if request.couch_user:
            published_snapshot.cda.user_id = request.couch_user.get_id
        published_snapshot.cda.user_ip = get_ip(request)

        published_snapshot.published = True
        published_snapshot.save()
        _notification_email_on_publish(domain, published_snapshot, request.couch_user)
    return True
示例#43
0
    def is_authenticated(self, request):
        """Follows what tastypie does, then tests for IP whitelisting
        """
        try:
            username, api_key = self.extract_credentials(request)
        except ValueError:
            return self._unauthorized()

        if not username or not api_key:
            return self._unauthorized()

        User = get_user_model()

        lookup_kwargs = {User.USERNAME_FIELD: username}
        try:
            user = User.objects.prefetch_related("api_keys").get(
                **lookup_kwargs)
        except (User.DoesNotExist, User.MultipleObjectsReturned):
            return self._unauthorized()

        if not self.check_active(user):
            return False

        # ensure API Key exists
        try:
            key = user.api_keys.get(key=api_key)
        except HQApiKey.DoesNotExist:
            return self._unauthorized()

        # ensure the IP address is in the allowlist, if that exists
        if key.ip_allowlist and (get_ip(request) not in key.ip_allowlist):
            return self._unauthorized()

        request.user = user
        request.api_key = key
        return True
示例#44
0
def register_user(request):
    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        vals = {}
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("domain_list")
    else:
        if request.method == 'POST': # If the form has been submitted...
            form = NewWebUserRegistrationForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)

                return redirect('registration_domain')
        else:
            form = NewWebUserRegistrationForm() # An unbound form

        vals = dict(form = form)
        return render(request, 'registration/create_new_user.html', vals)
示例#45
0
def request_new_domain(request, form, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    name = name_to_url(form.cleaned_data['hr_name'], "project")
    with CriticalSection(['request_domain_name_{}'.format(name)]):
        name = Domain.generate_name(name)
        new_domain = Domain(
            name=name,
            hr_name=form.cleaned_data['hr_name'],
            is_active=False,
            date_created=datetime.utcnow(),
            creating_user=current_user.username,
            secure_submissions=True,
        )

        if form.cleaned_data.get('domain_timezone'):
            new_domain.default_timezone = form.cleaned_data['domain_timezone']

        if not new_user:
            new_domain.is_active = True

        # ensure no duplicate domain documents get created on cloudant
        new_domain.save(**get_safe_write_kwargs())

    if domain_type == 'commtrack':
        new_domain.convert_to_commtrack()

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save() # we need to get the name from the _id

    create_30_day_trial(new_domain)
    UserRole.init_domain_with_presets(new_domain.name)

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid,
                                       request.user.get_full_name())
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)

    return new_domain.name
示例#46
0
def confirm_domain(request, guid=''):
    with CriticalSection(['confirm_domain_' + guid]):
        error = None
        # Did we get a guid?
        if not guid:
            error = _('An account activation key was not provided.  If you think this '
                      'is an error, please contact the system administrator.')

        # Does guid exist in the system?
        else:
            req = RegistrationRequest.get_by_guid(guid)
            if not req:
                error = _('The account activation key "%s" provided is invalid. If you '
                          'think this is an error, please contact the system '
                          'administrator.') % guid

        if error is not None:
            context = {
                'message_body': error,
                'current_page': {'page_name': 'Account Not Activated'},
            }
            return render(request, 'registration/confirmation_error.html', context)

        requested_domain = Domain.get_by_name(req.domain)
        view_name = "dashboard_default"
        view_args = [requested_domain.name]
        if not domain_has_apps(req.domain):
            if False and settings.IS_SAAS_ENVIRONMENT and domain_is_on_trial(req.domain):
                view_name = "app_from_template"
                view_args.append("appcues")
            else:
                view_name = "default_new_app"

        # Has guid already been confirmed?
        if requested_domain.is_active:
            assert(req.confirm_time is not None and req.confirm_ip is not None)
            messages.success(request, 'Your account %s has already been activated. '
                'No further validation is required.' % req.new_user_username)
            return HttpResponseRedirect(reverse(view_name, args=view_args))

        # Set confirm time and IP; activate domain and new user who is in the
        req.confirm_time = datetime.utcnow()
        req.confirm_ip = get_ip(request)
        req.save()
        requested_domain.is_active = True
        requested_domain.save()
        requesting_user = WebUser.get_by_username(req.new_user_username)

        send_new_request_update_email(requesting_user, get_ip(request), requested_domain.name, is_confirming=True)

        messages.success(request,
                'Your account has been successfully activated.  Thank you for taking '
                'the time to confirm your email address: %s.'
            % (requesting_user.username))
        track_workflow(requesting_user.email, "Confirmed new project")
        track_confirmed_account_on_hubspot.delay(requesting_user)
        request.session['CONFIRM'] = True

        if settings.IS_SAAS_ENVIRONMENT:
            # For AppCues v3, land new user in Web Apps
            view_name = get_cloudcare_urlname(requested_domain.name)
        return HttpResponseRedirect(reverse(view_name, args=view_args))
示例#47
0
def request_new_domain(request, form, is_new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    dom_req = RegistrationRequest()
    if is_new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    project_name = form.cleaned_data.get('hr_name') or form.cleaned_data.get('project_name')
    name = name_to_url(project_name, "project")
    with CriticalSection(['request_domain_name_{}'.format(name)]):
        name = Domain.generate_name(name)
        new_domain = Domain(
            name=name,
            hr_name=project_name,
            is_active=False,
            date_created=datetime.utcnow(),
            creating_user=current_user.username,
            secure_submissions=True,
            use_sql_backend=True,
            first_domain_for_user=is_new_user
        )

        if form.cleaned_data.get('domain_timezone'):
            new_domain.default_timezone = form.cleaned_data['domain_timezone']

        if not is_new_user:
            new_domain.is_active = True

        # ensure no duplicate domain documents get created on cloudant
        new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save()  # we need to get the name from the _id

    if is_new_user:
        # Only new-user domains are eligible for Advanced trial
        # domains with no subscription are equivalent to be on free Community plan
        create_30_day_advanced_trial(new_domain, current_user.username)
    else:
        ensure_explicit_community_subscription(new_domain.name, date.today())

    UserRole.init_domain_with_presets(new_domain.name)

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if is_new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid,
                                       request.user.get_full_name())
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=is_new_user)

    set_toggle(toggles.USE_FORMPLAYER_FRONTEND.slug, new_domain.name, True, namespace=toggles.NAMESPACE_DOMAIN)
    meta = get_meta(request)
    track_created_new_project_space_on_hubspot.delay(current_user, request.COOKIES, meta)
    return new_domain.name
示例#48
0
def request_new_domain(request, form, is_new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user, strict=True)

    dom_req = RegistrationRequest()
    if is_new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    project_name = form.cleaned_data.get('hr_name') or form.cleaned_data.get(
        'project_name')
    name = name_to_url(project_name, "project")
    with CriticalSection(['request_domain_name_{}'.format(name)]):
        name = Domain.generate_name(name)
        new_domain = Domain(name=name,
                            hr_name=project_name,
                            is_active=False,
                            date_created=datetime.utcnow(),
                            creating_user=current_user.username,
                            secure_submissions=True,
                            use_sql_backend=True,
                            first_domain_for_user=is_new_user)

        # Avoid projects created by dimagi.com staff members as self started
        new_domain.internal.self_started = not current_user.is_dimagi

        if form.cleaned_data.get('domain_timezone'):
            new_domain.default_timezone = form.cleaned_data['domain_timezone']

        if not is_new_user:
            new_domain.is_active = True

        # ensure no duplicate domain documents get created on cloudant
        new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save()  # we need to get the name from the _id
    dom_req.domain = new_domain.name

    if not settings.ENTERPRISE_MODE:
        _setup_subscription(new_domain.name, current_user)

    UserRole.init_domain_with_presets(new_domain.name)

    if request.user.is_authenticated:
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username
    elif is_new_user:
        _soft_assert_registration_issues(
            f"A new user {request.user.username} was not added to their domain "
            f"{new_domain.name} during registration")

    if is_new_user:
        dom_req.save()
        if settings.IS_SAAS_ENVIRONMENT:
            #  Load template apps to the user's new domain in parallel
            from corehq.apps.app_manager.tasks import load_appcues_template_app
            header = [
                load_appcues_template_app.si(new_domain.name,
                                             current_user.username, slug)
                for slug in APPCUES_APP_SLUGS
            ]
            callback = send_domain_registration_email.si(
                request.user.email, dom_req.domain, dom_req.activation_guid,
                request.user.get_full_name(), request.user.first_name)
            chord(header)(callback)
        else:
            send_domain_registration_email(request.user.email, dom_req.domain,
                                           dom_req.activation_guid,
                                           request.user.get_full_name(),
                                           request.user.first_name)
    send_new_request_update_email(request.user,
                                  get_ip(request),
                                  new_domain.name,
                                  is_new_user=is_new_user)

    send_hubspot_form(HUBSPOT_CREATED_NEW_PROJECT_SPACE_FORM_ID, request)
    return new_domain.name
示例#49
0
def request_new_domain(request, form, is_new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    dom_req = RegistrationRequest()
    if is_new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    name = name_to_url(form.cleaned_data['hr_name'], "project")
    with CriticalSection(['request_domain_name_{}'.format(name)]):
        name = Domain.generate_name(name)
        new_domain = Domain(
            name=name,
            hr_name=form.cleaned_data['hr_name'],
            is_active=False,
            date_created=datetime.utcnow(),
            creating_user=current_user.username,
            secure_submissions=True,
        )

        if form.cleaned_data.get('domain_timezone'):
            new_domain.default_timezone = form.cleaned_data['domain_timezone']

        if not is_new_user:
            new_domain.is_active = True

        force_sql_backed = getattr(settings, 'NEW_DOMAINS_USE_SQL_BACKEND', False)
        if force_sql_backed or current_user.is_superuser and form.cleaned_data.get('use_new_backend') == ['yes']:
            enable_toggles_for_scale_beta(new_domain.name)

        # ensure no duplicate domain documents get created on cloudant
        new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save()  # we need to get the name from the _id

    if is_new_user:
        # Only new-user domains are eligible for Advanced trial
        # domains with no subscription are equivalent to be on free Community plan
        create_30_day_advanced_trial(new_domain)

    UserRole.init_domain_with_presets(new_domain.name)

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if is_new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid,
                                       request.user.get_full_name())
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=is_new_user)

    meta = get_meta(request)
    track_created_new_project_space_on_hubspot.delay(current_user, request.COOKIES, meta)
    return new_domain.name
示例#50
0
def get_submit_ip(request):
    return get_ip(request)
示例#51
0
def request_new_domain(request, form, is_new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user, strict=True)

    dom_req = RegistrationRequest()
    if is_new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    project_name = form.cleaned_data.get('hr_name') or form.cleaned_data.get('project_name')
    name = name_to_url(project_name, "project")
    with CriticalSection(['request_domain_name_{}'.format(name)]):
        name = Domain.generate_name(name)
        new_domain = Domain(
            name=name,
            hr_name=project_name,
            is_active=False,
            date_created=datetime.utcnow(),
            creating_user=current_user.username,
            secure_submissions=True,
            use_sql_backend=True,
            first_domain_for_user=is_new_user
        )

        # Avoid projects created by dimagi.com staff members as self started
        new_domain.internal.self_started = not current_user.is_dimagi

        if form.cleaned_data.get('domain_timezone'):
            new_domain.default_timezone = form.cleaned_data['domain_timezone']

        if not is_new_user:
            new_domain.is_active = True

        # ensure no duplicate domain documents get created on cloudant
        new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save()  # we need to get the name from the _id

    if is_new_user:
        # Only new-user domains are eligible for Advanced trial
        # domains with no subscription are equivalent to be on free Community plan
        create_30_day_advanced_trial(new_domain, current_user.username)
    else:
        ensure_explicit_community_subscription(
            new_domain.name, date.today(), SubscriptionAdjustmentMethod.USER,
            web_user=current_user.username,
        )

    UserRole.init_domain_with_presets(new_domain.name)

    # add user's email as contact email for billing account for the domain
    account = BillingAccount.get_account_by_domain(new_domain.name)
    billing_contact, _ = BillingContactInfo.objects.get_or_create(account=account)
    billing_contact.email_list = [current_user.email]
    billing_contact.save()

    dom_req.domain = new_domain.name

    if request.user.is_authenticated:
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if is_new_user:
        dom_req.save()
        if settings.IS_SAAS_ENVIRONMENT:
            from corehq.apps.app_manager.tasks import load_appcues_template_app
            chain(
                load_appcues_template_app.si(new_domain.name, current_user.username, HEALTH_APP),
                load_appcues_template_app.si(new_domain.name, current_user.username, AGG_APP),
                load_appcues_template_app.si(new_domain.name, current_user.username, WASH_APP),
                send_domain_registration_email.si(
                    request.user.email,
                    dom_req.domain,
                    dom_req.activation_guid,
                    request.user.get_full_name(),
                    request.user.first_name
                )
            ).apply_async()
        else:
            send_domain_registration_email(request.user.email,
                                           dom_req.domain,
                                           dom_req.activation_guid,
                                           request.user.get_full_name(),
                                           request.user.first_name)
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=is_new_user)

    send_hubspot_form(HUBSPOT_CREATED_NEW_PROJECT_SPACE_FORM_ID, request)
    return new_domain.name
示例#52
0
def confirm_domain(request, guid=None):
    # Did we get a guid?
    vals = {}
    if guid is None:
        vals["message_title"] = _("Missing Activation Key")
        vals["message_subtitle"] = _("Account Activation Failed")
        vals["message_body"] = _(
            "An account activation key was not provided.  If you think this "
            "is an error, please contact the system administrator."
        )
        vals["is_error"] = True
        return render(request, "registration/confirmation_complete.html", vals)

    # Does guid exist in the system?
    req = RegistrationRequest.get_by_guid(guid)
    if not req:
        vals["message_title"] = _("Invalid Activation Key")
        vals["message_subtitle"] = _("Account Activation Failed")
        vals["message_body"] = (
            _(
                'The account activation key "%s" provided is invalid. If you '
                "think this is an error, please contact the system "
                "administrator."
            )
            % guid
        )
        vals["is_error"] = True
        return render(request, "registration/confirmation_complete.html", vals)

    requested_domain = Domain.get_by_name(req.domain)
    context = get_domain_context(requested_domain.domain_type)
    context["requested_domain"] = req.domain

    # Has guid already been confirmed?
    if requested_domain.is_active:
        assert req.confirm_time is not None and req.confirm_ip is not None
        context["message_title"] = _("Already Activated")
        context["message_body"] = (
            _("Your account %s has already been activated. No further " "validation is required.")
            % req.new_user_username
        )
        context["is_error"] = False
        return render(request, "registration/confirmation_complete.html", context)

    # Set confirm time and IP; activate domain and new user who is in the
    req.confirm_time = datetime.utcnow()
    req.confirm_ip = get_ip(request)
    req.save()
    requested_domain.is_active = True
    requested_domain.save()
    requesting_user = WebUser.get_by_username(req.new_user_username)

    send_new_request_update_email(requesting_user, get_ip(request), requested_domain.name, is_confirming=True)

    context["message_title"] = _("Account Confirmed")
    context["message_subtitle"] = _("Thank you for activating your account, %s!") % requesting_user.first_name
    context["message_body"] = (
        _(
            "Your account has been successfully activated.  Thank you for taking "
            "the time to confirm your email address: %s."
        )
        % requesting_user.username
    )
    context["is_error"] = False
    return render(request, "registration/confirmation_complete.html", context)
示例#53
0
def request_new_domain(request, form, org, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    commtrack_enabled = domain_type == 'commtrack'

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(
        name=form.cleaned_data['domain_name'],
        is_active=False,
        date_created=datetime.utcnow(),
        commtrack_enabled=commtrack_enabled,
        creating_user=current_user.username,
        secure_submissions=True,
    )

    if form.cleaned_data.get('domain_timezone'):
        new_domain.default_timezone = form.cleaned_data['domain_timezone']

    if org:
        new_domain.organization = org
        new_domain.hr_name = request.POST.get('domain_hrname', None) or new_domain.name

    if not new_user:
        new_domain.is_active = True

    # ensure no duplicate domain documents get created on cloudant
    new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save() # we need to get the name from the _id

    # Create a 30 Day Trial subscription to the Advanced Plan
    advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain(
        new_domain, edition=SoftwarePlanEdition.ADVANCED, is_trial=True
    )
    expiration_date = date.today() + timedelta(days=30)
    trial_account = BillingAccount.objects.get_or_create(
        name="Trial Account for %s" % new_domain.name,
        currency=Currency.get_default(),
        created_by_domain=new_domain.name,
        account_type=BillingAccountType.TRIAL,
    )[0]
    trial_subscription = Subscription.new_domain_subscription(
        trial_account, new_domain.name, advanced_plan_version,
        date_end=expiration_date,
        adjustment_method=SubscriptionAdjustmentMethod.TRIAL,
        is_trial=True,
    )
    trial_subscription.is_active = True
    trial_subscription.save()

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
示例#54
0
def confirm_domain(request, guid=''):
    with CriticalSection(['confirm_domain_' + guid]):
        error = None
        # Did we get a guid?
        if not guid:
            error = _('An account activation key was not provided.  If you think this '
                      'is an error, please contact the system administrator.')

        # Does guid exist in the system?
        else:
            req = RegistrationRequest.get_by_guid(guid)
            if not req:
                error = _('The account activation key "%s" provided is invalid. If you '
                          'think this is an error, please contact the system '
                          'administrator.') % guid

        if error is not None:
            context = {
                'message_body': error,
                'current_page': {'page_name': 'Account Not Activated'},
            }
            return render(request, 'registration/confirmation_error.html', context)

        requested_domain = Domain.get_by_name(req.domain)
        view_name = "dashboard_default"
        view_args = [requested_domain.name]
        if not domain_has_apps(req.domain):
            if False and settings.IS_SAAS_ENVIRONMENT and domain_is_on_trial(req.domain):
                view_name = "app_from_template"
                view_args.append("appcues")
            else:
                view_name = "default_new_app"

        # Has guid already been confirmed?
        if requested_domain.is_active:
            assert(req.confirm_time is not None and req.confirm_ip is not None)
            messages.success(request, 'Your account %s has already been activated. '
                'No further validation is required.' % req.new_user_username)
            return HttpResponseRedirect(reverse(view_name, args=view_args))

        # Set confirm time and IP; activate domain and new user who is in the
        req.confirm_time = datetime.utcnow()
        req.confirm_ip = get_ip(request)
        req.save()
        requested_domain.is_active = True
        requested_domain.save()
        requesting_user = WebUser.get_by_username(req.new_user_username)

        send_new_request_update_email(requesting_user, get_ip(request), requested_domain.name, is_confirming=True)

        messages.success(request,
                'Your account has been successfully activated.  Thank you for taking '
                'the time to confirm your email address: %s.'
            % (requesting_user.username))
        track_workflow(requesting_user.email, "Confirmed new project")
        track_confirmed_account_on_hubspot_v2.delay(requesting_user)
        request.session['CONFIRM'] = True

        if settings.IS_SAAS_ENVIRONMENT:
            # For AppCues v3, land new user in Web Apps
            view_name = get_cloudcare_urlname(requested_domain.name)
        return HttpResponseRedirect(reverse(view_name, args=view_args))