예제 #1
0
    def setUpClass(cls):
        super(GetRestoreUserTest, cls).setUpClass()
        cls.project = Domain(name=cls.domain)
        cls.project.save()

        cls.other_project = Domain(name=cls.other_domain)
        cls.other_project.save()

        cls.web_user = WebUser.create(
            username='******',
            domain=cls.domain,
            password='******',
        )
        cls.commcare_user = CommCareUser.create(
            username=format_username('jane', cls.domain),
            domain=cls.domain,
            password='******',
        )
        cls.other_commcare_user = CommCareUser.create(
            username=format_username('john', cls.domain),
            domain=cls.domain,
            password='******',
        )
        cls.super_user = WebUser.create(
            username='******',
            domain=cls.other_domain,
            password='******',
        )
        cls.super_user.is_superuser = True
        cls.super_user.save()
예제 #2
0
    def setUpClass(cls):
        super(RestorePermissionsTest, cls).setUpClass()

        cls.other_project = Domain(name=cls.other_domain)
        cls.other_project.save()

        cls.web_user = WebUser.create(
            username='******',
            domain=cls.domain,
            password='******',
        )
        cls.super_user = WebUser.create(
            username='******',
            domain=cls.other_domain,
            password='******',
        )
        cls.super_user.is_superuser = True
        cls.super_user.save()
        cls.commcare_user = CommCareUser.create(
            username=format_username('super', cls.domain),
            domain=cls.domain,
            password='******',
        )
        cls.no_edit_commcare_user = CommCareUser.create(
            username=format_username('noedit', cls.domain),
            domain=cls.domain,
            password='******',
        )
        cls.location_user = CommCareUser.create(
            username=format_username('location', cls.domain),
            domain=cls.domain,
            password='******',
        )
        cls.wrong_location_user = CommCareUser.create(
            username=format_username('wrong-location', cls.domain),
            domain=cls.domain,
            password='******',
        )
        cls.web_location_user = WebUser.create(
            username='******',
            domain=cls.domain,
            password='******',
        )

        cls.commcare_user.set_location(cls.locations['usa'])
        cls.web_location_user.set_location(cls.domain, cls.locations['usa'])
        cls.no_edit_commcare_user.set_location(cls.locations['usa'])
        cls.location_user.set_location(cls.locations['ma'])
        cls.wrong_location_user.set_location(cls.locations['montreal'])

        cls.restrict_user_to_assigned_locations(cls.commcare_user)
        cls.restrict_user_to_assigned_locations(cls.web_location_user)
예제 #3
0
def _login(req, domain_name, template_name):

    if req.user.is_authenticated() and req.method == "GET":
        redirect_to = req.GET.get('next', '')
        if redirect_to:
            return HttpResponseRedirect(redirect_to)
        if not domain_name:
            return HttpResponseRedirect(reverse('homepage'))
        else:
            return HttpResponseRedirect(reverse('domain_homepage', args=[domain_name]))

    if req.method == 'POST' and domain_name and '@' not in req.POST.get('auth-username', '@'):
        req.POST._mutable = True
        req.POST['auth-username'] = format_username(req.POST['auth-username'], domain_name)
        req.POST._mutable = False

    req.base_template = settings.BASE_TEMPLATE

    context = {}
    if domain_name:
        domain = Domain.get_by_name(domain_name)
        req_params = req.GET if req.method == 'GET' else req.POST
        context.update({
            'domain': domain_name,
            'hr_name': domain.display_name() if domain else domain_name,
            'next': req_params.get('next', '/a/%s/' % domain),
            'allow_domain_requests': domain.allow_domain_requests,
        })

    auth_view = HQLoginView if not domain_name else CloudCareLoginView
    return auth_view.as_view(template_name=template_name, extra_context=context)(req)
