コード例 #1
0
 def register_new_user(self, data):
     reg_form = RegisterWebUserForm(data['data'],
                                    show_number=self.ab_show_number)
     if reg_form.is_valid():
         self._create_new_account(reg_form)
         try:
             request_new_domain(self.request, reg_form, is_new_user=True)
         except NameUnavailableException:
             # technically, the form should never reach this as names are
             # auto-generated now. But, just in case...
             logging.error(
                 "There as an issue generating a unique domain name "
                 "for a user during new registration.")
             return {
                 'errors': {
                     'project name unavailable': [],
                 }
             }
         return {
             'success': True,
         }
     logging.error(
         "There was an error processing a new user registration form."
         "This shouldn't happen as validation should be top-notch "
         "client-side. Here is what the errors are: {}".format(
             reg_form.errors))
     return {
         'errors': reg_form.errors,
     }
コード例 #2
0
ファイル: views.py プロジェクト: dimagi/commcare-hq
 def register_new_user(self, data):
     reg_form = RegisterWebUserForm(data['data'])
     if reg_form.is_valid():
         ab_test = ab_tests.SessionAbTest(ab_tests.APPCUES_V3_APP, self.request)
         appcues_ab_test = ab_test.context['version']
         self._create_new_account(reg_form, additional_hubspot_data={
             "appcues_test": appcues_ab_test,
         })
         try:
             request_new_domain(
                 self.request, reg_form, is_new_user=True
             )
         except NameUnavailableException:
             # technically, the form should never reach this as names are
             # auto-generated now. But, just in case...
             logging.error("There as an issue generating a unique domain name "
                           "for a user during new registration.")
             return {
                 'errors': {
                     'project name unavailable': [],
                 }
             }
         return {
             'success': True,
             'appcues_ab_test': appcues_ab_test
         }
     logging.error(
         "There was an error processing a new user registration form."
         "This shouldn't happen as validation should be top-notch "
         "client-side. Here is what the errors are: {}".format(reg_form.errors))
     return {
         'errors': reg_form.errors,
     }
コード例 #3
0
 def register_new_user(self, data):
     reg_form = RegisterWebUserForm(data['data'])
     if reg_form.is_valid():
         ab_test = ab_tests.SessionAbTest(ab_tests.APPCUES_V3_APP, self.request)
         appcues_ab_test = ab_test.context['version']
         self._create_new_account(reg_form, additional_hubspot_data={
             "appcues_test": appcues_ab_test,
         })
         try:
             request_new_domain(
                 self.request, reg_form, is_new_user=True
             )
         except NameUnavailableException:
             # technically, the form should never reach this as names are
             # auto-generated now. But, just in case...
             logging.error("There as an issue generating a unique domain name "
                           "for a user during new registration.")
             return {
                 'errors': {
                     'project name unavailable': [],
                 }
             }
         return {
             'success': True,
             'appcues_ab_test': appcues_ab_test
         }
     logging.error(
         "There was an error processing a new user registration form."
         "This shouldn't happen as validation should be top-notch "
         "client-side. Here is what the errors are: {}".format(reg_form.errors))
     return {
         'errors': reg_form.errors,
     }
コード例 #4
0
ファイル: views.py プロジェクト: soitun/commcare-hq
    def register_new_user(self, data):
        idp = None
        if settings.ENFORCE_SSO_LOGIN:
            idp = IdentityProvider.get_required_identity_provider(
                data['data']['email'])

        reg_form = RegisterWebUserForm(data['data'], is_sso=idp is not None)
        if reg_form.is_valid():
            ab_test = ab_tests.SessionAbTest(ab_tests.APPCUES_V3_APP,
                                             self.request)
            appcues_ab_test = ab_test.context['version']

            if idp:
                signup_request = AsyncSignupRequest.create_from_registration_form(
                    reg_form,
                    additional_hubspot_data={
                        "appcues_test": appcues_ab_test,
                    })
                return {
                    'success': True,
                    'appcues_ab_test': appcues_ab_test,
                    'ssoLoginUrl': idp.get_login_url(signup_request.username),
                    'ssoIdpName': idp.name,
                }

            self._create_new_account(reg_form,
                                     additional_hubspot_data={
                                         "appcues_test": appcues_ab_test,
                                     })
            try:
                request_new_domain(self.request,
                                   reg_form.cleaned_data['project_name'],
                                   is_new_user=True)
            except NameUnavailableException:
                # technically, the form should never reach this as names are
                # auto-generated now. But, just in case...
                logging.error(
                    "There as an issue generating a unique domain name "
                    "for a user during new registration.")
                return {
                    'errors': {
                        'project name unavailable': [],
                    }
                }
            return {
                'success': True,
                'appcues_ab_test': appcues_ab_test,
            }
        logging.error(
            "There was an error processing a new user registration form."
            "This shouldn't happen as validation should be top-notch "
            "client-side. Here is what the errors are: {}".format(
                reg_form.errors))
        return {
            'errors': reg_form.errors,
        }
