def handle(self, *args, **options): django_requests = OldRegistrationRequest.objects.all() print "Migrating RegistrationRequest Model from django to couch" for request in django_requests: existing_request = None try: existing_request = RegistrationRequest.get_by_guid( request.activation_guid) except Exception: pass try: if not existing_request: new_req = RegistrationRequest( tos_confirmed=request.tos_confirmed, request_time=request.request_time, request_ip=request.request_ip, activation_guid=request.activation_guid, confirm_time=request.confirm_time, confirm_ip=request.confirm_ip, domain=request.domain.name, new_user_username=request.new_user.username, requesting_user_username=request.requesting_user. username) new_req.save() except Exception as e: print "There was an error migrating a registration request with guid %s." % request.activation_guid print "Error: %s" % e
def handle(self, *args, **options): django_requests = OldRegistrationRequest.objects.all() print "Migrating RegistrationRequest Model from django to couch" for request in django_requests: existing_request = None try: existing_request = RegistrationRequest.get_by_guid(request.activation_guid) except Exception: pass try: if not existing_request: new_req = RegistrationRequest(tos_confirmed=request.tos_confirmed, request_time=request.request_time, request_ip=request.request_ip, activation_guid=request.activation_guid, confirm_time=request.confirm_time, confirm_ip=request.confirm_ip, domain=request.domain.name, new_user_username=request.new_user.username, requesting_user_username=request.requesting_user.username) new_req.save() except Exception as e: print "There was an error migrating a registration request with guid %s." % request.activation_guid print "Error: %s" % e
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)
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)
def request_new_domain(request, form, org, new_user=True): now = datetime.utcnow() dom_req = RegistrationRequest() if new_user: dom_req.tos_confirmed = form.cleaned_data['tos_confirmed'] dom_req.request_time = now dom_req.request_ip = get_ip(request) dom_req.activation_guid = uuid.uuid1().hex if org: new_domain = Domain(slug=form.cleaned_data['domain_name'], is_active=False, date_created=datetime.utcnow(), organization=org) else: new_domain = Domain(name=form.cleaned_data['domain_name'], is_active=False, date_created=datetime.utcnow()) 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(): current_user = CouchUser.from_django_user(request.user) 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)
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') _render = partial( render_registration_view, domain_type='commtrack' if dom_req.project.commtrack_enabled else None) if request.method == 'POST': try: send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid) except Exception: vals = {'error_msg':'There was a problem with your request', 'error_details':sys.exc_info(), 'show_homepage_link': 1 } return _render(request, 'error.html', vals) else: vals = dict(alert_message="An email has been sent to %s." % dom_req.new_user_username, requested_domain=dom_req.domain) return _render(request, 'registration/confirmation_sent.html', vals) return _render(request, 'registration/confirmation_resend.html', { 'requested_domain': dom_req.domain })
def activation_24hr_reminder_email(): """ Reminds inactive users registered 24 hrs ago to activate their account. """ request_reminders = RegistrationRequest.get_requests_24hrs_ago() DNS_name = get_site_domain() for request in request_reminders: user = WebUser.get_by_username(request.new_user_username) registration_link = 'http://' + DNS_name + reverse( 'registration_confirm_domain') + request.activation_guid + '/' email_context = { "domain": request.domain, "registration_link": registration_link, "full_name": user.full_name, "first_name": user.first_name, 'url_prefix': '' if settings.STATIC_CDN else 'http://' + DNS_name, } message_plaintext = render_to_string( 'registration/email/confirm_account_reminder.txt', email_context) message_html = render_to_string( 'registration/email/confirm_account.html', email_context) subject = ugettext('Reminder to Activate your CommCare project') send_html_email_async.delay( subject, request.new_user_username, message_html, text_content=message_plaintext, email_from=settings.DEFAULT_FROM_EMAIL )
def activation_24hr_reminder_email(): """ Reminds inactive users registered 24 hrs ago to activate their account. """ request_reminders = RegistrationRequest.get_requests_24hrs_ago() DNS_name = get_site_domain() for request in request_reminders: user = WebUser.get_by_username(request.new_user_username) registration_link = 'http://' + DNS_name + reverse( 'registration_confirm_domain') + request.activation_guid + '/' email_context = { "domain": request.domain, "registration_link": registration_link, "full_name": user.full_name, "first_name": user.first_name, 'url_prefix': '' if settings.STATIC_CDN else 'http://' + DNS_name, } message_plaintext = render_to_string( 'registration/email/confirm_account_reminder.txt', email_context) message_html = render_to_string( 'registration/email/confirm_account.html', email_context) subject = ugettext('Reminder to Activate your CommCare project') send_html_email_async.delay(subject, request.new_user_username, message_html, text_content=message_plaintext, email_from=settings.DEFAULT_FROM_EMAIL)
def resend_confirmation(request): dom_req = None try: dom_req = RegistrationRequest.get_request_for_username(request.user.username) except Exception: pass 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') if request.method == 'POST': # If the form has been submitted... try: send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid) except Exception: vals = {'error_msg':'There was a problem with your request', 'error_details':sys.exc_info(), 'show_homepage_link': 1 } return render_to_response(request, 'error.html', vals) else: vals = dict(alert_message="An email has been sent to %s." % dom_req.new_user_username, requested_domain=dom_req.domain) return render_to_response(request, 'registration/confirmation_sent.html', vals) vals = dict(requested_domain=dom_req.domain) return render_to_response(request, 'registration/confirmation_resend.html', vals)
def register_domain(request, domain_type=None): domain_type = domain_type or 'commcare' assert domain_type in DOMAIN_TYPES _render = partial(render_registration_view, domain_type=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: vals = dict(requested_domain=domains_for_user[0]) return _render(request, 'registration/confirmation_waiting.html', { 'requested_domain': domains_for_user[0] }) 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: vals = {'error_msg':'Number of domains requested today exceeds limit ('+str(max_req)+') - contact Dimagi', 'show_homepage_link': 1 } return _render(request, 'error.html', vals) request_new_domain( request, form, org, new_user=is_new, domain_type=domain_type) requested_domain = form.cleaned_data['domain_name'] if is_new: vals = dict(alert_message="An email has been sent to %s." % request.user.username, requested_domain=requested_domain) return _render(request, 'registration/confirmation_sent.html', vals) else: messages.success(request, '<strong>The project {project_name} was successfully created!</strong> An email has been sent to {username} for your records.'.format( username=request.user.username, project_name=requested_domain ), 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: # messages.error(request, "The new project could not be created! Please make sure to fill out all fields of the form.") return orgs_landing(request, org, form=form) else: form = DomainRegistrationForm(initial={'domain_type': domain_type}) return _render(request, 'registration/domain_request.html', { 'form': form, 'is_new': is_new, })
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]))
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)
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)
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() if request.method == 'POST': try: 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'), 'error_details': sys.exc_info(), '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': _('Resend Confirmation Email') }, }) return render(request, 'registration/confirmation_resend.html', context)
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)
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]))
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)
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]))
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(dom_req.project.domain_type) if request.method == 'POST': try: send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid) except Exception: context.update({ 'error_msg': _('There was a problem with your request'), 'error_details': sys.exc_info(), 'show_homepage_link': 1, }) return render(request, 'error.html', context) else: context.update({ 'alert_message': _("An email has been sent to %s.") % dom_req.new_user_username, 'requested_domain': dom_req.domain }) return render(request, 'registration/confirmation_sent.html', context) context.update({'requested_domain': dom_req.domain}) return render(request, 'registration/confirmation_resend.html', context)
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)
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() if request.method == 'POST': try: 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'), 'error_details': sys.exc_info(), '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': _('Resend Confirmation Email')}, }) return render(request, 'registration/confirmation_resend.html', context)
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(dom_req.project.domain_type) if request.method == 'POST': try: send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid, request.user.get_full_name()) except Exception: context.update({ 'error_msg': _('There was a problem with your request'), 'error_details': sys.exc_info(), 'show_homepage_link': 1, }) return render(request, 'error.html', context) else: context.update({ 'alert_message': _( "An email has been sent to %s.") % dom_req.new_user_username, 'requested_domain': dom_req.domain }) return render(request, 'registration/confirmation_sent.html', context) context.update({ 'requested_domain': dom_req.domain }) return render(request, 'registration/confirmation_resend.html', context)
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(dom_req.project.domain_type) if request.method == "POST": try: send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid) except Exception: context.update( { "error_msg": _("There was a problem with your request"), "error_details": sys.exc_info(), "show_homepage_link": 1, } ) return render(request, "error.html", context) else: context.update( { "alert_message": _("An email has been sent to %s.") % dom_req.new_user_username, "requested_domain": dom_req.domain, } ) return render(request, "registration/confirmation_sent.html", context) context.update({"requested_domain": dom_req.domain}) return render(request, "registration/confirmation_resend.html", context)
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)
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)
def request_new_domain(request, form, org, 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 = form.cleaned_data['hr_name'] 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 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 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) 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) return new_domain.name
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
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) # 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() 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
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)
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 with transaction.atomic(): 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: # 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
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)
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)
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
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
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
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))
def register_domain(request, domain_type=None): domain_type = domain_type or 'commcare' assert domain_type in DOMAIN_TYPES 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)
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
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))
def register_domain(request, domain_type=None): domain_type = domain_type or "commcare" assert domain_type in DOMAIN_TYPES 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)