Exemple #1
0
def _edit_profile(request, unique_id, new_account):
    ldap = UserSession.connect(request)
    person = ldap.get_by_unique_id(unique_id)

    del_form = forms.DeleteForm(
        initial=dict(unique_id=unique_id))

    if person:
        if request.method == 'POST':
            form = forms.ProfileForm(request.POST, request.FILES)
            if form.is_valid():
                ldap = UserSession.connect(request)
                ldap.update_person(unique_id, form.cleaned_data)
                ldap.update_profile_photo(unique_id, form.cleaned_data)
                if new_account:
                    return redirect('confirm_register')
                else:
                    return redirect('profile', unique_id)
        else:
            initial = dict(first_name=person.first_name,
                           last_name=person.last_name,
                           biography=person.biography,)

            initial.update(_get_services_fields(ldap, unique_id))
            form = forms.ProfileForm(initial)

        return jingo.render(request, 'phonebook/edit_profile.html', dict(
                form=form,
                delete_form=del_form,
                person=person,
                registration_flow=new_account,
                ))
    else:
        raise Http404
Exemple #2
0
    def authenticate(self, request=None, assertion=None):
        """Authentication based on BrowserID assertion.

        ``django.contrib.auth`` backend that is SASL and BrowserID
        savy. Uses session to maintain assertion over multiple
        requests.
        """
        if not (request and assertion):
            return None
        store_assertion(request, assertion)

        directory = UserSession(request)
        with statsd.timer('larper.sasl_bind_time'):
            (registered, details) = _get_registered_user(directory, request)

        if registered:
            person = directory.get_by_unique_id(details)
            defaults = dict(username=person.username,
                            first_name=person.first_name,
                            last_name=person.last_name,
                            email=person.username)
            user, created = User.objects.get_or_create(username=person.username,
                                                       defaults=defaults)
            if created:
                user.set_unusable_password()
                user.save()
            return user
        return None
Exemple #3
0
    def authenticate(self, request=None, assertion=None):
        """Authentication based on BrowserID assertion.

        ``django.contrib.auth`` backend that is SASL and BrowserID
        savy. Uses session to maintain assertion over multiple
        requests.
        """
        if not (request and assertion):
            return None
        store_assertion(request, assertion)

        directory = UserSession(request)
        with statsd.timer('larper.sasl_bind_time'):
            (registered, details) = _get_registered_user(directory, request)

        if registered:
            person = directory.get_by_unique_id(details)
            defaults = dict(username=person.username,
                            first_name=person.first_name,
                            last_name=person.last_name,
                            email=person.username)
            user, created = User.objects.get_or_create(
                username=person.username, defaults=defaults)
            if created:
                user.set_unusable_password()
                user.save()
            return user
        return None
Exemple #4
0
        def _view(request, *args, **kwargs):
            (asst_hsh, assertion) = get_assertion(request)
            if not asst_hsh or not assertion:
                log.info("No assertion in session")
                return _redirect(request, login_url, redirect_field_name)

            try:
                directory = UserSession(request)
                (registered, unique_id) = directory.registered_user()
            except ldap.OTHER:
                statsd.incr('browserid.session_timedout')
                log.info("Backend session timed out, clearing session assertion")
                return _redirect(request, login_url, redirect_field_name)
            return view_func(request, *args, **kwargs)
Exemple #5
0
        def _view(request, *args, **kwargs):
            (asst_hsh, assertion) = get_assertion(request)
            if not asst_hsh or not assertion:
                log.info("No assertion in session")
                return _redirect(request, login_url, redirect_field_name)

            try:
                directory = UserSession(request)
                (registered, unique_id) = directory.registered_user()
            except ldap.OTHER:
                statsd.incr('browserid.session_timedout')
                log.info(
                    "Backend session timed out, clearing session assertion")
                return _redirect(request, login_url, redirect_field_name)
            return view_func(request, *args, **kwargs)
Exemple #6
0
def _profile(request, person, use_master):
    vouch_form = None
    ldap = UserSession.connect(request)

    if person.voucher_unique_id:
        try:
            # Stale data okay
            person.voucher = ldap.get_by_unique_id(person.voucher_unique_id)
        except NO_SUCH_PERSON:
            # Bug#688788 Invalid voucher is okay
            person.voucher = BAD_VOUCHER
    elif request.user.unique_id != person.unique_id:
        voucher = request.user.unique_id
        vouch_form = forms.VouchForm(initial=dict(
                voucher=voucher,
                vouchee=person.unique_id))

    services = ldap.profile_service_ids(person.unique_id, use_master)
    person.irc_nickname = None
    if MOZILLA_IRC_SERVICE_URI in services:
        person.irc_nickname = services[MOZILLA_IRC_SERVICE_URI]
        del services[MOZILLA_IRC_SERVICE_URI]

    return jingo.render(request, 'phonebook/profile.html',
                        dict(absolutify=absolutify,
                             person=person,
                             vouch_form=vouch_form,
                             services=services))