コード例 #5
0
ファイル: views.py プロジェクト: bderenzi/commcare-hq
    def register_new_user(self, data):
        reg_form = RegisterWebUserForm(
            data['data'],
            show_number=self.ab_show_number,
        )
        if reg_form.is_valid():
            self._create_new_account(reg_form)
            try:
                request_new_domain(self.request, reg_form, is_new_user=True)
            except NameUnavailableException:
                # technically, the form should never reach this as names are
                # auto-generated now. But, just in case...
                logging.error(
                    "There as an issue generating a unique domain name "
                    "for a user during new registration.")
                return {
                    'errors': {
                        'project name unavailable': [],
                    }
                }

            persona_fields = {}
            if reg_form.cleaned_data['persona']:
                persona_fields['buyer_persona'] = reg_form.cleaned_data[
                    'persona']
                if reg_form.cleaned_data['persona_other']:
                    persona_fields[
                        'buyer_persona_other'] = reg_form.cleaned_data[
                            'persona_other']
                couch_user = CouchUser.get_by_username(
                    reg_form.cleaned_data['email'])
                if couch_user:
                    update_hubspot_properties.delay(couch_user, persona_fields)

            return {
                'success':
                True,
                'is_mobile_experience':
                (reg_form.cleaned_data.get('is_mobile')
                 and toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST.enabled(
                     reg_form.cleaned_data['email'], toggles.NAMESPACE_USER))
            }
        logging.error(
            "There was an error processing a new user registration form."
            "This shouldn't happen as validation should be top-notch "
            "client-side. Here is what the errors are: {}".format(
                reg_form.errors))
        return {
            'errors': reg_form.errors,
        }
コード例 #6
0
ファイル: views.py プロジェクト: puttarajubr/commcare-hq
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)
コード例 #7
0
ファイル: views.py プロジェクト: saketkanth/commcare-hq
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)
コード例 #8
0
ファイル: views.py プロジェクト: mekete/commcare-hq
    def register_new_user(self, data):
        reg_form = RegisterWebUserForm(
            data['data'],
            show_number=self.ab_show_number,
        )
        if reg_form.is_valid():
            self._create_new_account(reg_form)
            try:
                request_new_domain(self.request, reg_form, is_new_user=True)
            except NameUnavailableException:
                # technically, the form should never reach this as names are
                # auto-generated now. But, just in case...
                logging.error(
                    "There as an issue generating a unique domain name "
                    "for a user during new registration.")
                return {
                    'errors': {
                        'project name unavailable': [],
                    }
                }

            username = reg_form.cleaned_data['email']
            appcues_ab_test = toggles.APPCUES_AB_TEST.enabled(
                username, toggles.NAMESPACE_USER)

            return {
                'success':
                True,
                'is_mobile_experience':
                (toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST_CONTROLLER.enabled(
                    username)
                 and toggles.MOBILE_SIGNUP_REDIRECT_AB_TEST.enabled(
                     username, toggles.NAMESPACE_USER)),
                'appcues_ab_test':
                appcues_ab_test,
            }
        logging.error(
            "There was an error processing a new user registration form."
            "This shouldn't happen as validation should be top-notch "
            "client-side. Here is what the errors are: {}".format(
                reg_form.errors))
        return {
            'errors': reg_form.errors,
        }
コード例 #9
0
    def post(self, request, *args, **kwargs):
        referer_url = request.GET.get('referer', '')
        nextpage = request.POST.get('next')
        form = DomainRegistrationForm(request.POST)
        context = self.get_context_data(form=form)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'current_page': {
                        'page_name': _('Oops!')
                    },
                    'error_msg':
                    _('Number of domains requested today exceeds limit (%d) - contact Dimagi'
                      ) % max_req,
                    'show_homepage_link':
                    1
                })
                return render(request, 'error.html', context)

            try:
                domain_name = request_new_domain(request,
                                                 form,
                                                 is_new_user=self.is_new_user)
            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)

            if self.is_new_user:
                context.update({
                    'requested_domain': domain_name,
                    'current_page': {
                        'page_name': _('Confirm Account')
                    },
                })
                track_workflow(self.request.user.email, "Created new project")
                return render(request, 'registration/confirmation_sent.html',
                              context)
            else:
                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(
                    reverse("domain_homepage", args=[domain_name]))

        return self.render_to_response(context)