예제 #4
0
파일: v0_4.py 프로젝트: ekush/commcare-hq
    def post_list(self, request, **kwargs):
        domain = kwargs.get('domain')
        request.domain = domain
        username = request.POST.get('username')
        password = request.POST.get('password')

        if username is None:
            return HttpResponseBadRequest('Missing required parameter: username')

        if password is None:
            return HttpResponseBadRequest('Missing required parameter: password')

        if '@' not in username:
            username = format_username(username, domain)

        # Convert to the appropriate type of user
        couch_user = CouchUser.get_by_username(username)
        if couch_user is None or not couch_user.is_member_of(domain) or not couch_user.check_password(password):
            return HttpResponseForbidden()

        if couch_user.is_commcare_user():
            user_resource = v0_1.CommCareUserResource()
        elif couch_user.is_web_user():
            user_resource = v0_1.WebUserResource()
        else:
            return HttpResponseForbidden()

        bundle = user_resource.build_bundle(obj=couch_user, request=request)
        bundle = user_resource.full_dehydrate(bundle)
        return user_resource.create_response(request, bundle, response_class=HttpResponse)
예제 #5
0
파일: forms.py 프로젝트: bazuzi/commcare-hq
def clean_mobile_worker_username(
    domain, username, name_too_long_message=None, name_reserved_message=None, name_exists_message=None
):

    max_username_length = get_mobile_worker_max_username_length(domain)

    if len(username) > max_username_length:
        raise forms.ValidationError(
            name_too_long_message
            or _("Username %(username)s is too long.  Must be under %(max_length)s characters.")
            % {"username": username, "max_length": max_username_length}
        )

    if username in UNALLOWED_MOBILE_WORKER_NAMES:
        raise forms.ValidationError(
            name_reserved_message or _('The username "%(username)s" is reserved for CommCare.') % {"username": username}
        )

    username = format_username(username, domain)
    validate_username(username)

    if CouchUser.username_exists(username):
        raise forms.ValidationError(name_exists_message or _("This Mobile Worker already exists."))

    return username
예제 #6
0
파일: views.py 프로젝트: dimagi/commcare-hq
    def get_restore_as_user(request, domain):
        """
        returns (user, set_cookie), where set_cookie is a function to be called on
        the eventual response
        """

        if not hasattr(request, 'couch_user'):
            raise Http404()

        def set_cookie(response):  # set_coookie is a noop by default
            return response

        cookie_name = six.moves.urllib.parse.quote(
            'restoreAs:{}:{}'.format(domain, request.couch_user.username))
        username = request.COOKIES.get(cookie_name)
        if username:
            user = CouchUser.get_by_username(format_username(username, domain))
            if user:
                return user, set_cookie
            else:
                def set_cookie(response):  # overwrite the default noop set_cookie
                    response.delete_cookie(cookie_name)
                    return response

        return request.couch_user, set_cookie
예제 #7
0
def _process_log_subreport(domain, xform):
    form_data = xform.form_data
    logs = _get_logs(form_data, 'log_subreport', 'log')
    logged_in_username = None
    logged_in_user_id = None
    to_save = []
    for i, log in enumerate(logs):
        if not log:
            continue
        if log["type"] == 'login':
            # j2me log = user_id_prefix-username
            logged_in_username = log["msg"].split('-')[1]
            cc_username = format_username(logged_in_username, domain)
            logged_in_user_id = get_user_id_by_username(cc_username)
        elif log["type"] == 'user' and log["msg"][:5] == 'login':
            # android log = login|username|user_id
            msg_split = log["msg"].split('|')
            logged_in_username = msg_split[1]
            logged_in_user_id = msg_split[2]

        to_save.append(DeviceReportEntry(
            xform_id=xform.form_id,
            i=i,
            domain=domain,
            type=log["type"],
            msg=log["msg"],
            # must accept either date or datetime string
            date=log["@date"],
            server_date=xform.received_on,
            app_version=form_data.get('app_version'),
            device_id=form_data.get('device_id'),
            username=logged_in_username,
            user_id=logged_in_user_id,
        ))
    DeviceReportEntry.objects.bulk_create(to_save)