Exemple #7
0
def _profile(request, person, use_master):
    vouch_form = None
    ldap = UserSession.connect(request)

    if person.voucher_unique_id or cache.get('vouched_' + person.unique_id):
        try:
            # Stale data okay
            person.voucher = ldap.get_by_unique_id(person.voucher_unique_id)
        except NO_SUCH_PERSON:
            # Bug#688788 Invalid voucher is okay
            person.voucher = BAD_VOUCHER
    elif request.user.unique_id != person.unique_id:
        voucher = request.user.unique_id
        vouch_form = forms.VouchForm(initial=dict(
                vouchee=person.unique_id))

    services = ldap.profile_service_ids(person.unique_id, use_master)
    person.irc_nickname = None
    if MOZILLA_IRC_SERVICE_URI in services:
        person.irc_nickname = services[MOZILLA_IRC_SERVICE_URI]
        del services[MOZILLA_IRC_SERVICE_URI]

    # Get user groups from their profile.
    groups = person.get_profile().groups.all()

    data = dict(person=person, vouch_form=vouch_form, services=services,
                groups=groups)
    return render(request, 'phonebook/profile.html', data)
Exemple #8
0
    def vouch_person(self, new_unique_id):
        request = _mock_request('/en-US/', username='******')
        directory = self.d = UserSession.connect(request)

        ok_(directory.record_vouch('7f3a67u000001', new_unique_id))
        newbie = directory.get_by_unique_id(new_unique_id)
        eq_('7f3a67u000001', newbie.voucher_unique_id)
Exemple #9
0
 def f():
     if not hasattr(user, 'person'):
         directory = UserSession.connect(request)
         # Stale data okay
         user.person = directory.get_by_unique_id(user.unique_id)
     # Presence of voucher DN is enough, don't validate
     return bool(user.person.voucher_unique_id)
Exemple #10
0
def _profile(request, person, use_master):
    vouch_form = None
    ldap = UserSession.connect(request)
    profile = person.get_profile()

    # TODO: rely more on db for this test
    if not profile.is_vouched and request.user.unique_id != person.unique_id:
        vouch_form = forms.VouchForm(initial=dict(vouchee=person.unique_id))

    services = ldap.profile_service_ids(person.unique_id, use_master)

    person.irc_nickname = None
    if MOZILLA_IRC_SERVICE_URI in services:
        person.irc_nickname = services[MOZILLA_IRC_SERVICE_URI]
        del services[MOZILLA_IRC_SERVICE_URI]

    # Get user groups from their profile.
    groups = person.get_profile().groups.all()

    data = dict(person=person,
                profile=profile,
                vouch_form=vouch_form,
                services=services,
                groups=groups)
    return render(request, 'phonebook/profile.html', data)
Exemple #11
0
def _with_temp_user(fn):
    """
    Runs a function in the context of a newly created user.
    It will cleanup the user after fn is run, unless it
    has already been deleted.

    fn - A callable function. First parameter should be
    a unique_id string.
    """
    regi = RegistrarSession.connect(_mock_request('/en-US/search?q=David'))
    username = '******' % str(uuid4())[0:8]
    data = dict(first_name='Jane',
                last_name='Doe',
                email=username,
                password='******',
                biography='Keeping it real.',
                irc_nickname='',
                irc_nickname_unique_id='')
    new_unique_id = regi.create_person(data)
    fn(new_unique_id)

    directory = UserSession.connect(_mock_request('/en-US/search?q=David'))
    try:
        directory.get_by_unique_id(new_unique_id)

        admin = AdminSession.connect(_mock_request('/en-US/search?q=David'))
        admin.delete_person(new_unique_id)
    except:
        pass
    finally:
        pass
Exemple #12
0
def _with_temp_user(fn):
    """
    Runs a function in the context of a newly created user.
    It will cleanup the user after fn is run, unless it
    has already been deleted.

    fn - A callable function. First parameter should be
    a unique_id string.
    """
    regi = RegistrarSession.connect(
        _mock_request('/en-US/search?q=David'))
    username = '******' % str(uuid4())[0:8]
    data = dict(first_name='Jane', last_name='Doe',
                email=username, password='******',
                biography='Keeping it real.',
                         irc_nickname='',
                         irc_nickname_unique_id='')
    new_unique_id = regi.create_person(data)
    fn(new_unique_id)

    directory = UserSession.connect(_mock_request('/en-US/search?q=David'))
    try:
        directory.get_by_unique_id(new_unique_id)

        admin = AdminSession.connect(_mock_request('/en-US/search?q=David'))
        admin.delete_person(new_unique_id)
    except:
        pass
    finally:
        pass
Exemple #13
0
    def test_update_person(self):
        unique_id = '7f3a67u000098'
        username = '******'
        request = _mock_request('/en-US/search?q=David',
                                username=username,
                                unique_id='7f3a67u000098')

        directory = self.d = UserSession.connect(request)

        amandeep = directory.get_by_unique_id(unique_id)
        first_name = amandeep.first_name
        last_name = amandeep.last_name
        eq_('Amandeep', first_name)
        eq_('McIlrath', last_name)
        eq_('Amandeep McIlrath', amandeep.full_name)

        form_data = dict(first_name='Deep',
                         last_name=last_name,
                         biography='',
                         irc_nickname='',
                         irc_nickname_unique_id='',)

        ok_(directory.update_person(unique_id, form_data))

        amandeep = directory.get_by_unique_id(unique_id)
        eq_('Deep', amandeep.first_name, 'First name edit worked')
        eq_(last_name, amandeep.last_name, 'No change')

        form_data['first_name'] = first_name
        ok_(directory.update_person(unique_id, form_data))
        amandeep = directory.get_by_unique_id(unique_id)
        eq_(first_name, amandeep.first_name)