コード例 #10
0
ファイル: test_utils.py プロジェクト: soitun/commcare-hq
 def test_domain_is_not_active_for_new_user(self):
     """
     Ensure that the first domain created by a new user is not active.
     """
     domain_name = request_new_domain(
         self.request,
         'test-sso-2',
         is_new_user=True,
     )
     domain = Domain.get_by_name(domain_name)
     self.assertFalse(domain.is_active)
コード例 #11
0
ファイル: views.py プロジェクト: dimagi/commcare-hq
    def post(self, request, *args, **kwargs):
        referer_url = request.GET.get('referer', '')
        nextpage = request.POST.get('next')
        form = DomainRegistrationForm(request.POST)
        context = self.get_context_data(form=form)
        if not form.is_valid():
            return self.render_to_response(context)

        if settings.RESTRICT_DOMAIN_CREATION and not request.user.is_superuser:
            context.update({
                'current_page': {'page_name': _('Oops!')},
                'error_msg': _('Your organization has requested that project creation be restricted. '
                               'For more information, please speak to your administrator.'),
            })
            return render(request, 'error.html', context)

        reqs_today = RegistrationRequest.get_requests_today()
        max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
        if reqs_today >= max_req:
            context.update({
                'current_page': {'page_name': _('Oops!')},
                'error_msg': _(
                    'Number of projects requested today exceeds limit (%d) - contact Dimagi'
                ) % max_req,
                'show_homepage_link': 1
            })
            return render(request, 'error.html', context)

        try:
            domain_name = request_new_domain(request, form, is_new_user=self.is_new_user)
        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)

        if self.is_new_user:
            context.update({
                'requested_domain': domain_name,
                'current_page': {'page_name': _('Confirm Account')},
            })
            track_workflow(self.request.user.email, "Created new project")
            return render(request, 'registration/confirmation_sent.html', context)

        if nextpage:
            return HttpResponseRedirect(nextpage)
        if referer_url:
            return redirect(referer_url)
        return HttpResponseRedirect(reverse("domain_homepage", args=[domain_name]))
コード例 #12
0
 def register_new_user(self, data):
     reg_form = RegisterWebUserForm(
         data['data'],
         show_number=(
             self.ab.version == ab_tests.NEW_USER_NUMBER_OPTION_SHOW_NUM))
     if reg_form.is_valid():
         self._create_new_account(reg_form)
         try:
             requested_domain = request_new_domain(self.request,
                                                   reg_form,
                                                   is_new_user=True)
             # If user created a form via prelogin demo, create an app for them
             if reg_form.cleaned_data['xform']:
                 lang = 'en'
                 app = Application.new_app(requested_domain,
                                           "Untitled Application")
                 module = Module.new_module(_("Untitled Module"), lang)
                 app.add_module(module)
                 save_xform(app, app.new_form(0, "Untitled Form", lang),
                            reg_form.cleaned_data['xform'])
                 app.save()
                 web_user = WebUser.get_by_username(
                     reg_form.cleaned_data['email'])
                 if web_user:
                     update_hubspot_properties(web_user, {
                         'signup_via_demo': 'yes',
                     })
         except NameUnavailableException:
             # technically, the form should never reach this as names are
             # auto-generated now. But, just in case...
             logging.error(
                 "There as an issue generating a unique domain name "
                 "for a user during new registration.")
             return {
                 'errors': {
                     'project name unavailable': [],
                 }
             }
         return {
             'success': True,
         }
     logging.error(
         "There was an error processing a new user registration form."
         "This shouldn't happen as validation should be top-notch "
         "client-side. Here is what the errors are: {}".format(
             reg_form.errors))
     return {
         'errors': reg_form.errors,
     }