예제 #8
0
def _login(req, domain, domain_type, template_name, domain_context=None):
    from corehq.apps.registration.views import get_domain_context

    if req.user.is_authenticated() and req.method != "POST":
        redirect_to = req.REQUEST.get('next', '')
        if redirect_to:
            return HttpResponseRedirect(redirect_to)
        if not domain:
            return HttpResponseRedirect(reverse('homepage'))
        else:
            return HttpResponseRedirect(reverse('domain_homepage', args=[domain]))

    if req.method == 'POST' and domain and '@' not in req.POST.get('username', '@'):
        req.POST._mutable = True
        req.POST['username'] = format_username(req.POST['username'], domain)
        req.POST._mutable = False
    
    req.base_template = settings.BASE_TEMPLATE
    context = domain_context or get_domain_context(domain_type)
    context['domain'] = domain
    if domain:
        context['next'] = req.REQUEST.get('next', '/a/%s/' % domain)

    return django_login(req, template_name=template_name,
                        authentication_form=EmailAuthenticationForm if not domain else CloudCareAuthenticationForm,
                        extra_context=context)
예제 #9
0
    def get(self, request, *args, **kwargs):
        full_username = request.GET.get('as', '')
        if not full_username or '@' not in full_username:
            return HttpResponseBadRequest('Please specify a user using ?as=user@domain')

        username, domain = full_username.split('@')
        if not domain.endswith(settings.HQ_ACCOUNT_ROOT):
            full_username = format_username(username, domain)

        self.user = CommCareUser.get_by_username(full_username)
        if not self.user:
            return HttpResponseNotFound('User %s not found.' % full_username)

        self.app_id = kwargs.get('app_id', None)

        raw = request.GET.get('raw') == 'true'
        if raw:
            response, _ = self._get_restore_response()
            return response

        download = request.GET.get('download') == 'true'
        if download:
            response, _ = self._get_restore_response()
            response['Content-Disposition'] = "attachment; filename={}-restore.xml".format(username)
            return response

        return super(AdminRestoreView, self).get(request, *args, **kwargs)
예제 #10
0
def _login(req, domain, template_name):

    if req.user.is_authenticated() and req.method != "POST":
        redirect_to = req.REQUEST.get('next', '')
        if redirect_to:
            return HttpResponseRedirect(redirect_to)
        if not domain:
            return HttpResponseRedirect(reverse('homepage'))
        else:
            return HttpResponseRedirect(reverse('domain_homepage', args=[domain]))

    if req.method == 'POST' and domain and '@' not in req.POST.get('username', '@'):
        req.POST._mutable = True
        req.POST['username'] = format_username(req.POST['username'], domain)
        req.POST._mutable = False
    
    req.base_template = settings.BASE_TEMPLATE

    context = {}
    if domain:
        context.update({
            'domain': domain,
            'next': req.REQUEST.get('next', '/a/%s/' % domain),
        })

    return django_login(req, template_name=template_name,
                        authentication_form=EmailAuthenticationForm if not domain else CloudCareAuthenticationForm,
                        extra_context=context)
예제 #11
0
def get_id_from_name(uploaded_name, domain, cache):
    '''
    :param uploaded_name: A username or group name
    :param domain:
    :param cache:
    :return: Looks for the given name and returns the corresponding id if the
    user or group exists and None otherwise. Searches for user first, then
    group.
    '''
    if uploaded_name in cache:
        return cache[uploaded_name]
    try:
        name_as_address = uploaded_name
        if '@' not in name_as_address:
            name_as_address = format_username(uploaded_name, domain)
        user = CouchUser.get_by_username(name_as_address)
        id = getattr(user, 'couch_id', None)
    except NoResultFound:
        id = None
    if not id:
        group = Group.by_name(domain, uploaded_name, one=True)
        id = getattr(group, 'get_id', None)

    cache[uploaded_name] = id
    return id