Exemple #14
0
    def vouch_person(self, new_unique_id):
        request = _mock_request('/en-US/', username='******')
        directory = self.d = UserSession.connect(request)

        ok_(larper.record_vouch('7f3a67u000001', new_unique_id))
        newbie = directory.get_by_unique_id(new_unique_id)
        eq_('7f3a67u000001', newbie.voucher_unique_id)
Exemple #15
0
    def test_update_person(self):
        unique_id = '7f3a67u000098'
        username = '******'
        request = _mock_request('/en-US/search?q=David',
                                username=username,
                                unique_id='7f3a67u000098')

        directory = self.d = UserSession.connect(request)

        amandeep = directory.get_by_unique_id(unique_id)
        first_name = amandeep.first_name
        last_name = amandeep.last_name
        eq_('Amandeep', first_name)
        eq_('McIlrath', last_name)
        eq_('Amandeep McIlrath', amandeep.full_name)

        form_data = dict(
            first_name='Deep',
            last_name=last_name,
            biography='',
            irc_nickname='',
            irc_nickname_unique_id='',
        )

        ok_(directory.update_person(unique_id, form_data))

        amandeep = directory.get_by_unique_id(unique_id)
        eq_('Deep', amandeep.first_name, 'First name edit worked')
        eq_(last_name, amandeep.last_name, 'No change')

        form_data['first_name'] = first_name
        ok_(directory.update_person(unique_id, form_data))
        amandeep = directory.get_by_unique_id(unique_id)
        eq_(first_name, amandeep.first_name)
Exemple #16
0
def photo(request, unique_id):
    ldap = UserSession.connect(request)
    image = ldap.profile_photo(unique_id)
    if image:
        return HttpResponse(image, mimetype="image/jpeg")
    else:
        return redirect('/media/img/unknown.png')
Exemple #17
0
    def test_person_with_no_given_name(self):
        request = _mock_request('/en-US/')
        directory = self.d = UserSession.connect(request)
        matt = directory.get_by_unique_id("7f3a67u000002")

        eq_('*****@*****.**', matt.username)
        eq_('7f3a67u000002', matt.unique_id)
        eq_('', matt.first_name)
Exemple #18
0
    def test_person_with_no_given_name(self):
        request = _mock_request('/en-US/')
        directory = self.d = UserSession.connect(request)
        matt = directory.get_by_unique_id("7f3a67u000002")

        eq_('*****@*****.**', matt.username)
        eq_('7f3a67u000002', matt.unique_id)
        eq_('', matt.first_name)
Exemple #19
0
    def test_search_is_fun(self):
        request = _mock_request('/en-US/search?q=David')
        directory = self.d = UserSession.connect(request)
        rs = directory.search("Bridget Hill")
        eq_(1, len(rs))

        rs = directory.search("*****@*****.**")
        eq_(1, len(rs))
Exemple #20
0
    def test_search_is_fun(self):
        request = _mock_request('/en-US/search?q=David')
        directory = self.d = UserSession.connect(request)
        rs = directory.search("Bridget Hill")
        eq_(1, len(rs))

        rs = directory.search("*****@*****.**")
        eq_(1, len(rs))
Exemple #21
0
 def test_search_by_irc_nick(self):
     request = _mock_request('/en-US/')
     directory = UserSession.connect(request)
     rs = directory.search("andrew_f")
     eq_(1, len(rs))
     person = rs[0]
     eq_('Andrew Findlay', person.full_name)
     eq_('8', person.unique_id)
Exemple #22
0
def vouch(request):
    form = forms.VouchForm(request.POST)
    if form.is_valid():
        ldap = UserSession.connect(request)
        data = form.cleaned_data
        vouchee = data.get('vouchee')
        ldap.record_vouch(data.get('voucher'), vouchee)
        return redirect(reverse('profile', args=[vouchee]))
Exemple #23
0
 def test_search_by_irc_nick(self):
     request = _mock_request('/en-US/')
     directory = UserSession.connect(request)
     rs = directory.search("andrew_f")
     eq_(1, len(rs))
     person = rs[0]
     eq_('Andrew Findlay', person.full_name)
     eq_('8', person.unique_id)