コード例 #13
0
ファイル: views.py プロジェクト: saketkanth/commcare-hq
    def post(self, request, *args, **kwargs):
        referer_url = request.GET.get('referer', '')
        nextpage = request.POST.get('next')
        form = DomainRegistrationForm(request.POST, current_user=request.couch_user)
        context = self.get_context_data(form=form)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'current_page': {'page_name': _('Oops!')},
                    'error_msg': _(
                        'Number of domains requested today exceeds limit (%d) - contact Dimagi'
                    ) % max_req,
                    'show_homepage_link': 1
                })
                return render(request, 'error.html', context)

            try:
                domain_name = request_new_domain(
                    request, form, is_new_user=self.is_new_user)
            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)

            if self.is_new_user:
                context.update({
                    'requested_domain': domain_name,
                    'track_domain_registration': True,
                    'current_page': {'page_name': _('Confirm Account')},
                })
                return render(request, 'registration/confirmation_sent.html', context)
            else:
                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(reverse("domain_homepage", args=[domain_name]))

        return self.render_to_response(context)
コード例 #14
0
 def register_new_user(self, data):
     reg_form = RegisterWebUserForm(data['data'])
     if reg_form.is_valid():
         self._create_new_account(reg_form)
         try:
             requested_domain = request_new_domain(
                 self.request, reg_form, is_new_user=True
             )
             # If user created a form via prelogin demo, create an app for them
             if reg_form.cleaned_data['xform']:
                 lang = 'en'
                 app = Application.new_app(requested_domain, "Untitled Application")
                 module = Module.new_module(_("Untitled Module"), lang)
                 app.add_module(module)
                 save_xform(app, app.new_form(0, "Untitled Form", lang), reg_form.cleaned_data['xform'])
                 app.save()
                 web_user = WebUser.get_by_username(reg_form.cleaned_data['email'])
                 if web_user:
                     update_hubspot_properties(web_user, {
                         'signup_via_demo': 'yes',
                     })
         except NameUnavailableException:
             # technically, the form should never reach this as names are
             # auto-generated now. But, just in case...
             logging.error("There as an issue generating a unique domain name "
                           "for a user during new registration.")
             return {
                 'errors': {
                     'project name unavailable': [],
                 }
             }
         return {
             'success': True,
         }
     logging.error(
         "There was an error processing a new user registration form."
         "This shouldn't happen as validation should be top-notch "
         "client-side. Here is what the errors are: {}".format(reg_form.errors))
     return {
         'errors': reg_form.errors,
     }
コード例 #15
0
def sso_saml_acs(request, idp_slug):
    """
    ACS stands for "Assertion Consumer Service". The Identity Provider will send
    its response to this view after authenticating a user. This is often
    referred to as the "Entity ID" in the IdP's Service Provider configuration.

    In this view we verify the received SAML 2.0 response and then log in the user
    to CommCare HQ.
    """
    # todo these are placeholders for the json dump below
    error_reason = None
    request_session_data = None
    saml_relay = None

    request_id = request.session.get('AuthNRequestID')
    processed_response = request.saml2_auth.process_response(
        request_id=request_id)
    errors = request.saml2_auth.get_errors()
    not_auth_warn = not request.saml2_auth.is_authenticated()

    if not errors:
        if 'AuthNRequestID' in request.session:
            del request.session['AuthNRequestID']

        store_saml_data_in_session(request)

        user = auth.authenticate(
            request=request,
            username=request.session['samlNameId'],
            idp_slug=idp_slug,
            is_handshake_successful=True,
        )

        # we add the messages to the django messages framework here since
        # that middleware was not available for SsoBackend
        if hasattr(request, 'sso_new_user_messages'):
            for success_message in request.sso_new_user_messages['success']:
                messages.success(request, success_message)
            for error_message in request.sso_new_user_messages['error']:
                messages.error(request, error_message)

        if user:
            auth.login(request, user)

            # activate new project if needed
            project_name = get_new_sso_user_project_name_from_session(request)
            if project_name:
                try:
                    request_new_domain(request, project_name, is_new_user=True)
                except NameUnavailableException:
                    # this should never happen, but in the off chance it does
                    # we don't want to throw a 500 on this view
                    messages.error(
                        request,
                        _("We were unable to create your requested project "
                          "because the name was already taken."
                          "Please contact support."))

            clear_sso_registration_data_from_session(request)
            return redirect("homepage")

        # todo for debugging purposes to dump into the response below
        request_session_data = {
            "samlUserdata":
            request.session['samlUserdata'],
            "samlNameId":
            request.session['samlNameId'],
            "samlNameIdFormat":
            request.session['samlNameIdFormat'],
            "samlNameIdNameQualifier":
            request.session['samlNameIdNameQualifier'],
            "samlNameIdSPNameQualifier":
            request.session['samlNameIdSPNameQualifier'],
            "samlSessionIndex":
            request.session['samlSessionIndex'],
        }

    else:
        error_reason = request.saml2_auth.get_last_error_reason()

    return HttpResponse(
        json.dumps({
            "errors": errors,
            "error_reason": error_reason,
            "not_auth_warn": not_auth_warn,
            "request_id": request_id,
            "processed_response": processed_response,
            "saml_relay": saml_relay,
            "request_session_data": request_session_data,
            "login_error": getattr(request, 'sso_login_error', None),
        }), 'text/json')