예제 #12
0
    def clean(self):
        try:
            password = self.cleaned_data['password']
            password_2 = self.cleaned_data['password_2']
        except KeyError:
            pass
        else:
            if password != password_2:
                raise forms.ValidationError("Passwords do not match")
            if self.password_format == 'n' and not password.isnumeric():
                raise forms.ValidationError("Password is not numeric")

        try:
            username = self.cleaned_data['username']
        except KeyError:
            pass
        else:
            if len(username) > CommCareAccountForm.max_len_username:
                raise forms.ValidationError(
                    "Username %s is too long.  Must be under %d characters."
                    % (username, CommCareAccountForm.max_len_username))
            validate_username('*****@*****.**' % username)
            domain = self.cleaned_data['domain']
            username = format_username(username, domain)
            num_couch_users = len(CouchUser.view("users/by_username",
                                                 key=username,
                                                 reduce=False))
            if num_couch_users > 0:
                raise forms.ValidationError("CommCare user already exists")

            # set the cleaned username to [email protected]
            self.cleaned_data['username'] = username
        return self.cleaned_data
예제 #13
0
 def handle(self, *args, **options):
     if len(args) < 1:
         raise CommandError('Usage: manage.py submit_forms <domain>')
     domain = args[0]
     key = make_form_couch_key(domain)
     submissions = XFormInstance.view('reports_forms/all_forms',
         startkey=key,
         endkey=key+[{}],
         include_docs=True
     )
     ids_by_username = dict()
     def get_id(username):
         if username in ids_by_username:
             return ids_by_username[username]
         else:
             userID = get_db().view('users/logins_by_username', key=username).one()
             userID = userID['value'] if userID else None
             ids_by_username[username] = userID
             return userID
     for submission in submissions:
         if 'meta' in submission.form:
             username = format_username(submission.form['meta']['username'], domain)
             userID = get_id(username)
             if userID:
                 submission.form['meta']['userID'] = userID
                 submission.save()
             print submission._id, username, userID
         else:
             print "skipped: %s" % submission._id
예제 #14
0
    def check_username(self, in_data):
        try:
            username = in_data['username'].strip()
        except KeyError:
            return HttpResponseBadRequest('You must specify a username')
        if username == 'admin' or username == 'demo_user':
            return {'error': _('Username {} is reserved.').format(username)}
        try:
            validate_email("{}@example.com".format(username))
            if BAD_MOBILE_USERNAME_REGEX.search(username) is not None:
                raise ValidationError("Username contained an invalid character")
        except ValidationError:
            if '..' in username:
                return {
                    'error': _("Username may not contain consecutive . (period).")
                }
            if username.endswith('.'):
                return {
                    'error': _("Username may not end with a . (period).")
                }
            return {
                'error': _("Username may not contain special characters.")
            }

        full_username = format_username(username, self.domain)
        exists = user_exists(full_username)
        if exists.exists:
            if exists.is_deleted:
                result = {'warning': _('Username {} belonged to a user that was deleted.'
                                       ' Reusing it may have unexpected consequences.').format(username)}
            else:
                result = {'error': _('Username {} is already taken').format(username)}
        else:
            result = {'success': _('Username {} is available').format(username)}
        return result
예제 #15
0
 def test_assign_to_user_in_different_domain(self):
     other_user = CommCareUser.create('bad-domain', format_username('bad-domain-user', self.domain), "****")
     case = self._new_case()
     try:
         assign_case(case.case_id, other_user._id)
         self.fail('reassigning to user in wrong domain should fail')
     except CaseAssignmentError:
         pass
예제 #16
0
파일: tasks.py 프로젝트: dimagi/commcare-hq
def _get_unique_username(domain, base, suffix=0, tries_left=3):
    if tries_left == 0:
        raise AssertionError("Username {} on domain {} exists in multiple variations, "
                             "what's up with that?".format(base, domain))
    with_suffix = "{}{}".format(base, suffix) if suffix else base
    username = format_username(with_suffix, domain)
    if not CommCareUser.username_exists(username):
        return username
    return _get_unique_username(domain, base, suffix + 1, tries_left - 1)
예제 #17
0
 def get_from_user(name):
     try:
         name_as_address = name
         if '@' not in name_as_address:
             name_as_address = format_username(name, domain)
         user = CouchUser.get_by_username(name_as_address)
         return getattr(user, 'couch_id', None)
     except NoResultFound:
         return None