Exemple #24
0
def search(request):
    limit = None
    nonvouched_only = False
    people = []
    size_exceeded = False
    show_pagination = False
    form = forms.SearchForm(request.GET)

    if form.is_valid():
        query = form.cleaned_data.get('q', '')
        limit = form.cleaned_data['limit']
        nonvouched_only = form.cleaned_data['nonvouched_only']

        if request.user.is_authenticated():
            ldap = UserSession.connect(request)
            try:
                # Stale data okay
                sortk = attrgetter('full_name')
                people = sorted(ldap.search(query,
                                            nonvouched_only=nonvouched_only),
                                key=sortk)

                # Search based on group name as well
                groups = Group.objects.filter(name__icontains=query)[:limit]
                for group in groups:
                    for user in users_from_groups(
                            request,
                            group,
                            limit=forms.PAGINATION_LIMIT,
                            nonvouched_only=nonvouched_only):
                        if not user.unique_id in [p.unique_id for p in people]:
                            people.append(user)

                paginator = Paginator(people, limit)
                page = request.GET.get('page', 1)
                try:
                    people = paginator.page(page)
                except PageNotAnInteger:
                    people = paginator.page(1)
                except EmptyPage:
                    people = paginator.page(paginator.num_pages)

                if paginator.count > forms.PAGINATION_LIMIT:
                    show_pagination = True

            except SIZELIMIT_EXCEEDED:
                size_exceeded = True

            if len(people) == 1 and not show_pagination:
                return redirect(reverse('profile', args=[people[0].unique_id]))

    d = dict(people=people,
             form=form,
             limit=limit,
             nonvouched_only=nonvouched_only,
             show_pagination=show_pagination,
             size_exceeded_error=size_exceeded)
    return render(request, 'phonebook/search.html', d)
Exemple #25
0
def photo(request, unique_id):
    needs_master = (request.user.unique_id == unique_id)

    ldap = UserSession.connect(request)
    image = ldap.profile_photo(unique_id, use_master=needs_master)
    if image:
        return HttpResponse(image, mimetype="image/jpeg")
    else:
        return redirect('/media/img/unknown.png')
Exemple #26
0
def search(request):
    limit = None
    nonvouched_only = False
    people = []
    size_exceeded = False
    show_pagination = False
    form = forms.SearchForm(request.GET)

    if form.is_valid():
        query = form.cleaned_data.get("q", "")
        limit = form.cleaned_data["limit"]
        nonvouched_only = form.cleaned_data["nonvouched_only"]

        if request.user.is_authenticated():
            ldap = UserSession.connect(request)
            try:
                # Stale data okay
                sortk = attrgetter("full_name")
                people = sorted(ldap.search(query, nonvouched_only=nonvouched_only), key=sortk)

                # Search based on group name as well
                groups = Group.objects.filter(name__icontains=query)[:limit]
                for group in groups:
                    for user in users_from_groups(
                        request, group, limit=forms.PAGINATION_LIMIT, nonvouched_only=nonvouched_only
                    ):
                        if not user.unique_id in [p.unique_id for p in people]:
                            people.append(user)

                paginator = Paginator(people, limit)
                page = request.GET.get("page", 1)
                try:
                    people = paginator.page(page)
                except PageNotAnInteger:
                    people = paginator.page(1)
                except EmptyPage:
                    people = paginator.page(paginator.num_pages)

                if paginator.count > forms.PAGINATION_LIMIT:
                    show_pagination = True

            except SIZELIMIT_EXCEEDED:
                size_exceeded = True

            if len(people) == 1 and not show_pagination:
                return redirect(reverse("profile", args=[people[0].unique_id]))

    d = dict(
        people=people,
        form=form,
        limit=limit,
        nonvouched_only=nonvouched_only,
        show_pagination=show_pagination,
        size_exceeded_error=size_exceeded,
    )
    return render(request, "phonebook/search.html", d)
Exemple #27
0
    def test_connection_pooling(self):
        # Don't use _mock_request, nor TestLarper since we want full control
        # over the request to find pooling bugs
        rf = RequestFactory()
        request = rf.get('/en-US')
        request.session = {}
        request.user = MockUser('*****@*****.**', '7f3a67u000001')

        larper.store_password(request, 'secret')

        R = larper.READ
        W = larper.WRITE

        directory = UserSession.connect(request)
        self.assertFalse(hasattr(request, 'larper_conns'))

        regi = RegistrarSession.connect(request)
        self.assertFalse(hasattr(request, 'larper_conns'))

        regi_W_conn = regi._ensure_conn(W)
        regi_W_conn2 = regi._ensure_conn(W)

        self.assertIs(regi_W_conn, regi_W_conn2)
        self.assertTrue(hasattr(request, 'larper_conns'))
        self.assertEqual(len(request.larper_conns[R].keys()), 0)
        self.assertEqual(len(request.larper_conns[W].keys()), 1)

        dir_W_conn = directory._ensure_conn(W)
        dir_W_conn2 = directory._ensure_conn(W)

        self.assertIs(dir_W_conn, dir_W_conn2)
        self.assertEqual(len(request.larper_conns[R].keys()), 0)
        self.assertEqual(len(request.larper_conns[W].keys()), 2)

        dir_R_conn = directory._ensure_conn(R)

        admin = AdminSession.connect(request)
        admin_R_conn = admin._ensure_conn(R)
        admin_R_conn2 = admin._ensure_conn(R)
        admin_W_conn = admin._ensure_conn(W)

        self.assertIs(admin_R_conn, admin_R_conn2)
        self.assertIsNot(admin_R_conn, admin_W_conn)

        for conn in (regi_W_conn, dir_R_conn, admin_R_conn, admin_W_conn):
            # nor is it dir_R_conn2 or admin_R_conn2
            self.assertIsNot(dir_W_conn, conn)

        self.assertEqual(len(request.larper_conns[R].keys()), 2)
        self.assertEqual(len(request.larper_conns[W].keys()), 3)

        directory.disconnect(request)

        self.assertEqual(len(request.larper_conns[R].keys()), 0)
        self.assertEqual(len(request.larper_conns[W].keys()), 0)