コード例 #16
0
ファイル: views.py プロジェクト: atinus/commcare-hq
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES or request.couch_user.is_commcare_user():
        raise Http404()

    context = get_domain_context(domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(domains_for_user) > 0:
            context['requested_domain'] = domains_for_user[0]
            return render(request, 'registration/confirmation_waiting.html',
                    context)

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'error_msg': _(
                        'Number of domains requested today exceeds limit (%d) - contact Dimagi'
                    ) % max_req,
                    'show_homepage_link': 1
                })
                return render(request, 'error.html', context)

            request_new_domain(
                request, form, org, new_user=is_new, domain_type=domain_type)

            requested_domain = form.cleaned_data['domain_name']
            if is_new:
                context.update({
                    'alert_message': _("An email has been sent to %s.") % request.user.username,
                    'requested_domain': requested_domain
                })
                return render(request, 'registration/confirmation_sent.html',
                        context)
            else:
                messages.success(request, _(
                    '<strong>The project {project} was successfully created!</strong> '
                    'An email has been sent to {user} for your records.').format(
                    project=requested_domain, user=request.user.username),
                    extra_tags="html")

                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(reverse("domain_homepage", args=[requested_domain]))
        else:
            if nextpage:
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    context.update({
        'form': form,
        'is_new': is_new,
    })
    return render(request, 'registration/domain_request.html', context)
コード例 #17
0
ファイル: views.py プロジェクト: johan--/commcare-hq
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES or (not request.couch_user) or request.couch_user.is_commcare_user():
        raise Http404()

    context = get_domain_context(domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(domains_for_user) > 0:
            context['requested_domain'] = domains_for_user[0]
            return render(request, 'registration/confirmation_waiting.html',
                    context)

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'error_msg': _(
                        'Number of domains requested today exceeds limit (%d) - contact Dimagi'
                    ) % max_req,
                    'show_homepage_link': 1
                })
                return render(request, 'error.html', context)

            try:
                domain_name = request_new_domain(
                    request, form, org, new_user=is_new, 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)

            if is_new:
                context.update({
                    'alert_message': _("An email has been sent to %s.") % request.user.username,
                    'requested_domain': domain_name,
                    'track_domain_registration': True,
                })
                return render(request, 'registration/confirmation_sent.html',
                        context)
            else:
                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(reverse("domain_homepage", args=[domain_name]))
        else:
            if nextpage:
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    context.update({
        'form': form,
        'is_new': is_new,
    })
    return render(request, 'registration/domain_request.html', context)
コード例 #18
0
ファイル: views.py プロジェクト: thedevelopermw/commcare-hq
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES or request.couch_user.is_commcare_user(
    ):
        raise Http404()

    context = get_domain_context(domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user,
                                                  is_active=False)
        if len(domains_for_user) > 0:
            context['requested_domain'] = domains_for_user[0]
            return render(request, 'registration/confirmation_waiting.html',
                          context)

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'error_msg':
                    _('Number of domains requested today exceeds limit (%d) - contact Dimagi'
                      ) % max_req,
                    'show_homepage_link':
                    1
                })
                return render(request, 'error.html', context)

            request_new_domain(request,
                               form,
                               org,
                               new_user=is_new,
                               domain_type=domain_type)

            requested_domain = form.cleaned_data['domain_name']
            if is_new:
                context.update({
                    'alert_message':
                    _("An email has been sent to %s.") % request.user.username,
                    'requested_domain':
                    requested_domain
                })
                return render(request, 'registration/confirmation_sent.html',
                              context)
            else:
                messages.success(
                    request,
                    _('<strong>The project {project} was successfully created!</strong> '
                      'An email has been sent to {user} for your records.'
                      ).format(project=requested_domain,
                               user=request.user.username),
                    extra_tags="html")

                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(
                    reverse("domain_homepage", args=[requested_domain]))
        else:
            if nextpage:
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    context.update({
        'form': form,
        'is_new': is_new,
    })
    return render(request, 'registration/domain_request.html', context)
