def __call__(self, request, invitation_id, **kwargs): # add the correct parameters to this instance self.request = request for k, v in kwargs.iteritems(): if k in self.need: setattr(self, k, v) if request.GET.get('switch') == 'true': logout(request) return redirect_to_login(request.path) if request.GET.get('create') == 'true': logout(request) return HttpResponseRedirect(request.path) invitation = self.inv_type.get(invitation_id) if invitation.is_accepted: messages.error(request, "Sorry, that invitation has already been used up. " "If you feel this is a mistake please ask the inviter for " "another invitation.") return HttpResponseRedirect(reverse("login")) self.validate_invitation(invitation) if request.user.is_authenticated(): if request.couch_user.username != invitation.email: messages.error(request, "The invited user %s and your user %s do not match!" % (invitation.email, request.couch_user.username)) if request.method == "POST": couch_user = CouchUser.from_django_user(request.user) self._invite(invitation, couch_user) return HttpResponseRedirect(self.redirect_to_on_success) else: mobile_user = CouchUser.from_django_user(request.user).is_commcare_user() context = self.added_context() context.update({ 'mobile_user': mobile_user, "invited_user": invitation.email if request.couch_user.username != invitation.email else "", }) return render(request, self.template, context) else: if request.method == "POST": form = NewWebUserRegistrationForm(request.POST) if form.is_valid(): # create the new user user = activate_new_user(form) user.save() messages.success(request, "User account for %s created! You may now login." % form.cleaned_data["email"]) self._invite(invitation, user) return HttpResponseRedirect(reverse("login")) else: form = NewWebUserRegistrationForm(initial={'email': invitation.email}) return render(request, self.template, {"form": form})
def _ensure_request_couch_user(request): couch_user = getattr(request, 'couch_user', None) if not couch_user and hasattr(request, 'user'): request.couch_user = couch_user = CouchUser.from_django_user( request.user) elif couch_user and couch_user.is_anonymous and hasattr( request, 'user') and not request.user.is_anonymous: # if ANONYMOUS_WEB_APPS_USAGE toggle is enabled then `request.couch_user` get's set to the anonymous # mobile user in middleware which breaks this check if later authentication succeeds e.g. apikey request.couch_user = couch_user = CouchUser.from_django_user( request.user) return couch_user
def get(self, request, *args, **kwargs): couch_user = CouchUser.from_django_user(request.user) if couch_user.is_web_user(): data = {'domains': couch_user.domains} return JsonResponse(data) else: return HttpResponse('Only web users can access this endpoint', status=400)
def update_user(self, existing_user=None, save=True, **kwargs): is_update_successful = False if not existing_user and 'email' in self.cleaned_data: from django.contrib.auth.models import User django_user = User() django_user.username = self.cleaned_data['email'] django_user.save() existing_user = CouchUser.from_django_user(django_user) existing_user.save() is_update_successful = True if 'email' in self.cleaned_data: old_email = existing_user.email new_email = self.cleaned_data['email'] if old_email != new_email: handle_changed_mailchimp_email(existing_user, old_email, new_email) for prop in self.direct_properties: setattr(existing_user, prop, self.cleaned_data[prop]) is_update_successful = True if is_update_successful and save: existing_user.save() return is_update_successful
def get(self, request, *args, **kwargs): couch_user = CouchUser.from_django_user(request.user) if couch_user.is_web_user(): data = {'domains': couch_user.domains} return JsonResponse(data) else: return HttpResponse('Only web users can access this endpoint', status=400)
def update_user(self, existing_user=None, **kwargs): is_update_successful = False if not existing_user and 'email' in self.cleaned_data: from django.contrib.auth.models import User django_user = User() django_user.username = self.cleaned_data['email'] django_user.save() existing_user = CouchUser.from_django_user(django_user) existing_user.save() is_update_successful = True if 'email' in self.cleaned_data: old_email = existing_user.email new_email = self.cleaned_data['email'] if old_email != new_email: if existing_user.subscribed_to_commcare_users: handle_changed_mailchimp_email( existing_user, old_email, new_email, settings.MAILCHIMP_COMMCARE_USERS_ID) if not existing_user.email_opt_out: handle_changed_mailchimp_email( existing_user, old_email, new_email, settings.MAILCHIMP_MASS_EMAIL_ID) for prop in self.direct_properties: setattr(existing_user, prop, self.cleaned_data[prop]) is_update_successful = True if is_update_successful: existing_user.save() return is_update_successful
def save(self, commit=True): user = super(HQPasswordChangeForm, self).save(commit) couch_user = CouchUser.from_django_user(user) couch_user.last_password_set = datetime.utcnow() if commit: couch_user.save() return user
def post(self, request, *args, **kwargs): can_toggle_is_staff = request.user.is_staff form = SuperuserManagementForm(can_toggle_is_staff, self.request.POST) if form.is_valid(): users = form.cleaned_data['users'] is_superuser = '******' in form.cleaned_data['privileges'] is_staff = 'is_staff' in form.cleaned_data['privileges'] fields_changed = {} for user in users: # save user object only if needed and just once if user.is_superuser is not is_superuser: user.is_superuser = is_superuser fields_changed['is_superuser'] = is_superuser if can_toggle_is_staff and user.is_staff is not is_staff: user.is_staff = is_staff fields_changed['is_staff'] = is_staff if fields_changed: user.save() couch_user = CouchUser.from_django_user(user) log_user_change(by_domain=None, for_domain=None, couch_user=couch_user, changed_by_user=self.request.couch_user, changed_via=USER_CHANGE_VIA_WEB, fields_changed=fields_changed, by_domain_required_for_log=False, for_domain_required_for_log=False) messages.success(request, _("Successfully updated superuser permissions")) return self.get(request, *args, **kwargs)
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 update_user(self, existing_user=None, save=True, **kwargs): is_update_successful = False # From what I can tell, everything that invokes this method invokes it # with a value for existing_user. It also looks like the code below is # not behaving properly for mobile workers when existing_user is None. # If the soft asserts confirm this isn't ever being passed existing_user=None, # I propose making existing_user a required arg and removing the code below # that creates the user. _assert = soft_assert('@'.join(['gcapalbo', 'dimagi.com']), exponential_backoff=False) _assert(existing_user is not None, "existing_user is None") if not existing_user and 'email' in self.cleaned_data: from django.contrib.auth.models import User django_user = User() django_user.username = self.cleaned_data['email'] django_user.save() existing_user = CouchUser.from_django_user(django_user) existing_user.save() is_update_successful = True for prop in self.direct_properties: setattr(existing_user, prop, self.cleaned_data[prop]) is_update_successful = True if is_update_successful and save: existing_user.save() return is_update_successful
def save(self, commit=True): user = super(HQPasswordChangeForm, self).save(commit) couch_user = CouchUser.from_django_user(user) couch_user.last_password_set = datetime.utcnow() if commit: couch_user.save() return user
def testCreateCompleteWebUser(self): """ testing couch user internal functions """ username = "******" email = "*****@*****.**" password = "******" # create django user domain1 = create_domain('domain1') domain2 = create_domain('domain2') self.addCleanup(domain2.delete) self.addCleanup(domain1.delete) couch_user = WebUser.create(None, username, password, None, None, email=email) self.addCleanup(couch_user.delete, deleted_by=None) self.assertEqual(couch_user.username, username) self.assertEqual(couch_user.email, email) couch_user.add_domain_membership('domain1') self.assertEqual(couch_user.domain_memberships[0].domain, 'domain1') couch_user.add_domain_membership('domain2') self.assertEqual(couch_user.domain_memberships[1].domain, 'domain2') django_user = couch_user.get_django_user() self.assertEqual(couch_user.user_id, CouchUser.from_django_user(django_user).user_id)
def update_user(self, existing_user=None, save=True, **kwargs): is_update_successful = False # From what I can tell, everything that invokes this method invokes it # with a value for existing_user. It also looks like the code below is # not behaving properly for mobile workers when existing_user is None. # If the soft asserts confirm this isn't ever being passed existing_user=None, # I propose making existing_user a required arg and removing the code below # that creates the user. _assert = soft_assert('@'.join(['gcapalbo', 'dimagi.com']), exponential_backoff=False) _assert(existing_user is not None, "existing_user is None") if not existing_user and 'email' in self.cleaned_data: from django.contrib.auth.models import User django_user = User() django_user.username = self.cleaned_data['email'] django_user.save() existing_user = CouchUser.from_django_user(django_user) existing_user.save() is_update_successful = True for prop in self.direct_properties: setattr(existing_user, prop, self.cleaned_data[prop]) is_update_successful = True if is_update_successful and save: existing_user.save() return is_update_successful
def _inner(req, domain, *args, **kwargs): user = req.user domain_name, domain = load_domain(req, domain) if domain: if user.is_authenticated() and user.is_active: if not domain.is_active: return HttpResponseRedirect(reverse("domain_select")) if hasattr(req, "couch_user"): couch_user = req.couch_user # set by user middleware else: # some views might not have this set couch_user = CouchUser.from_django_user(user) if couch_user.is_member_of(domain) or domain.is_public: return view_func(req, domain_name, *args, **kwargs) elif user.is_superuser and not domain.restrict_superusers: # superusers can circumvent domain permissions. return view_func(req, domain_name, *args, **kwargs) elif domain.is_snapshot: # snapshots are publicly viewable return require_previewer(view_func)(req, domain_name, *args, **kwargs) else: raise Http404 else: login_url = reverse('login', kwargs={ 'domain_type': domain.domain_type }) return _redirect_for_login_or_domain(req, REDIRECT_FIELD_NAME, login_url) else: raise Http404
def _inner(req, domain, *args, **kwargs): user = req.user domain_name, domain = load_domain(req, domain) if domain: if user.is_authenticated() and user.is_active: if not domain.is_active: msg = _( ( 'The domain "{domain}" has been deactivated. ' "Please report an issue if you think this is a mistake." ).format(domain=domain_name) ) messages.info(req, msg) return HttpResponseRedirect(reverse("domain_select")) if hasattr(req, "couch_user"): couch_user = req.couch_user # set by user middleware else: # some views might not have this set couch_user = CouchUser.from_django_user(user) if couch_user.is_member_of(domain) or domain.is_public: return view_func(req, domain_name, *args, **kwargs) elif user.is_superuser and not domain.restrict_superusers: # superusers can circumvent domain permissions. return view_func(req, domain_name, *args, **kwargs) elif domain.is_snapshot: # snapshots are publicly viewable return require_previewer(view_func)(req, domain_name, *args, **kwargs) else: raise Http404 else: login_url = reverse("domain_login", kwargs={"domain": domain}) return _redirect_for_login_or_domain(req, REDIRECT_FIELD_NAME, login_url) else: raise Http404
def _runCreateUserFromRegistrationTest(self): """ test creating of couch user from a registration xmlns. this is more of an integration test than a unit test. """ couch_user, created = CommCareUser.create_or_update_from_xform( self.xform) self.assertEqual(couch_user.user_id, self.uuid) # czue: removed lxml reference #uuid = ET.fromstring(xml).findtext(".//{http://openrosa.org/user/registration}uuid") couch_user = CommCareUser.get_by_user_id(self.xform.form['uuid']) self.assertNotEqual(couch_user, None) self.assertEqual(couch_user.username, format_username(self.username, self.domain)) self.assertEqual(couch_user.domain, self.domain) self.assertEqual(couch_user.user_id, self.uuid) date = datetime.date(datetime.strptime(self.date_string, '%Y-%m-%d')) self.assertEqual(couch_user.created_on, force_to_datetime(date)) self.assertEqual(couch_user.device_ids[0], self.registering_device_id) django_user = couch_user.get_django_user() self.assertEqual(couch_user.user_id, CouchUser.from_django_user(django_user).user_id)
def _inner(req, domain, *args, **kwargs): user = req.user domain_name, domain = load_domain(req, domain) if domain: if user.is_authenticated() and user.is_active: if not domain.is_active: msg = _(( 'The domain "{domain}" has been deactivated. ' 'Please report an issue if you think this is a mistake.' ).format(domain=domain_name)) messages.info(req, msg) return HttpResponseRedirect(reverse("domain_select")) if hasattr(req, "couch_user"): couch_user = req.couch_user # set by user middleware else: # some views might not have this set couch_user = CouchUser.from_django_user(user) if couch_user.is_member_of(domain) or domain.is_public: return view_func(req, domain_name, *args, **kwargs) elif user.is_superuser and not domain.restrict_superusers: # superusers can circumvent domain permissions. return view_func(req, domain_name, *args, **kwargs) elif domain.is_snapshot: # snapshots are publicly viewable return require_previewer(view_func)(req, domain_name, *args, **kwargs) else: raise Http404 else: login_url = reverse('domain_login', kwargs={'domain': domain}) return _redirect_for_login_or_domain(req, REDIRECT_FIELD_NAME, login_url) else: msg = _(('The domain "{domain}" was not found.').format(domain=domain_name)) raise Http404(msg)
def form_valid(self, form): from django_otp import devices_for_user username = form.cleaned_data['username'] user = User.objects.get(username__iexact=username) for device in devices_for_user(user): device.delete() disable_for_days = form.cleaned_data['disable_for_days'] if disable_for_days: couch_user = CouchUser.from_django_user(user) disable_until = datetime.utcnow() + timedelta( days=disable_for_days) couch_user.two_factor_auth_disabled_until = disable_until couch_user.save() verification = form.cleaned_data['verification_mode'] verified_by = form.cleaned_data['via_who'] or self.request.user.username log_model_change( self.request.user, user, f'Two factor disabled. Verified by: {verified_by}, verification mode: "{verification}"' ) mail_admins( "Two-Factor account reset", "Two-Factor auth was reset. Details: \n" " Account reset: {username}\n" " Reset by: {reset_by}\n" " Request Verificatoin Mode: {verification}\n" " Verified by: {verified_by}\n" " Two-Factor disabled for {days} days.".format( username=username, reset_by=self.request.user.username, verification=verification, verified_by=verified_by, days=disable_for_days), ) send_HTML_email( "%sTwo-Factor authentication reset" % settings.EMAIL_SUBJECT_PREFIX, username, render_to_string( 'hqadmin/email/two_factor_reset_email.html', context={ 'until': disable_until.strftime('%Y-%m-%d %H:%M:%S UTC') if disable_for_days else None, 'support_email': settings.SUPPORT_EMAIL, 'email_subject': "[URGENT] Possible Account Breach", 'email_body': "Two Factor Auth on my CommCare account " "was disabled without my request. My username is: %s" % username, }), ) messages.success(self.request, _('Two-Factor Auth successfully disabled.')) return redirect('{}?q={}'.format(reverse('web_user_lookup'), username))
def _handle_user_form(request, domain, couch_user=None): context = {} if couch_user: create_user = False else: create_user = True can_change_admin_status = ( request.user.is_superuser or request.couch_user.can_edit_web_users(domain=domain) ) and request.couch_user.user_id != couch_user.user_id if couch_user.is_commcare_user(): role_choices = UserRole.commcareuser_role_choices(domain) else: role_choices = UserRole.role_choices(domain) if request.method == "POST" and request.POST["form_type"] == "basic-info": form = UserForm(request.POST, role_choices=role_choices) if form.is_valid(): if create_user: django_user = User() django_user.username = form.cleaned_data["email"] django_user.save() couch_user = CouchUser.from_django_user(django_user) couch_user.first_name = form.cleaned_data["first_name"] couch_user.last_name = form.cleaned_data["last_name"] couch_user.email = form.cleaned_data["email"] couch_user.language = form.cleaned_data["language"] if can_change_admin_status: role = form.cleaned_data["role"] if role: couch_user.set_role(domain, role) couch_user.save() if request.couch_user.get_id == couch_user.get_id and couch_user.language: # update local language in the session request.session["django_language"] = couch_user.language messages.success(request, 'Changes saved for user "%s"' % couch_user.username) else: form = UserForm(role_choices=role_choices) if not create_user: form.initial["first_name"] = couch_user.first_name form.initial["last_name"] = couch_user.last_name form.initial["email"] = couch_user.email form.initial["language"] = couch_user.language if can_change_admin_status: if couch_user.is_commcare_user(): role = couch_user.get_role(domain) if role is None: initial = "none" else: initial = role.get_qualified_id() form.initial["role"] = initial else: form.initial["role"] = couch_user.get_role(domain, include_teams=False).get_qualified_id() or "" if not can_change_admin_status: del form.fields["role"] context.update({"form": form}) return context
def obj_get_list(self, bundle, **kwargs): application_id = bundle.request.GET.get('application_id') if not application_id: raise NotFound('application_id parameter required') domain = kwargs['domain'] couch_user = CouchUser.from_django_user(bundle.request.user) if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION ) or not couch_user.is_member_of(domain): raise ImmediateHttpResponse( HttpForbidden( 'You are not allowed to get list of forms for this domain') ) results = [] application = Application.get(docid=application_id) if not application: return [] forms_objects = application.get_forms(bare=False) for form_object in forms_objects: form = form_object['form'] module = form_object['module'] form_name = '{} > {} > {}'.format(application.name, module.default_name(), form.default_name()) results.append(Form(form_xmlns=form.xmlns, form_name=form_name)) return results
def restore(request, domain, app_id=None): """ We override restore because we have to supply our own user model (and have the domain in the url) """ user = request.user couch_user = CouchUser.from_django_user(user) return get_restore_response(domain, couch_user, app_id, **get_restore_params(request))
def restore(request, domain): """ We override restore because we have to supply our own user model (and have the domain in the url) """ user = request.user couch_user = CouchUser.from_django_user(user) return get_restore_response(domain, couch_user, **get_restore_params(request))
def _inner(request, domain, *args, **kwargs): request.couch_user = couch_user = CouchUser.from_django_user( request.user) if (allow_cc_users or couch_user.is_web_user() ) and couch_user.is_member_of(domain): return fn(request, domain, *args, **kwargs) else: return HttpResponseForbidden()
def form_valid(self, form): change_messages = {} if not self.user: return self.redirect_response(self.request) reset_password = form.cleaned_data['reset_password'] if reset_password: self.user.set_password(uuid.uuid4().hex) change_messages.update(UserChangeMessage.password_reset()) # toggle active state self.user.is_active = not self.user.is_active self.user.save() verb = 're-enabled' if self.user.is_active else 'disabled' reason = form.cleaned_data['reason'] change_messages.update( UserChangeMessage.status_update(self.user.is_active, reason)) couch_user = CouchUser.from_django_user(self.user) log_user_change(by_domain=None, for_domain=None, couch_user=couch_user, changed_by_user=self.request.couch_user, changed_via=USER_CHANGE_VIA_WEB, change_messages=change_messages, fields_changed={'is_active': self.user.is_active}, by_domain_required_for_log=False, for_domain_required_for_log=False) mail_admins( "User account {}".format(verb), "The following user account has been {verb}: \n" " Account: {username}\n" " Reset by: {reset_by}\n" " Password reset: {password_reset}\n" " Reason: {reason}".format( verb=verb, username=self.username, reset_by=self.request.user.username, password_reset=str(reset_password), reason=reason, )) send_HTML_email( "%sYour account has been %s" % (settings.EMAIL_SUBJECT_PREFIX, verb), self.user.get_email() if self.user else self.username, render_to_string('hqadmin/email/account_disabled_email.html', context={ 'support_email': settings.SUPPORT_EMAIL, 'password_reset': reset_password, 'user': self.user, 'verb': verb, 'reason': form.cleaned_data['reason'], }), ) messages.success(self.request, _('Account successfully %(verb)s.' % {'verb': verb})) return redirect(self.redirect_url)
def post(self, request, *args, **kwargs): self.extra_context['hide_password_feedback'] = has_custom_clean_password() response = super().post(request, *args, **kwargs) uidb64 = kwargs.get('uidb64') uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) couch_user = CouchUser.from_django_user(user) clear_login_attempts(couch_user) return response
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 post(self, request, *args, **kwargs): self.extra_context['hide_password_feedback'] = settings.ENABLE_DRACONIAN_SECURITY_FEATURES response = super().post(request, *args, **kwargs) uidb64 = kwargs.get('uidb64') uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) couch_user = CouchUser.from_django_user(user) clear_login_attempts(couch_user) return response
def eula_agreement(request): if request.method == 'POST': current_user = CouchUser.from_django_user(request.user) current_user.eula.signed = True current_user.eula.date = datetime.utcnow() current_user.eula.user_ip = get_ip(request) current_user.save() return HttpResponseRedirect(request.POST.get('next', '/'))
def eula_agreement(request): if request.method == 'POST': current_user = CouchUser.from_django_user(request.user) current_user.eula.signed = True current_user.eula.date = datetime.utcnow() current_user.eula.user_ip = get_ip(request) current_user.save() return HttpResponseRedirect(request.POST.get('next', '/'))
def _handle_user_form(request, domain, couch_user=None): from corehq.apps.reports.util import get_possible_reports context = {} if couch_user: create_user = False else: create_user = True can_change_admin_status = \ (request.user.is_superuser or request.couch_user.can_edit_web_users(domain=domain))\ and request.couch_user.user_id != couch_user.user_id if couch_user.is_commcare_user(): role_choices = UserRole.commcareuser_role_choices(domain) else: role_choices = UserRole.role_choices(domain) if request.method == "POST" and request.POST['form_type'] == "basic-info": form = UserForm(request.POST, role_choices=role_choices) if form.is_valid(): if create_user: django_user = User() django_user.username = form.cleaned_data['email'] django_user.save() couch_user = CouchUser.from_django_user(django_user) couch_user.first_name = form.cleaned_data['first_name'] couch_user.last_name = form.cleaned_data['last_name'] couch_user.email = form.cleaned_data['email'] couch_user.language = form.cleaned_data['language'] if can_change_admin_status: role = form.cleaned_data['role'] if role: couch_user.set_role(domain, role) couch_user.save() messages.success(request, 'Changes saved for user "%s"' % couch_user.username) else: form = UserForm(role_choices=role_choices) if not create_user: form.initial['first_name'] = couch_user.first_name form.initial['last_name'] = couch_user.last_name form.initial['email'] = couch_user.email form.initial['language'] = couch_user.language if can_change_admin_status: if couch_user.is_commcare_user(): role = couch_user.get_role(domain) if role is None: initial = "none" else: initial = role.get_qualified_id() form.initial['role'] = initial else: form.initial['role'] = couch_user.get_role(domain).get_qualified_id() or '' if not can_change_admin_status: del form.fields['role'] context.update({"form": form}) return context
def track_user_login(sender, request, user, **kwargs): couch_user = CouchUser.from_django_user(user) if couch_user and couch_user.is_web_user(): if not request or HUBSPOT_COOKIE not in request.COOKIES: # API calls, form submissions etc. return meta = get_meta(request) track_user_sign_in_on_hubspot.delay(couch_user, request.COOKIES, meta, request.path)
def handle(self, *args, **options): for dimagi_user in self.get_dimagi_account_users(): couch_user = CouchUser.from_django_user(dimagi_user) if couch_user: username = dimagi_user.username print("username: "******"domain: " + domain_name) self.update_domain_if_self_started(domain_name, username)
def handle(self, *args, **options): for dimagi_user in self.get_dimagi_account_users(): couch_user = CouchUser.from_django_user(dimagi_user) if couch_user: username = dimagi_user.username print("username: "******"domain: " + domain_name) self.update_domain_if_self_started(domain_name, username)
def _inner(request, domain, *args, **kwargs): request.couch_user = couch_user = CouchUser.from_django_user(request.user) if ( couch_user and (allow_cc_users or couch_user.is_web_user()) and couch_user.is_member_of(domain) ): return fn(request, domain, *args, **kwargs) else: return HttpResponseForbidden()
def track_user_login(sender, request, user, **kwargs): couch_user = CouchUser.from_django_user(user) if couch_user and couch_user.is_web_user(): if not request or HUBSPOT_COOKIE not in request.COOKIES: # API calls, form submissions etc. return meta = get_meta(request) track_user_sign_in_on_hubspot.delay(couch_user, request.COOKIES, meta, request.path)
def set_language(sender, **kwargs): """ Whenever a user logs in, attempt to set their browser session to the right language. HT: http://mirobetm.blogspot.com/2012/02/django-language-set-in-database-field.html """ user = kwargs['user'] couch_user = CouchUser.from_django_user(user) if couch_user and couch_user.language: kwargs['request'].session['django_language'] = couch_user.language
def post(self, request, *args, **kwargs): extra_context = kwargs.setdefault('extra_context', {}) extra_context['hide_password_feedback'] = settings.ENABLE_DRACONIAN_SECURITY_FEATURES response = password_reset_confirm(request, *args, **kwargs) uidb64 = kwargs.get('uidb64') uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) couch_user = CouchUser.from_django_user(user) clear_login_attempts(couch_user) return response
def eula_agreement(request, domain): domain = Domain.get_by_name(domain) if request.method == 'POST': current_user = CouchUser.from_django_user(request.user) current_user.eula.signed = True current_user.eula.date = datetime.utcnow() current_user.eula.type = 'End User License Agreement' current_user.eula.user_ip = get_ip(request) current_user.save() return HttpResponseRedirect(reverse("corehq.apps.reports.views.default", args=[domain]))
def obj_get_list(self, bundle, **kwargs): domain = kwargs['domain'] couch_user = CouchUser.from_django_user(bundle.request.user) if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION) or not couch_user.is_member_of(domain): raise ImmediateHttpResponse( HttpForbidden('You are not allowed to get list of case types for this domain') ) case_types = get_case_types_for_domain_es(domain) results = [CaseType(case_type=case_type) for case_type in case_types] return results
def all_for_user(user): if not hasattr(user,'get_profile'): # this had better be an anonymous user return OldDomain.objects.none() from corehq.apps.users.models import CouchUser couch_user = CouchUser.from_django_user(user) if couch_user: domain_names = couch_user.get_domains() return OldDomain.objects.filter(name__in=domain_names) else: return OldDomain.objects.none()
def list_apps(request): """Return a list of all apps available to the user Used by the phone for app installation """ couch_user = CouchUser.from_django_user(request.user) return HttpResponse( get_app_list_xml( get_all_latest_builds_for_user(couch_user)).serializeDocument(), content_type='application/xml', )
def eula_agreement(request, domain): domain = Domain.get_by_name(domain) if request.method == 'POST': current_user = CouchUser.from_django_user(request.user) current_user.eula.signed = True current_user.eula.date = datetime.utcnow() current_user.eula.type = 'End User License Agreement' current_user.eula.user_ip = get_ip(request) current_user.save() return HttpResponseRedirect(reverse("corehq.apps.reports.views.default", args=[domain]))
def obj_get_list(self, bundle, **kwargs): domain = kwargs['domain'] couch_user = CouchUser.from_django_user(bundle.request.user) if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION) or not couch_user.is_member_of(domain): raise ImmediateHttpResponse( HttpForbidden('You are not allowed to get list of case types for this domain') ) case_types = get_case_types_for_domain_es(domain) results = [CaseType(case_type=case_type) for case_type in case_types] return results
def get_object_list(self, request): couch_user = CouchUser.from_django_user(request.user) results = [] for domain in couch_user.get_domains(): if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION): continue domain_object = Domain.get_by_name(domain) results.append(UserDomain( domain_name=domain_object.name, project_name=domain_object.hr_name or domain_object.name )) return results
def list_apps(request): """Return a list of all apps available to the user Used by the phone for app installation """ couch_user = CouchUser.from_django_user(request.user) return HttpResponse( get_app_list_xml( get_all_latest_builds_for_user(couch_user) ).serializeDocument(), content_type='application/xml', )
def track_user_login(sender, request, user, **kwargs): couch_user = CouchUser.from_django_user(user) if couch_user and couch_user.is_web_user(): if not request or HUBSPOT_COOKIE not in request.COOKIES: # API calls, form submissions etc. return meta = { 'HTTP_X_FORWARDED_FOR': request.META.get('HTTP_X_FORWARDED_FOR'), 'REMOTE_ADDR': request.META.get('REMOTE_ADDR'), } track_user_sign_in_on_hubspot.delay(couch_user, request.COOKIES, meta)
def _inner(req, domain, *args, **kwargs): user = req.user domain_name, domain = load_domain(req, domain) if domain: if user.is_authenticated and user.is_active: if not domain.is_active: msg = _(( 'The domain "{domain}" has not yet been activated. ' 'Please report an issue if you think this is a mistake.' ).format(domain=domain_name)) messages.info(req, msg) return HttpResponseRedirect(reverse("domain_select")) if hasattr(req, "couch_user"): couch_user = req.couch_user # set by user middleware else: # some views might not have this set couch_user = CouchUser.from_django_user(user) if couch_user.is_member_of(domain): if domain.two_factor_auth and not user.is_verified( ) and not couch_user.two_factor_disabled: return TemplateResponse( request=req, template='two_factor/core/otp_required.html', status=403, ) else: return view_func(req, domain_name, *args, **kwargs) elif (_page_is_whitelist(req.path, domain_name) or not domain.restrict_superusers) and user.is_superuser: # superusers can circumvent domain permissions. return view_func(req, domain_name, *args, **kwargs) elif domain.is_snapshot: # snapshots are publicly viewable return require_previewer(view_func)(req, domain_name, *args, **kwargs) elif domain.allow_domain_requests: from corehq.apps.users.views import DomainRequestView return DomainRequestView.as_view()(req, *args, **kwargs) else: raise Http404 elif (req.path.startswith( u'/a/{}/reports/custom'.format(domain_name)) and PUBLISH_CUSTOM_REPORTS.enabled(domain_name)): return view_func(req, domain_name, *args, **kwargs) else: login_url = reverse('domain_login', kwargs={'domain': domain}) return _redirect_for_login_or_domain(req, REDIRECT_FIELD_NAME, login_url) else: msg = _(('The domain "{domain}" was not found.').format( domain=domain_name)) raise Http404(msg)
def all_for_user(user): if not hasattr(user, "get_profile"): # this had better be an anonymous user return [] from corehq.apps.users.models import CouchUser couch_user = CouchUser.from_django_user(user) if couch_user: domain_names = couch_user.get_domains() return Domain.view("domain/domains", keys=domain_names, reduce=False, include_docs=True).all() else: return []
def active_for_user(user, is_active=True): if isinstance(user, AnonymousUser): return [] from corehq.apps.users.models import CouchUser if isinstance(user, CouchUser): couch_user = user else: couch_user = CouchUser.from_django_user(user) if couch_user: return Domain.active_for_couch_user(couch_user, is_active=is_active) else: return []
def active_for_user(user, is_active=True): if isinstance(user, AnonymousUser): return [] from corehq.apps.users.models import CouchUser if isinstance(user, CouchUser): couch_user = user else: couch_user = CouchUser.from_django_user(user) if couch_user: return Domain.active_for_couch_user(couch_user, is_active=is_active) else: return []
def get_object_list(self, request): couch_user = CouchUser.from_django_user(request.user) results = [] for domain in couch_user.get_domains(): if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION): continue domain_object = Domain.get_by_name(domain) results.append( UserDomain(domain_name=domain_object.name, project_name=domain_object.hr_name or domain_object.name)) return results
def track_user_login(sender, request, user, **kwargs): couch_user = CouchUser.from_django_user(user) if couch_user and couch_user.is_web_user(): if not request or HUBSPOT_COOKIE not in request.COOKIES: # API calls, form submissions etc. return meta = { 'HTTP_X_FORWARDED_FOR': request.META.get('HTTP_X_FORWARDED_FOR'), 'REMOTE_ADDR': request.META.get('REMOTE_ADDR'), } track_user_sign_in_on_hubspot.delay(couch_user, request.COOKIES, meta)
def obj_get_list(self, bundle, **kwargs): domain = kwargs['domain'] couch_user = CouchUser.from_django_user(bundle.request.user) if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION) or not couch_user.is_member_of(domain): raise ImmediateHttpResponse( HttpForbidden('You are not allowed to get list of usernames for this domain') ) user_ids_username_pairs = get_all_user_id_username_pairs_by_domain(domain) results = [UserInfo(user_id=user_pair[0], user_name=raw_username(user_pair[1])) for user_pair in user_ids_username_pairs] return results
def new_view(req, domain, *args, **kwargs): if req.method == 'POST': cookie = req.POST.get('_cookie') if cookie: cookies = dict(map(lambda x: x.strip().split('=', 1), cookie.split(';'))) session_key = cookies.get(settings.SESSION_COOKIE_NAME, None) engine = import_module(settings.SESSION_ENGINE) req.session = engine.SessionStore(session_key) req.user = get_user(req) req.couch_user = CouchUser.from_django_user(req.user) return login_decorator(view_func)(req, domain, *args, **kwargs)
def new_view(req, domain, *args, **kwargs): if req.method == 'POST': cookie = req.POST.get('_cookie') if cookie: cookies = dict([x.strip().split('=', 1) for x in cookie.split(';')]) session_key = cookies.get(settings.SESSION_COOKIE_NAME, None) engine = import_module(settings.SESSION_ENGINE) req.session = engine.SessionStore(session_key) req.user = get_user(req) req.couch_user = CouchUser.from_django_user(req.user) return login_decorator(view_func)(req, domain, *args, **kwargs)
def process_view(self, request, view_func, view_args, view_kwargs): if 'domain' in view_kwargs: request.domain = view_kwargs['domain'] if 'org' in view_kwargs: request.org = view_kwargs['org'] if request.user and hasattr(request.user, 'get_profile'): sessionid = request.COOKIES.get('sessionid', None) if sessionid: # roundabout way to keep doc_id based caching consistent. # get user doc_id from session_id MISSING = object() INTERRUPTED = object() try: cached_user_doc_id = rcache.get(SESSION_USER_KEY_PREFIX % sessionid, MISSING) except ConnectionInterrumped: cached_user_doc_id = INTERRUPTED # disable session based couch user caching - to be enabled later. if cached_user_doc_id not in (MISSING, INTERRUPTED): # cache hit couch_user = CouchUser.wrap_correctly( cache_core.cached_open_doc( CouchUser.get_db(), cached_user_doc_id ) ) else: # cache miss, write to cache couch_user = CouchUser.from_django_user(request.user) if couch_user: cache_core.do_cache_doc(couch_user.to_json()) if cached_user_doc_id is not INTERRUPTED: rcache.set(SESSION_USER_KEY_PREFIX % sessionid, couch_user.get_id) request.couch_user = couch_user if 'domain' in view_kwargs: domain = request.domain if not request.couch_user: couch_domain = Domain.view("domain/domains", key=domain, reduce=False, include_docs=True, ).one() if couch_domain and couch_domain.is_public: request.couch_user = PublicUser(domain) else: request.couch_user = InvalidUser() if request.couch_user: request.couch_user.current_domain = domain return None
def track_user_login(sender, request, user, **kwargs): if settings.ANALYTICS_IDS.get('HUBSPOT_API_ID'): couch_user = CouchUser.from_django_user(user) if couch_user and couch_user.is_web_user(): if not request or HUBSPOT_COOKIE not in request.COOKIES: # API calls, form submissions etc. user_confirming = request.path.startswith(reverse(ProcessRegistrationView.urlname)) if user_confirming: _no_cookie_soft_assert(False, 'User confirmed account but had no cookie') else: return meta = get_meta(request) track_user_sign_in_on_hubspot_v2.delay(couch_user, request.COOKIES.get(HUBSPOT_COOKIE), meta, request.path)
def request_new_domain(request, form, org, new_user=True, slug=''): now = datetime.utcnow() current_user = CouchUser.from_django_user(request.user) dom_req = RegistrationRequest() if new_user: dom_req.request_time = now dom_req.request_ip = get_ip(request) dom_req.activation_guid = uuid.uuid1().hex new_domain = Domain(name=form.cleaned_data['domain_name'], is_active=False, date_created=datetime.utcnow(), creating_user=current_user.username) if org: new_domain.organization = org if slug: new_domain.slug = slug if not new_user: new_domain.is_active = True new_domain.save() if not new_domain.name: new_domain.name = new_domain._id new_domain.save() # we need to get the name from the _id dom_req.domain = new_domain.name if request.user.is_authenticated(): if not current_user: current_user = WebUser() current_user.sync_from_django_user(request.user) current_user.save() current_user.add_domain_membership(new_domain.name, is_admin=True) current_user.save() dom_req.requesting_user_username = request.user.username dom_req.new_user_username = request.user.username if new_user: dom_req.save() send_domain_registration_email(request.user.email, dom_req.domain, dom_req.activation_guid) else: send_global_domain_registration_email(request.user, new_domain.name) send_new_domain_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
def accept_invitation(request, domain, invitation_id): if request.GET.get('switch') == 'true': logout(request) return redirect_to_login(request.path) if request.GET.get('create') == 'true': logout(request) return HttpResponseRedirect(request.path) invitation = Invitation.get(invitation_id) assert(invitation.domain == domain) if invitation.is_accepted: messages.error(request, "Sorry that invitation has already been used up. " "If you feel this is a mistake please ask the inviter for " "another invitation.") return HttpResponseRedirect(reverse("login")) if request.user.is_authenticated(): # if you are already authenticated, just add the domain to your # list of domains if request.couch_user.username != invitation.email: messages.error(request, "The invited user %s and your user %s do not match!" % (invitation.email, request.couch_user.username)) if request.method == "POST": couch_user = CouchUser.from_django_user(request.user) couch_user.add_domain_membership(domain=domain) couch_user.set_role(domain, invitation.role) couch_user.save() invitation.is_accepted = True invitation.save() messages.success(request, "You have been added to the %s domain" % domain) return HttpResponseRedirect(reverse("domain_homepage", args=[domain,])) else: return render_to_response(request, 'users/accept_invite.html', {'domain': domain, "invited_user": invitation.email if request.couch_user.username != invitation.email else ""}) else: # if you're not authenticated we need you to fill out your information if request.method == "POST": form = NewWebUserRegistrationForm(request.POST) if form.is_valid(): user = activate_new_user(form, is_domain_admin=False, domain=invitation.domain) user.set_role(domain, invitation.role) user.save() invitation.is_accepted = True invitation.save() messages.success(request, "User account for %s created! You may now login." % form.cleaned_data["email"]) return HttpResponseRedirect(reverse("login")) else: form = NewWebUserRegistrationForm(initial={'email': invitation.email}) return render_to_response(request, "users/accept_invite.html", {"form": form})