Exemple #28
0
    def test_connection_pooling(self):
        # Don't use _mock_request, nor TestLarper since we want full control
        # over the request to find pooling bugs
        rf = RequestFactory()
        request = rf.get('/en-US')
        request.session = {}
        request.user = MockUser('*****@*****.**', '7f3a67u000001')

        larper.store_password(request, 'secret')

        R = larper.READ
        W = larper.WRITE

        directory = UserSession.connect(request)
        self.assertFalse(hasattr(request, 'larper_conns'))

        regi = RegistrarSession.connect(request)
        self.assertFalse(hasattr(request, 'larper_conns'))

        regi_W_conn = regi._ensure_conn(W)
        regi_W_conn2 = regi._ensure_conn(W)

        self.assertIs(regi_W_conn, regi_W_conn2)
        self.assertTrue(hasattr(request, 'larper_conns'))
        self.assertEqual(len(request.larper_conns[R].keys()), 0)
        self.assertEqual(len(request.larper_conns[W].keys()), 1)

        dir_W_conn = directory._ensure_conn(W)
        dir_W_conn2 = directory._ensure_conn(W)

        self.assertIs(dir_W_conn, dir_W_conn2)
        self.assertEqual(len(request.larper_conns[R].keys()), 0)
        self.assertEqual(len(request.larper_conns[W].keys()), 2)

        dir_R_conn = directory._ensure_conn(R)

        admin = AdminSession.connect(request)
        admin_R_conn = admin._ensure_conn(R)
        admin_R_conn2 = admin._ensure_conn(R)
        admin_W_conn = admin._ensure_conn(W)

        self.assertIs(admin_R_conn, admin_R_conn2)
        self.assertIsNot(admin_R_conn, admin_W_conn)

        for conn in (regi_W_conn, dir_R_conn, admin_R_conn, admin_W_conn):
            # nor is it dir_R_conn2 or admin_R_conn2
            self.assertIsNot(dir_W_conn, conn)

        self.assertEqual(len(request.larper_conns[R].keys()), 2)
        self.assertEqual(len(request.larper_conns[W].keys()), 3)

        directory.disconnect(request)

        self.assertEqual(len(request.larper_conns[R].keys()), 0)
        self.assertEqual(len(request.larper_conns[W].keys()), 0)
Exemple #29
0
def photo(request, unique_id):
    needs_master = request.user.unique_id == unique_id

    ldap = UserSession.connect(request)
    image = ldap.profile_photo(unique_id, use_master=needs_master)
    if image:
        return HttpResponse(image, mimetype="image/jpeg")
    else:
        # If gravatar has no image, it will return this image.
        default = "http://%s/media/img/unknown.png" % request.get_host()
        email = ldap.get_by_unique_id(unique_id, needs_master).username
        return redirect(gravatar(email, default))
Exemple #30
0
def _edit_profile(request, new_account):
    ldap = UserSession.connect(request)
    unique_id = request.user.unique_id
    try:
        person = ldap.get_by_unique_id(unique_id, use_master=True)
    except NO_SUCH_PERSON:
        log.info("profile_uid Sending 404 for [%s]" % unique_id)
        raise Http404

    del_form = forms.DeleteForm(initial=dict(unique_id=unique_id))

    if not person:
        raise Http404

    if request.user.unique_id != person.unique_id:
        return HttpResponseForbidden()

    profile = request.user.get_profile()
    user_groups = stringify_groups(profile.groups.all().order_by("name"))

    if request.method == "POST":
        form = forms.ProfileForm(request.POST, request.FILES)
        if form.is_valid():
            # Save both LDAP and RDBS data via our ProfileForm
            ldap.update_person(unique_id, form.cleaned_data)
            ldap.update_profile_photo(unique_id, form.cleaned_data)

            form.save(request, ldap)

            return redirect(reverse("confirm_register") if new_account else reverse("profile", args=[unique_id]))
    else:
        initial = dict(
            first_name=person.first_name,
            last_name=person.last_name,
            biography=person.biography,
            website=profile.website,
            groups=user_groups,
        )

        initial.update(_get_services_fields(ldap, unique_id, use_master=True))
        form = forms.ProfileForm(initial=initial)

    d = dict(
        form=form,
        edit_form_action=reverse("phonebook.edit_profile"),
        delete_form=del_form,
        person=person,
        email=person.username,
        registration_flow=new_account,
        user_groups=user_groups,
        photo=ldap.profile_photo(unique_id, use_master=True),
    )
    return render(request, "phonebook/edit_profile.html", d)