예제 #18
0
    def create_mobile_worker(self, in_data):
        if not self.can_add_extra_users:
            return {
                'error': _("No Permission."),
            }
        try:
            user_data = in_data['mobileWorker']
        except KeyError:
            return {
                'error': _("Please provide mobile worker data."),
            }

        try:
            form_data = {}
            for k, v in user_data.get('customFields', {}).items():
                form_data["{}-{}".format(CUSTOM_DATA_FIELD_PREFIX, k)] = v
            for f in ['username', 'password', 'first_name', 'last_name', 'location_id']:
                form_data[f] = user_data[f]
            form_data['domain'] = self.domain
            self.request.POST = form_data
        except Exception as e:
            return {
                'error': _("Check your request: %s" % e)
            }

        if self.new_mobile_worker_form.is_valid() and self.custom_data.is_valid():

            username = self.new_mobile_worker_form.cleaned_data['username']
            password = self.new_mobile_worker_form.cleaned_data['password']
            first_name = self.new_mobile_worker_form.cleaned_data['first_name']
            last_name = self.new_mobile_worker_form.cleaned_data['last_name']
            location_id = self.new_mobile_worker_form.cleaned_data['location_id']

            couch_user = CommCareUser.create(
                self.domain,
                format_username(username, self.domain),
                password,
                device_id="Generated from HQ",
                first_name=first_name,
                last_name=last_name,
                user_data=self.custom_data.get_data_to_save(),
            )
            if location_id:
                couch_user.set_location(SQLLocation.objects.get(location_id=location_id))

            return {
                'success': True,
                'editUrl': reverse(
                    EditCommCareUserView.urlname,
                    args=[self.domain, couch_user.userID]
                )
            }

        return {
            'error': _("Forms did not validate"),
        }
예제 #19
0
 def get_user_id(self, username, domain):
     cc_username = format_username(username, domain)
     result = CouchUser.view(
         'users/by_username',
         key=cc_username,
         include_docs=False,
     )
     row = result.one()
     if row:
         return row["id"]
예제 #20
0
    def setUpClass(cls):
        super(ReadableQuestionsAPITest, cls).setUpClass()
        cls.project = create_domain(cls.domain)
        cls.password = "******"
        cls.username = format_username('reed', cls.domain)

        cls.user = CommCareUser.create(
            cls.domain,
            cls.username,
            cls.password
        )
예제 #21
0
def generate_username(domain, first_name, last_name):
    if first_name and last_name:
        username = u'%s_%s' % (first_name, last_name)
    elif first_name:
        username = first_name
    else:
        username = '******' + uuid.uuid4().hex[:8]

    username = re.sub('[^\w]', '', username)
    username = username[:40]

    if CouchUser.username_exists(format_username(username, domain)):
        for i in range(2, 10000):
            tmp_username = u'%s-%s' % (username, i)
            if not CouchUser.username_exists(format_username(tmp_username, domain)):
                username = tmp_username
                break

    # Perform standard validation
    return clean_mobile_worker_username(domain, username)
예제 #22
0
    def setUp(self):
        super(UTHTests, self).setUp()
        delete_all_xforms()
        delete_all_cases()

        self.domain = create_domain(UTH_DOMAIN)

        username = format_username("vscan_user", UTH_DOMAIN)

        self.vscan_user = CommCareUser.get_by_username(username) or CommCareUser.create(UTH_DOMAIN, username, "secret")

        self.case_id = self.create_scan_case(self.vscan_user._id, "VH014466XK", "123123", "2014-03-28T10:48:49Z")
예제 #23
0
 def transfer_to_domain(self, domain, app_id):
     username = format_username(raw_username(self.username), domain)
     self.change_username(username)
     self.domain = domain
     for form in self.get_forms():
         form.domain = domain
         form.app_id = app_id
         form.save()
     for case in self.get_cases():
         case.domain = domain
         case.save()
     self.save()