コード例 #19
0
ファイル: saml.py プロジェクト: soitun/commcare-hq
def sso_saml_acs(request, idp_slug):
    """
    ACS stands for "Assertion Consumer Service". The Identity Provider will send
    its response to this view after authenticating a user. This is often
    referred to as the "Entity ID" in the IdP's Service Provider configuration.

    In this view we verify the received SAML 2.0 response and then log in the user
    to CommCare HQ.
    """
    request_id = request.session.get('AuthNRequestID')
    error_template = 'sso/acs_errors.html'

    try:
        request.saml2_auth.process_response(request_id=request_id)
        errors = request.saml2_auth.get_errors()
    except OneLogin_Saml2_Error as e:
        if e.code == OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND:
            return redirect("sso_saml_login", idp_slug=idp_slug)
        errors = [e]

    if errors:
        return render(
            request,
            error_template,
            {
                'saml_error_reason':
                request.saml2_auth.get_last_error_reason() or errors[0],
                'idp_type':
                "Azure AD",  # we will update this later,
                'docs_link':
                get_documentation_url(request.idp),
            })

    if not request.saml2_auth.is_authenticated():
        return render(request, 'sso/sso_request_denied.html', {})

    if 'AuthNRequestID' in request.session:
        del request.session['AuthNRequestID']

    store_saml_data_in_session(request)

    user = auth.authenticate(
        request=request,
        username=request.session['samlNameId'],
        idp_slug=idp_slug,
        is_handshake_successful=True,
    )

    # we add the messages to the django messages framework here since
    # that middleware was not available for SsoBackend
    if hasattr(request, 'sso_new_user_messages'):
        for success_message in request.sso_new_user_messages['success']:
            messages.success(request, success_message)
        for error_message in request.sso_new_user_messages['error']:
            messages.error(request, error_message)

    if user:
        auth.login(request, user)

        # activate new project if needed
        async_signup = AsyncSignupRequest.get_by_username(user.username)
        if async_signup and async_signup.project_name:
            try:
                request_new_domain(request,
                                   async_signup.project_name,
                                   is_new_user=True,
                                   is_new_sso_user=True)
            except NameUnavailableException:
                # this should never happen, but in the off chance it does
                # we don't want to throw a 500 on this view
                messages.error(
                    request,
                    _("We were unable to create your requested project "
                      "because the name was already taken."
                      "Please contact support."))

        AsyncSignupRequest.clear_data_for_username(user.username)

        relay_state = request.saml2_request_data['post_data'].get('RelayState')
        if relay_state not in [
                OneLogin_Saml2_Utils.get_self_url(request.saml2_request_data),
                get_saml_login_url(request.idp),
        ]:
            # redirect to next=<relay_state>
            return HttpResponseRedirect(
                request.saml2_auth.redirect_to(relay_state))

        return redirect("homepage")

    return render(request, error_template, {
        'login_error': getattr(request, 'sso_login_error', None),
    })
コード例 #20
0
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES or request.couch_user.is_commcare_user(
    ):
        raise Http404()

    context = get_domain_context(domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user,
                                                  is_active=False)
        if len(domains_for_user) > 0:
            context['requested_domain'] = domains_for_user[0]
            return render(request, 'registration/confirmation_waiting.html',
                          context)

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'error_msg':
                    _('Number of domains requested today exceeds limit (%d) - contact Dimagi'
                      ) % max_req,
                    'show_homepage_link':
                    1
                })
                return render(request, 'error.html', context)

            try:
                domain_name = request_new_domain(request,
                                                 form,
                                                 org,
                                                 new_user=is_new,
                                                 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)

            if is_new:
                context.update({
                    'alert_message':
                    _("An email has been sent to %s.") % request.user.username,
                    'requested_domain':
                    domain_name,
                    'track_domain_registration':
                    True,
                })
                return render(request, 'registration/confirmation_sent.html',
                              context)
            else:
                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(
                    reverse("domain_homepage", args=[domain_name]))
        else:
            if nextpage:
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    context.update({
        'form': form,
        'is_new': is_new,
    })
    return render(request, 'registration/domain_request.html', context)
コード例 #21
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)