Exemple #31
0
def profile_uid(request, unique_id):
    """
    View a profile by unique_id, which is a stable,
    random user id.
    """
    ldap = UserSession.connect(request)
    try:
        person = ldap.get_by_unique_id(unique_id)
        if person.last_name:
            return _profile(request, person)
    except NO_SUCH_PERSON:
        raise Http404
Exemple #32
0
def _edit_profile(request, new_account):
    ldap = UserSession.connect(request)
    unique_id = request.user.unique_id
    try:
        person = ldap.get_by_unique_id(unique_id, use_master=True)
    except NO_SUCH_PERSON:
        log.info('profile_uid Sending 404 for [%s]' % unique_id)
        raise Http404

    del_form = forms.DeleteForm(initial=dict(unique_id=unique_id))

    if not person:
        raise Http404

    if request.user.unique_id != person.unique_id:
        return HttpResponseForbidden()

    profile = request.user.get_profile()
    user_groups = stringify_groups(profile.groups.all().order_by('name'))

    if request.method == 'POST':
        form = forms.ProfileForm(request.POST, request.FILES)
        if form.is_valid():
            # Save both LDAP and RDBS data via our ProfileForm
            ldap.update_person(unique_id, form.cleaned_data)
            ldap.update_profile_photo(unique_id, form.cleaned_data)

            form.save(request, ldap)

            return redirect(
                reverse('confirm_register')
                if new_account else reverse('profile', args=[unique_id]))
    else:
        initial = dict(first_name=person.first_name,
                       last_name=person.last_name,
                       biography=person.biography,
                       website=profile.website,
                       groups=user_groups)

        initial.update(_get_services_fields(ldap, unique_id, use_master=True))
        form = forms.ProfileForm(initial=initial)

    d = dict(
        form=form,
        edit_form_action=reverse('phonebook.edit_profile'),
        delete_form=del_form,
        person=person,
        email=person.username,
        registration_flow=new_account,
        user_groups=user_groups,
        photo=ldap.profile_photo(unique_id, use_master=True),
    )
    return render(request, 'phonebook/edit_profile.html', d)
Exemple #33
0
def photo(request, unique_id):
    needs_master = (request.user.unique_id == unique_id)

    ldap = UserSession.connect(request)
    image = ldap.profile_photo(unique_id, use_master=needs_master)
    if image:
        return HttpResponse(image, mimetype="image/jpeg")
    else:
        # If gravatar has no image, it will return this image.
        default = 'http://%s/media/img/unknown.png' % request.get_host()
        email = ldap.get_by_unique_id(unique_id, needs_master).username
        return redirect(gravatar(email, default))
Exemple #34
0
def profile_uid(request, unique_id):
    """View a profile by unique_id, which is a stable, random user id."""
    needs_master = request.user.unique_id == unique_id
    ldap = UserSession.connect(request)
    try:
        # Stale data okay when viewing others
        person = ldap.get_by_unique_id(unique_id, needs_master)
        if person.last_name:
            return _profile(request, person, needs_master)
    except NO_SUCH_PERSON:
        log.warning("profile_uid Sending 404 for [%s]" % unique_id)
        raise Http404
Exemple #35
0
def profile_uid(request, unique_id):
    """View a profile by unique_id, which is a stable, random user id."""
    needs_master = (request.user.unique_id == unique_id)
    ldap = UserSession.connect(request)
    try:
        # Stale data okay when viewing others
        person = ldap.get_by_unique_id(unique_id, needs_master)
        if person.last_name:
            return _profile(request, person, needs_master)
    except NO_SUCH_PERSON:
        log.warning('profile_uid Sending 404 for [%s]' % unique_id)
        raise Http404
Exemple #36
0
def profile_photo(context, person):
    user = context['request'].user
    me = bool(user.username == person.username)
    url = reverse('phonebook.profile_photo', args=[person.unique_id])

    if me:
        url += '?%d' % int(time.time())

    needs_master = (user.unique_id == person.unique_id)
    ldap = UserSession.connect(context['request'])
    image = ldap.profile_photo(person.unique_id, use_master=needs_master)

    return dict(image_url=url, gravatar=not image)
Exemple #37
0
def profile_photo(context, person):
    user = context['request'].user
    me = bool(user.username == person.username)
    url = reverse('phonebook.profile_photo', args=[person.unique_id])

    if me:
        url += '?%d' % int(time.time())

    needs_master = (user.unique_id == person.unique_id)
    ldap = UserSession.connect(context['request'])
    image = ldap.profile_photo(person.unique_id, use_master=needs_master)

    return dict(image_url=url, gravatar=not image)
Exemple #38
0
    def test_person_api(self):
        request = _mock_request('/en-US/search?q=David')
        directory = self.d = UserSession.connect(request)
        rs = directory.search("Bridget Hill")
        eq_(1, len(rs))
        bridget = rs[0]
        eq_('*****@*****.**', bridget.username)
        eq_('7f3a67u000001', bridget.unique_id)
        eq_('Bridget', bridget.first_name)
        eq_('Hill', bridget.last_name)
        eq_('Bridget Hill', bridget.full_name)
        eq_('7f3a67u000002', bridget.voucher_unique_id)

        eq_(None, bridget.biography)