예제 #24
0
    def test_other_registration_from_invite(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        user_data = {'abc': 'def'}

        # Initiate Registration Workflow
        SelfRegistrationInvitation.initiate_workflow(
            self.domain,
            [SelfRegistrationUserInfo('999123', user_data)],
            app_id=self.app_id,
        )

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=None,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_MOBILE_WORKER_INVITATION_START]])

        # Choose phone type 'other'
        incoming('+999123', '2', self.backend.hq_api_id)

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=SelfRegistrationInvitation.PHONE_TYPE_OTHER,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_MOBILE_WORKER_JAVA_INVITATION].format(self.domain)])

        # Register over SMS
        incoming('+999123', 'JOIN {} WORKER test'.format(self.domain), self.backend.hq_api_id)
        user = CommCareUser.get_by_username(format_username('test', self.domain))
        self.assertIsNotNone(user)
        self.assertEqual(user.user_data, user_data)
        self.assertEqual(PhoneNumber.by_phone('999123').owner_id, user.get_id)

        self.assertLastOutgoingSMS('+999123', [_MESSAGES[MSG_REGISTRATION_WELCOME_MOBILE_WORKER]])

        self.assertRegistrationInvitation(
            status=SelfRegistrationInvitation.STATUS_REGISTERED,
        )
예제 #25
0
    def setUpClass(cls):
        super(CaseAPIMiscTests, cls).setUpClass()
        cls.domain = uuid.uuid4().hex
        cls.project = create_domain(cls.domain)
        cls.username = uuid.uuid4().hex
        cls.password = "******"

        cls.user = CommCareUser.create(
            cls.domain,
            format_username(cls.username, cls.domain),
            cls.password
        )
예제 #26
0
def admin_restore(request):
    full_username = request.GET.get('as', '')
    if not full_username or '@' not in full_username:
        return HttpResponseBadRequest('Please specify a user using ?as=user@domain')

    username, domain = full_username.split('@')
    if not domain.endswith(settings.HQ_ACCOUNT_ROOT):
        full_username = format_username(username, domain)

    user = CommCareUser.get_by_username(full_username)
    if not user:
        return HttpResponseNotFound('User %s not found.' % full_username)
    return get_restore_response(user, **get_restore_params(request))
예제 #27
0
    def test_android_only_registration_from_invite(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        # Initiate Registration Workflow
        with patch('corehq.apps.sms.models.SelfRegistrationInvitation.odk_url') as mock_odk_url, \
                patch.object(SelfRegistrationInvitation, 'get_user_registration_url', return_value=DUMMY_REGISTRATION_URL), \
                patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            mock_odk_url.__get__ = Mock(return_value=DUMMY_APP_ODK_URL)
            SelfRegistrationInvitation.initiate_workflow(
                self.domain,
                [SelfRegistrationUserInfo('999123')],
                app_id=self.app_id,
                android_only=True,
            )

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=SelfRegistrationInvitation.PHONE_TYPE_ANDROID,
            android_only=True,
            require_email=False,
            custom_user_data={},
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [
            _MESSAGES[MSG_MOBILE_WORKER_ANDROID_INVITATION].format(DUMMY_REGISTRATION_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])

        invite = self._get_sms_registration_invitation()
        c = Client()
        response = c.post('/a/{}/settings/users/commcare/register/{}/'.format(self.domain, invite.token), {
            'username': '******',
            'password': '******',
            'password2': 'abc',
            'email': '*****@*****.**',
        })
        self.assertEqual(response.status_code, 200)

        user = CommCareUser.get_by_username(format_username('new_user', self.domain))
        self.assertIsNotNone(user)
        self.assertEqual(user.user_data, {})
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(PhoneNumber.by_phone('999123').owner_id, user.get_id)

        self.assertRegistrationInvitation(
            status=SelfRegistrationInvitation.STATUS_REGISTERED,
        )
예제 #28
0
파일: views.py 프로젝트: mchampanis/core-hq
def login(req, template_name="login_and_password/login.html"):
    # this view, and the one below, is overridden because
    # we need to set the base template to use somewhere
    # somewhere that the login page can access it.
    if req.user.is_authenticated() and req.method != "POST":
        return HttpResponseRedirect(reverse('homepage'))

    if req.method == 'POST' and req.POST.get('domain') and '@' not in req.POST.get('username', '@'):
        req.POST._mutable = True
        req.POST['username'] = format_username(req.POST['username'], req.POST['domain'])
        req.POST._mutable = False

    req.base_template = settings.BASE_TEMPLATE
    return django_login(req, template_name=template_name, authentication_form=EmailAuthenticationForm if not req.GET.get('domain') else CloudCareAuthenticationForm)
예제 #29
0
def _get_user_info_from_log(domain, log):
    logged_in_username = None
    logged_in_user_id = None
    if log["type"] == 'login':
        # j2me log = user_id_prefix-username
        logged_in_username = log["msg"].split('-')[1]
        cc_username = format_username(logged_in_username, domain)
        logged_in_user_id = get_user_id_by_username(cc_username)
    elif log["type"] == 'user' and log["msg"][:5] == 'login':
        # android log = login|username|user_id
        msg_split = log["msg"].split('|')
        logged_in_username = msg_split[1]
        logged_in_user_id = msg_split[2]

    return logged_in_username, logged_in_user_id
예제 #30
0
파일: views.py 프로젝트: jmaina/commcare-hq
def admin_restore(request):
    full_username = request.GET.get("as", "")
    if not full_username or "@" not in full_username:
        return HttpResponseBadRequest("Please specify a user using ?as=user@domain")

    username, domain = full_username.split("@")
    if not domain.endswith(settings.HQ_ACCOUNT_ROOT):
        full_username = format_username(username, domain)

    user = CommCareUser.get_by_username(full_username)
    if not user:
        return HttpResponseNotFound("User %s not found." % full_username)

    overwrite_cache = request.GET.get("ignore_cache") == "true"
    return get_restore_response(user.domain, user, overwrite_cache=overwrite_cache, **get_restore_params(request))
예제 #31
0
 def create_user(username):
     return CommCareUser.create(self.domain,
                                format_username(username, self.domain),
                                password)
예제 #32
0
def _login(req, domain_name, custom_login_page, extra_context=None):
    extra_context = extra_context or {}
    if req.user.is_authenticated and req.method == "GET":
        redirect_to = req.GET.get('next', '')
        if redirect_to:
            return HttpResponseRedirect(redirect_to)
        if not domain_name:
            return HttpResponseRedirect(reverse('homepage'))
        else:
            return HttpResponseRedirect(
                reverse('domain_homepage', args=[domain_name]))

    if req.method == 'POST' and domain_name and '@' not in req.POST.get(
            'auth-username', '@'):
        with mutable_querydict(req.POST):
            req.POST['auth-username'] = format_username(
                req.POST['auth-username'], domain_name)

    if 'auth-username' in req.POST:
        couch_user = CouchUser.get_by_username(
            req.POST['auth-username'].lower())
        if couch_user:
            new_lang = couch_user.language
            old_lang = req.session.get(LANGUAGE_SESSION_KEY)
            update_session_language(req, old_lang, new_lang)

    req.base_template = settings.BASE_TEMPLATE

    context = {}
    context.update(extra_context)
    template_name = custom_login_page if custom_login_page else 'login_and_password/login.html'
    if not custom_login_page and domain_name:
        domain_obj = Domain.get_by_name(domain_name)
        req_params = req.GET if req.method == 'GET' else req.POST
        context.update({
            'domain': domain_name,
            'hr_name': domain_obj.display_name(),
            'next': req_params.get('next', '/a/%s/' % domain_name),
            'allow_domain_requests': domain_obj.allow_domain_requests,
            'current_page': {
                'page_name':
                _('Welcome back to %s!') % domain_obj.display_name()
            },
        })
    else:
        commcare_hq_name = commcare_hq_names(
            req)['commcare_hq_names']["COMMCARE_HQ_NAME"]
        context.update({
            'current_page': {
                'page_name': _('Welcome back to %s!') % commcare_hq_name
            },
        })
    if settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS:
        auth_view = CloudCareLoginView
    else:
        auth_view = HQLoginView if not domain_name else CloudCareLoginView

    demo_workflow_ab_v2 = ab_tests.SessionAbTest(ab_tests.DEMO_WORKFLOW_V2,
                                                 req)

    if settings.IS_SAAS_ENVIRONMENT:
        context['demo_workflow_ab_v2'] = demo_workflow_ab_v2.context

    response = auth_view.as_view(template_name=template_name,
                                 extra_context=context)(req)

    if settings.IS_SAAS_ENVIRONMENT:
        demo_workflow_ab_v2.update_response(response)

    return response
예제 #33
0
파일: data.py 프로젝트: dankohn/commcare-hq
def _get_or_create_user(domain):
    username = format_username('nick', domain)
    user = CommCareUser.get_by_username(username, strict=True)
    if not user:
        user = CommCareUser.create(domain, username, 'secret', None, None)
    return user
예제 #34
0
 def create_user(username):
     username = format_username(username, cls.domain)
     return CommCareUser.create(cls.domain, username, cls.password)
예제 #35
0
    def test_android_registration_from_invite(self):
        self.domain_obj.sms_mobile_worker_registration_enabled = True
        self.domain_obj.enable_registration_welcome_sms_for_mobile_worker = True
        self.domain_obj.save()

        user_data = {'abc': 'def'}

        # Initiate Registration Workflow
        SelfRegistrationInvitation.initiate_workflow(
            self.domain,
            [SelfRegistrationUserInfo('999123', user_data)],
            app_id=self.app_id,
        )

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=None,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS(
            '+999123', [_MESSAGES[MSG_MOBILE_WORKER_INVITATION_START]])

        # Choose phone type 'android'
        with patch('corehq.apps.sms.models.SelfRegistrationInvitation.odk_url') as mock_odk_url, \
                patch.object(SelfRegistrationInvitation, 'get_user_registration_url', return_value=DUMMY_REGISTRATION_URL), \
                patch.object(SelfRegistrationInvitation, 'get_app_info_url', return_value=DUMMY_APP_INFO_URL):
            mock_odk_url.__get__ = Mock(return_value=DUMMY_APP_ODK_URL)
            incoming('+999123', '1', self.backend.hq_api_id)

        self.assertRegistrationInvitation(
            phone_number='999123',
            app_id=self.app_id,
            phone_type=SelfRegistrationInvitation.PHONE_TYPE_ANDROID,
            android_only=False,
            require_email=False,
            custom_user_data=user_data,
            status=SelfRegistrationInvitation.STATUS_PENDING,
        )

        self.assertLastOutgoingSMS('+999123', [
            _MESSAGES[MSG_MOBILE_WORKER_ANDROID_INVITATION].format(
                DUMMY_REGISTRATION_URL),
            '[commcare app - do not delete] {}'.format(DUMMY_APP_INFO_URL_B64),
        ])

        invite = self._get_sms_registration_invitation()
        c = Client()
        response = c.post(
            '/a/{}/settings/users/commcare/register/{}/'.format(
                self.domain, invite.token), {
                    'username': '******',
                    'password': '******',
                    'password2': 'abc',
                    'email': '*****@*****.**',
                })
        self.assertEqual(response.status_code, 200)

        user = CommCareUser.get_by_username(
            format_username('new_user', self.domain))
        self.assertIsNotNone(user)
        self.assertEqual(user.user_data,
                         dict(self.default_user_data, **user_data))
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(
            PhoneNumber.get_two_way_number('999123').owner_id, user.get_id)

        self.assertRegistrationInvitation(
            status=SelfRegistrationInvitation.STATUS_REGISTERED, )
예제 #36
0
 def id_to_username(issuer_id):
     return format_username(compress_nikshay_id(issuer_id, 3), self.domain)