Exemple #39
0
    def test_person_api(self):
        request = _mock_request('/en-US/search?q=David')
        directory = self.d = UserSession.connect(request)
        rs = directory.search("Bridget Hill")
        eq_(1, len(rs))
        bridget = rs[0]
        eq_('*****@*****.**', bridget.username)
        eq_('7f3a67u000001', bridget.unique_id)
        eq_('Bridget', bridget.first_name)
        eq_('Hill', bridget.last_name)
        eq_('Bridget Hill', bridget.full_name)
        eq_('7f3a67u000002', bridget.voucher_unique_id)

        eq_(None, bridget.biography)
Exemple #40
0
def search(request):
    limit = None
    people = []
    size_exceeded = False
    show_pagination = False
    form = forms.SearchForm(request.GET)

    if form.is_valid():
        query = form.cleaned_data.get('q', '')
        limit = form.cleaned_data['limit']

        if request.user.is_authenticated():
            ldap = UserSession.connect(request)
            try:
                # Stale data okay
                sortk = attrgetter('full_name')
                people = sorted(ldap.search(query), key=sortk)

                # Search based on group name as well
                groups = Group.objects.filter(name__icontains=query)[:limit]
                for group in groups:
                    for user in users_from_groups(request, group,
                            limit=forms.PAGINATION_LIMIT):
                        if not user.unique_id in [p.unique_id for p in people]:
                            people.append(user)

                paginator = Paginator(people, limit)
                page = request.GET.get('page', 1)
                try:
                    people = paginator.page(page)
                except PageNotAnInteger:
                    people = paginator.page(1)
                except EmptyPage:
                    people = paginator.page(paginator.num_pages)

                if paginator.count > forms.PAGINATION_LIMIT:
                    show_pagination = True

            except SIZELIMIT_EXCEEDED:
                size_exceeded = True
    d = dict(people=people,
             form=form,
             limit=limit,
             show_pagination=show_pagination,
             size_exceeded_error=size_exceeded)
    return render(request, 'phonebook/search.html', d)
Exemple #41
0
def search(request):
    people = []
    size_exceeded = False
    form = forms.SearchForm(request.GET)
    if form.is_valid():
        query = form.cleaned_data.get('q', '')
        if request.user.is_authenticated():
            ldap = UserSession.connect(request)
            try:
                people = ldap.search(query)
            except SIZELIMIT_EXCEEDED:
                size_exceeded = True

    return jingo.render(request, 'phonebook/search.html',
                        dict(people=people,
                             form=form,
                             size_exceeded_error=size_exceeded))
Exemple #42
0
def users_from_groups(context, groups, limit=None, nonvouched_only=False):
    """Return all Person objects of users in the Group QuerySet.

    This helper exists because of our mixed datastore environment."""
    profiles = groups.userprofile_set.all()
    if limit:
        profiles = profiles[:limit]

    users = User.objects.filter(id__in=[p.user_id for p in profiles])
    ldap = UserSession.connect(context)

    ldap_users = []
    for u in users:
        # We have to walk this so we don't hit LDAP's HARD LIMIT.
        search_result = ldap.search_by_email(u.email, nonvouched_only)
        if search_result:
            ldap_users.append(search_result[0])

    return ldap_users
Exemple #43
0
def users_from_groups(context, groups, limit=None):
    """Return all Person objects of users in the Group QuerySet.

    This helper exists because of our mixed datastore environment."""
    profiles = groups.userprofile_set.all()
    if limit:
        profiles = profiles[:limit]

    users = User.objects.filter(id__in=[p.user_id for p in profiles])
    ldap = UserSession.connect(context)

    ldap_users = []
    for u in users:
        # We have to walk this so we don't hit LDAP's HARD LIMIT.
        search_result = ldap.search_by_email(u.email)
        if search_result:
            ldap_users.append(search_result[0])

    return ldap_users
Exemple #44
0
def _profile(request, person, use_master):
    vouch_form = None
    ldap = UserSession.connect(request)
    profile = person.get_profile()

    # TODO: rely more on db for this test
    if not profile.is_vouched and request.user.unique_id != person.unique_id:
        vouch_form = forms.VouchForm(initial=dict(vouchee=person.unique_id))

    services = ldap.profile_service_ids(person.unique_id, use_master)

    person.irc_nickname = None
    if MOZILLA_IRC_SERVICE_URI in services:
        person.irc_nickname = services[MOZILLA_IRC_SERVICE_URI]
        del services[MOZILLA_IRC_SERVICE_URI]

    # Get user groups from their profile.
    groups = person.get_profile().groups.all()

    data = dict(person=person, profile=profile, vouch_form=vouch_form, services=services, groups=groups)
    return render(request, "phonebook/profile.html", data)
Exemple #45
0
    def test_create_then_delete_person(self):
        regi = self.d = RegistrarSession.connect(
            _mock_request('/en-US/search?q=David'))
        username = '******' % str(uuid4())[0:8]
        data = dict(first_name='Jane', last_name='Doe',
                    email=username, password='******',
                    biography='Keeping it real.',
                         irc_nickname='hobart',
                         irc_nickname_unique_id='')
        new_unique_id = regi.create_person(data)

        directory = UserSession.connect(
            _mock_request('/en-US/search?q=David'))
        newbie = directory.get_by_unique_id(new_unique_id)
        eq_(username, newbie.username)

        admin = AdminSession.connect(
            _mock_request('/en-US/search?q=David'))
        admin.delete_person(new_unique_id)

        self.assertRaises(larper.NO_SUCH_PERSON, lambda:\
                              directory.get_by_unique_id(new_unique_id))
Exemple #46
0
def vouch(request):
    """
    When a voucher approves a vouch for a vouchee, there
    can be a replication lag between master -> slave. As a
    result, there is a possibility that viewing the vouchee's
    profile will not show the updated state. So we currently
    will cache the state for immediate feedback.
    """
    form = forms.VouchForm(request.POST)
    if form.is_valid():
        ldap = UserSession.connect(request)
        data = form.cleaned_data
        vouchee = data.get('vouchee')
        ldap.record_vouch(request.user.unique_id, vouchee)
        cache.set('vouched_' + vouchee, True)

        # Notify the current user that they vouched successfully.
        msg = _(u'Thanks for vouching for a fellow Mozillian! '
                 'This user is now vouched!')
        messages.info(request, msg)

        return redirect(reverse('profile', args=[vouchee]))
Exemple #47
0
def _profile(request, person):
    vouch_form = None
    ldap = UserSession.connect(request)

    if person.voucher_unique_id:
        person.voucher = ldap.get_by_unique_id(person.voucher_unique_id)
    elif request.user.unique_id != person.unique_id:
        voucher = request.user.unique_id
        vouch_form = forms.VouchForm(initial=dict(
                voucher=voucher,
                vouchee=person.unique_id))

    services = ldap.profile_service_ids(person.unique_id)
    person.irc_nickname = None
    if MOZILLA_IRC_SERVICE_URI in services:
        person.irc_nickname = services[MOZILLA_IRC_SERVICE_URI]
        del services[MOZILLA_IRC_SERVICE_URI]

    return jingo.render(request, 'phonebook/profile.html',
                        dict(person=person,
                             vouch_form=vouch_form,
                             services=services))
Exemple #48
0
    def test_create_then_delete_person(self):
        regi = self.d = RegistrarSession.connect(
            _mock_request('/en-US/search?q=David'))
        username = '******' % str(uuid4())[0:8]
        data = dict(first_name='Jane',
                    last_name='Doe',
                    email=username,
                    password='******',
                    biography='Keeping it real.',
                    irc_nickname='hobart',
                    irc_nickname_unique_id='')
        new_unique_id = regi.create_person(data)

        directory = UserSession.connect(_mock_request('/en-US/search?q=David'))
        newbie = directory.get_by_unique_id(new_unique_id)
        eq_(username, newbie.username)

        admin = AdminSession.connect(_mock_request('/en-US/search?q=David'))
        admin.delete_person(new_unique_id)

        self.assertRaises(larper.NO_SUCH_PERSON, lambda:\
                              directory.get_by_unique_id(new_unique_id))
Exemple #49
0
def invite(request):
    if request.method == 'POST':
        f = forms.InviteForm(request.POST)
        if f.is_valid():
            ldap = UserSession.connect(request)
            unique_id = request.user.unique_id
            try:
                person = ldap.get_by_unique_id(unique_id, use_master=True)
            except NO_SUCH_PERSON:
                log.info('profile_uid Sending 404 for [%s]' % unique_id)
                raise Http404

            invite = f.save(commit=False)
            invite.inviter = request.user.unique_id
            invite.save()
            invite.send(sender=person)

            return HttpResponseRedirect(reverse(invited, args=[invite.id]))
    else:
        f = forms.InviteForm()
    data = dict(form=f, foo='bar')

    return render(request, 'phonebook/invite.html', data)
Exemple #50
0
 def test_search_by_email(self):
     request = _mock_request('/en-US/search?q=David')
     directory = self.d = UserSession.connect(request)
     davids = directory.search_by_email("*****@*****.**")
     ok_(len(davids) > 0)
Exemple #51
0
 def test_get_by_unique_id(self):
     request = _mock_request('/en-US/')
     directory = self.d = UserSession.connect(request)
     directory.get_by_unique_id("7f3a67u000002")
Exemple #52
0
 def process_response(self, request, response):
     UserSession.disconnect(request)
     return response
Exemple #53
0
 def test_get_by_unique_id_raises(self):
     request = _mock_request('/en-US/')
     directory = self.d = UserSession.connect(request)
     self.assertRaises(larper.NO_SUCH_PERSON, lambda:\
                           directory.get_by_unique_id("unknownid"))
Exemple #54
0
 def test_search_by_name(self):
     request = _mock_request('/en-US/search?q=David')
     directory = self.d = UserSession.connect(request)
     davids = directory.search_by_name("David")
     ok_(len(davids) > 0)
Exemple #55
0
 def tearDown(self):
     """ Simulates middleware teardown """
     global requests
     for r in requests:
         UserSession.disconnect(r)