def form_valid(self, form): """Custom form validation to support email changing. If user is already authenticated and reaches this points, it's an email changing procedure. Validate that email is good and save it in the database. Otherwise continue with the default django-browserid verification. """ if not self.request.user.is_authenticated(): return super(BrowserIDVerify, self).form_valid(form) failure_url = urlparams(reverse('phonebook:profile_edit'), bid_login_failed=1) self.assertion = form.cleaned_data['assertion'] self.audience = get_audience(self.request) result = verify(self.assertion, self.audience) if not result: messages.error(self.request, _('Authentication failed.')) return redirect(failure_url) email = result['email'] if User.objects.filter(email=email).exists(): messages.error(self.request, _('Email already exists in the database.')) return redirect('phonebook:logout') user = self.request.user user.email = email user.save() return redirect('phonebook:profile_view', user.username)
def edit_profile(request): """Edit user profile view.""" # Don't user request.user user = User.objects.get(pk=request.user.id) profile = user.userprofile user_groups = stringify_groups(profile.groups.all().order_by('name')) user_skills = stringify_groups(profile.skills.all().order_by('name')) user_languages = stringify_groups(profile.languages.all().order_by('name')) user_form = forms.UserForm(request.POST or None, instance=user) AccountsFormset = inlineformset_factory(UserProfile, ExternalAccount, extra=1) accounts_formset = AccountsFormset(request.POST or None, instance=profile) new_profile = False form = forms.ProfileForm if not profile.is_complete: new_profile = True form = forms.RegisterForm profile_form = form(request.POST or None, request.FILES or None, instance=profile, locale=request.locale, initial=dict(groups=user_groups, skills=user_skills, languages=user_languages)) email_form = forms.EmailForm(request.POST or None, initial={'email': request.user.email, 'user_id': request.user.id}) if (user_form.is_valid() and profile_form.is_valid() and accounts_formset.is_valid() and email_form.is_valid()): old_username = request.user.username user_form.save() profile_form.save() accounts_formset.save() # Notify the user that their old profile URL won't work. if new_profile: update_invites(request) messages.info(request, _(u'Your account has been created.')) elif user.username != old_username: messages.info(request, _(u'You changed your username; please note your ' 'profile URL has also changed.')) if email_form.email_changed(): return render(request, 'phonebook/verify_email.html', {'email': email_form.cleaned_data['email']}) return redirect('phonebook:profile_view', user.username) data = dict(profile_form=profile_form, user_form=user_form, accounts_formset = accounts_formset, email_form = email_form, user_groups=user_groups, my_vouches=UserProfile.objects.filter(vouched_by=profile), profile=request.user.userprofile, apps=user.apiapp_set.filter(is_active=True)) # If there are form errors, don't send a 200 OK. status = 400 if (profile_form.errors or user_form.errors) else 200 return render(request, 'phonebook/edit_profile.html', data, status=status)
def change_primary_email(request, email_pk): """Change primary email address.""" user = User.objects.get(pk=request.user.id) profile = user.userprofile alternate_emails = ExternalAccount.objects.filter(user=profile, type=ExternalAccount.TYPE_EMAIL) # Only email owner can change primary email if not alternate_emails.filter(pk=email_pk).exists(): raise Http404() alternate_email = alternate_emails.get(pk=email_pk) primary_email = user.email # Change primary email user.email = alternate_email.identifier # Turn primary email to alternate alternate_email.identifier = primary_email with transaction.atomic(): user.save() alternate_email.save() return redirect('phonebook:profile_edit')
def delete_apikey(request, api_pk): api_key = get_object_or_404(APIv2App, pk=api_pk, owner=request.user.userprofile) api_key.delete() messages.success(request, _('API key successfully deleted.')) return redirect('phonebook:apikeys')
def invite(request): profile = request.user.userprofile invite_form = None vouch_form = None if profile.can_vouch: invite_form = forms.InviteForm(request.POST or None, instance=Invite(inviter=profile)) vouch_form = forms.VouchForm(request.POST or None) if invite_form and vouch_form and invite_form.is_valid( ) and vouch_form.is_valid(): invite_form.instance.reason = vouch_form.cleaned_data['description'] invite = invite_form.save() invite.send(sender=profile, personal_message=invite_form.cleaned_data['message']) msg = _(u"%s has been invited to Mozillians. They'll receive an email " u"with instructions on how to join. You can " u"invite another Mozillian if you like.") % invite.recipient messages.success(request, msg) return redirect('phonebook:invite') return render( request, 'phonebook/invite.html', { 'invite_form': invite_form, 'vouch_form': vouch_form, 'invites': profile.invites.all(), 'vouch_threshold': settings.CAN_VOUCH_THRESHOLD, })
def change_primary_email(request, email_pk): """Change primary email address.""" user = User.objects.get(pk=request.user.id) profile = user.userprofile alternate_emails = ExternalAccount.objects.filter( user=profile, type=ExternalAccount.TYPE_EMAIL) # Only email owner can change primary email if not alternate_emails.filter(pk=email_pk).exists(): raise Http404() alternate_email = alternate_emails.get(pk=email_pk) primary_email = user.email # Change primary email user.email = alternate_email.identifier # Turn primary email to alternate alternate_email.identifier = primary_email with transaction.atomic(): user.save() alternate_email.save() return redirect('phonebook:edit_emails')
def invite(request): profile = request.user.userprofile invite_form = None vouch_form = None if profile.can_vouch: invite_form = forms.InviteForm(request.POST or None, instance=Invite(inviter=profile)) vouch_form = forms.VouchForm(request.POST or None) if invite_form and vouch_form and invite_form.is_valid() and vouch_form.is_valid(): invite_form.instance.reason = vouch_form.cleaned_data['description'] invite = invite_form.save() invite.send(sender=profile, personal_message=invite_form.cleaned_data['message']) msg = _(u"%s has been invited to Mozillians. They'll receive an email " u"with instructions on how to join. You can " u"invite another Mozillian if you like.") % invite.recipient messages.success(request, msg) return redirect('phonebook:invite') return render(request, 'phonebook/invite.html', { 'invite_form': invite_form, 'vouch_form': vouch_form, 'invites': profile.invites.all(), 'vouch_threshold': settings.CAN_VOUCH_THRESHOLD, })
def view_profile(request, username): """View a profile by username.""" data = {} privacy_mappings = {'anonymous': PUBLIC, 'mozillian': MOZILLIANS, 'employee': EMPLOYEES, 'privileged': PRIVILEGED, 'myself': None} privacy_level = None if (request.user.is_authenticated() and request.user.username == username): # own profile view_as = request.GET.get('view_as', 'myself') privacy_level = privacy_mappings.get(view_as, None) profile = UserProfile.objects.privacy_level(privacy_level).get(user__username=username) data['privacy_mode'] = view_as else: userprofile_query = UserProfile.objects.filter(user__username=username) public_profile_exists = userprofile_query.public().exists() profile_exists = userprofile_query.exists() profile_complete = userprofile_query.exclude(full_name='').exists() if not public_profile_exists: if not request.user.is_authenticated(): # you have to be authenticated to continue messages.warning(request, LOGIN_MESSAGE) return (login_required(view_profile, login_url=reverse('phonebook:home')) (request, username)) if not request.user.userprofile.is_vouched: # you have to be vouched to continue messages.error(request, GET_VOUCHED_MESSAGE) return redirect('phonebook:home') if not profile_exists or not profile_complete: raise Http404 profile = UserProfile.objects.get(user__username=username) profile.set_instance_privacy_level(PUBLIC) if request.user.is_authenticated(): profile.set_instance_privacy_level( request.user.userprofile.privacy_level) if (not profile.is_vouched and request.user.is_authenticated() and request.user.userprofile.is_vouched): data['vouch_form'] = ( forms.VouchForm(initial={'vouchee': profile.pk})) data['shown_user'] = profile.user data['profile'] = profile data['groups'] = profile.get_annotated_groups() data['locale'] = request.locale # Only show pending groups if user is looking at their own profile, # or current user is a superuser if not (request.user.is_authenticated() and (request.user.username == username or request.user.is_superuser)): data['groups'] = [grp for grp in data['groups'] if not grp.pending] return render(request, 'phonebook/profile.html', data)
def view_profile(request, username): """View a profile by username.""" data = {} privacy_mappings = { "anonymous": PUBLIC, "mozillian": MOZILLIANS, "employee": EMPLOYEES, "privileged": PRIVILEGED, "myself": None, } privacy_level = None if request.user.is_authenticated() and request.user.username == username: # own profile view_as = request.GET.get("view_as", "myself") privacy_level = privacy_mappings.get(view_as, None) profile = UserProfile.objects.privacy_level(privacy_level).get(user__username=username) data["privacy_mode"] = view_as else: userprofile_query = UserProfile.objects.filter(user__username=username) public_profile_exists = userprofile_query.public().exists() profile_exists = userprofile_query.exists() profile_complete = userprofile_query.exclude(full_name="").exists() if not public_profile_exists: if not request.user.is_authenticated(): # you have to be authenticated to continue messages.warning(request, LOGIN_MESSAGE) return login_required(view_profile, login_url=reverse("phonebook:home"))(request, username) if not request.user.userprofile.is_vouched: # you have to be vouched to continue messages.error(request, GET_VOUCHED_MESSAGE) return redirect("phonebook:home") if not profile_exists or not profile_complete: raise Http404 profile = UserProfile.objects.get(user__username=username) profile.set_instance_privacy_level(PUBLIC) if request.user.is_authenticated(): profile.set_instance_privacy_level(request.user.userprofile.privacy_level) if not profile.is_vouched and request.user.is_authenticated() and request.user.userprofile.is_vouched: data["vouch_form"] = forms.VouchForm(initial={"vouchee": profile.pk}) data["shown_user"] = profile.user data["profile"] = profile data["groups"] = profile.get_annotated_groups() data["locale"] = request.locale # Only show pending groups if user is looking at their own profile, # or current user is a superuser if not (request.user.is_authenticated() and (request.user.username == username or request.user.is_superuser)): data["groups"] = [grp for grp in data["groups"] if not grp.pending] return render(request, "phonebook/profile.html", data)
def delete_invite(request, invite_pk): profile = request.user.userprofile deleted_invite = get_object_or_404(Invite, pk=invite_pk, inviter=profile, redeemed=None) deleted_invite.delete() msg = (_(u"%s's invitation to Mozillians has been revoked. " u"You can invite %s again if you like.") % (deleted_invite.recipient, deleted_invite.recipient)) messages.success(request, msg) return redirect('phonebook:invite')
def unvouch(request, username): """Automatically remove all vouches from username. This must be behind a waffle flag and activated only for testing purposes. """ profile = get_object_or_404(UserProfile, user__username=username) profile.vouches_received.all().delete() messages.success(request, _('Successfully unvouched user.')) return redirect('phonebook:profile_view', profile.user.username)
def delete_email(request, email_pk): """Delete alternate email address.""" user = User.objects.get(pk=request.user.id) profile = user.userprofile # Only email owner can delete emails if not ExternalAccount.objects.filter(user=profile, pk=email_pk).exists(): raise Http404() ExternalAccount.objects.get(pk=email_pk).delete() return redirect('phonebook:profile_edit')
def process_request(self, request): user = request.user path = request.path if settings.DEBUG: self.allow_urls.append(settings.MEDIA_URL) if (user.is_authenticated() and not user.userprofile.is_complete and not filter(lambda url: re.match(url, path), self.allow_urls)): messages.warning(request, _('Please complete registration before proceeding.')) return redirect('phonebook:profile_edit')
def delete_email(request, email_pk): """Delete alternate email address.""" user = User.objects.get(pk=request.user.id) profile = user.userprofile # Only email owner can delete emails if not ExternalAccount.objects.filter(user=profile, pk=email_pk).exists(): raise Http404() ExternalAccount.objects.get(pk=email_pk).delete() return redirect('phonebook:edit_emails')
def vouch(request, username): """Automatically vouch username. This must be behind a waffle flag and activated only for testing purposes. """ profile = get_object_or_404(UserProfile, user__username=username) now = timezone.now() description = 'Automatically vouched for testing purposes on {0}'.format(now) profile.vouch(None, description=description, autovouch=True) messages.success(request, _('Successfully vouched user.')) return redirect('phonebook:profile_view', profile.user.username)
def vouch(request): """Vouch a user.""" form = forms.VouchForm(request.POST) if form.is_valid(): p = UserProfile.objects.get(pk=form.cleaned_data.get("vouchee")) p.vouch(request.user.userprofile) # Notify the current user that they vouched successfully. msg = _(u"Thanks for vouching for a fellow Mozillian! " u"This user is now vouched!") messages.info(request, msg) return redirect("phonebook:profile_view", p.user.username) return HttpResponseBadRequest()
def search(request): num_pages = 0 limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) curated_groups = Group.get_curated() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect('phonebook:profile_view', people[0].user.username) show_pagination = paginator.count > settings.ITEMS_PER_PAGE d = dict(people=people, search_form=form, limit=limit, show_pagination=show_pagination, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def betasearch(request): """This view is for researching new search and data filtering options. It will eventually replace the 'search' view. This view is behind the 'betasearch' waffle flag. """ limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None functional_areas = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) functional_areas = Group.get_functional_areas() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect('phonebook:profile_view', people[0].user.username) show_pagination = paginator.count > settings.ITEMS_PER_PAGE d = dict(people=people, search_form=form, limit=limit, show_pagination=show_pagination, groups=groups, functional_areas=functional_areas) return render(request, 'phonebook/betasearch.html', d)
def vouch(request): """Vouch a user.""" form = forms.VouchForm(request.POST) if form.is_valid(): p = UserProfile.objects.get(pk=form.cleaned_data.get('vouchee')) p.vouch(request.user.userprofile) # Notify the current user that they vouched successfully. msg = _(u'Thanks for vouching for a fellow Mozillian! ' u'This user is now vouched!') messages.info(request, msg) return redirect('phonebook:profile_view', p.user.username) return HttpResponseBadRequest()
def invite(request): profile = request.user.userprofile invite_form = forms.InviteForm(request.POST or None, instance=Invite(inviter=profile)) if invite_form.is_valid(): invite = invite_form.save() invite.send(sender=profile, personal_message=invite_form.cleaned_data['message']) msg = _(u"%s has been invited to Mozillians. They'll receive an email " u"with instructions on how to join. You can " u"invite another Mozillian if you like.") % invite.recipient messages.success(request, msg) return redirect('phonebook:home') return render(request, 'phonebook/invite.html', {'invite_form': invite_form, 'invites': profile.invites.all()})
def invite(request): profile = request.user.userprofile invite_form = forms.InviteForm(request.POST or None, instance=Invite(inviter=profile)) if request.method == 'POST' and invite_form.is_valid(): invite = invite_form.save() invite.send(sender=profile) msg = _(u"%s has been invited to Mozillians. They'll receive an email " u"with instructions on how to join. You can " u"invite another Mozillian if you like." % invite.recipient) messages.success(request, msg) return redirect('phonebook:home') return render(request, 'phonebook/invite.html', {'invite_form': invite_form})
def process_request(self, request): user = request.user path = request.path allow_urls = [r'^/[\w-]+{0}'.format(reverse('phonebook:logout')), r'^/[\w-]+{0}'.format(reverse('phonebook:profile_edit')), r'^/browserid/', r'^/[\w-]+{0}'.format(reverse('phonebook:login')), r'^/[\w-]+/jsi18n/'] if settings.DEBUG: allow_urls.append(settings.MEDIA_URL) if (user.is_authenticated() and not user.userprofile.is_complete and not filter(lambda url: re.match(url, path), allow_urls)): messages.warning(request, _('Please complete registration before proceeding.')) return redirect('phonebook:profile_edit')
def register(request): """Registers Users. Pulls out an invite code if it exists and auto validates the user if so. Single-purpose view. """ # TODO already vouched users can be re-vouched? if 'code' in request.GET: request.session['invite-code'] = request.GET['code'] if request.user.is_authenticated(): if not request.user.userprofile.is_vouched: redeem_invite(request.user.userprofile, request.session['invite-code']) else: messages.info(request, _("You've been invited to join Mozillians.org! " "Sign in and then you can create a profile.")) return redirect('phonebook:home')
def edit_emails(request): """Edit alternate email addresses.""" user = User.objects.get(pk=request.user.id) profile = user.userprofile emails = ExternalAccount.objects.filter(type=ExternalAccount.TYPE_EMAIL) email_privacy_form = forms.EmailPrivacyForm(request.POST or None, instance=profile) alternate_email_formset = forms.AlternateEmailFormset(request.POST or None, instance=profile, queryset=emails) if alternate_email_formset.is_valid() and email_privacy_form.is_valid(): alternate_email_formset.save() email_privacy_form.save() return redirect('phonebook:edit_emails') return render(request, 'phonebook/edit_emails.html', {'alternate_email_formset': alternate_email_formset, 'email_privacy_form': email_privacy_form})
def invite(request): profile = request.user.userprofile invite_form = forms.InviteForm(request.POST or None, instance=Invite(inviter=profile)) if invite_form.is_valid(): invite = invite_form.save() invite.send(sender=profile, personal_message=invite_form.cleaned_data['message']) msg = _(u"%s has been invited to Mozillians. They'll receive an email " u"with instructions on how to join. You can " u"invite another Mozillian if you like.") % invite.recipient messages.success(request, msg) return redirect('phonebook:home') return render(request, 'phonebook/invite.html', { 'invite_form': invite_form, 'invites': profile.invites.all() })
def search(request): limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None functional_areas = None if form.is_valid(): query = form.cleaned_data.get("q", u"") limit = form.cleaned_data["limit"] include_non_vouched = form.cleaned_data["include_non_vouched"] page = request.GET.get("page", 1) functional_areas = Group.get_functional_areas() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect("phonebook:profile_view", people[0].user.username) show_pagination = paginator.count > settings.ITEMS_PER_PAGE d = dict( people=people, search_form=form, limit=limit, show_pagination=show_pagination, groups=groups, functional_areas=functional_areas, ) return render(request, "phonebook/search.html", d)
def apikeys(request): profile = request.user.userprofile apikey_request_form = forms.APIKeyRequestForm(request.POST or None, instance=APIv2App( enabled=True, owner=profile)) if apikey_request_form.is_valid(): apikey_request_form.save() msg = _(u'API Key generated successfully.') messages.success(request, msg) return redirect('phonebook:apikeys') data = { 'apps': request.user.apiapp_set.filter(is_active=True), 'appsv2': profile.apps.filter(enabled=True), 'apikey_request_form': apikey_request_form, } return render(request, 'phonebook/apikeys.html', data)
def apikeys(request): profile = request.user.userprofile apikey_request_form = forms.APIKeyRequestForm( request.POST or None, instance=APIv2App(enabled=True, owner=profile) ) if apikey_request_form.is_valid(): apikey_request_form.save() msg = _(u'API Key generated successfully.') messages.success(request, msg) return redirect('phonebook:apikeys') data = { 'apps': request.user.apiapp_set.filter(is_active=True), 'appsv2': profile.apps.filter(enabled=True), 'apikey_request_form': apikey_request_form, } return render(request, 'phonebook/apikeys.html', data)
def vouch(request, username): """Automatically vouch username. This must be behind a waffle flag and activated only for testing purposes. """ profile = get_object_or_404(UserProfile, user__username=username) now = timezone.now() description = 'Automatically vouched for testing purposes on {0}'.format(now) vouch = profile.vouch(None, description=description, autovouch=True) if vouch: messages.success(request, _('Successfully vouched user.')) else: msg = _('User not vouched. Maybe there are {0} vouches already?') msg = msg.format(settings.VOUCH_COUNT_LIMIT) messages.error(request, msg) return redirect('phonebook:profile_view', profile.user.username)
def process_request(self, request): user = request.user path = request.path allow_urls = [ r'^/[\w-]+{0}'.format(reverse('phonebook:logout')), r'^/[\w-]+{0}'.format(reverse('phonebook:profile_edit')), r'^/browserid/', r'^/[\w-]+{0}'.format(reverse('phonebook:login')), r'^/[\w-]+/jsi18n/' ] if settings.DEBUG: allow_urls.append(settings.MEDIA_URL) if (user.is_authenticated() and not user.userprofile.is_complete and not filter(lambda url: re.match(url, path), allow_urls)): messages.warning( request, _('Please complete registration ' 'before proceeding.')) return redirect('phonebook:profile_edit')
def process_view(self, request, view_func, view_args, view_kwargs): for view_url in self.exceptions: if re.match(view_url, request.path): return None allow_public = getattr(view_func, "_allow_public", None) if allow_public: return None if not request.user.is_authenticated(): messages.warning(request, LOGIN_MESSAGE) return login_required(view_func, login_url=reverse("phonebook:home"))(request, *view_args, **view_kwargs) if request.user.userprofile.is_vouched: return None allow_unvouched = getattr(view_func, "_allow_unvouched", None) if allow_unvouched: return None messages.error(request, GET_VOUCHED_MESSAGE) return redirect("phonebook:home")
def process_view(self, request, view_func, view_args, view_kwargs): for view_url in self.exceptions: if re.match(view_url, request.path): return None allow_public = getattr(view_func, '_allow_public', None) if allow_public: return None if not request.user.is_authenticated(): messages.warning(request, LOGIN_MESSAGE) return (login_required(view_func, login_url=reverse('phonebook:home'))( request, *view_args, **view_kwargs)) if request.user.userprofile.is_vouched: return None allow_unvouched = getattr(view_func, '_allow_unvouched', None) if allow_unvouched: return None messages.error(request, GET_VOUCHED_MESSAGE) return redirect('phonebook:home')
def edit_profile(request): """Edit user profile view.""" # Don't user request.user user = User.objects.get(pk=request.user.id) profile = user.userprofile user_groups = profile.groups.all().order_by('name') user_skills = stringify_groups(profile.skills.all().order_by('name')) user_form = forms.UserForm(request.POST or None, instance=user) queryset = ExternalAccount.objects.exclude(type=ExternalAccount.TYPE_EMAIL) accounts_formset = forms.AccountsFormset(request.POST or None, instance=profile, queryset=queryset) new_profile = False form = forms.ProfileForm language_formset = forms.LanguagesFormset(request.POST or None, instance=profile, locale=request.locale) if not profile.is_complete: new_profile = True form = forms.RegisterForm profile_form = form(request.POST or None, request.FILES or None, instance=profile, initial={ 'skills': user_skills, 'saveregion': True if profile.geo_region else False, 'savecity': True if profile.geo_city else False, 'lat': profile.lat, 'lng': profile.lng }) all_forms = [user_form, profile_form, accounts_formset, language_formset] # Using ``list`` to force calling is_valid on all the forms, even if earlier # ones are not valid, so we detect and display all the errors. if all(list(f.is_valid() for f in all_forms)): old_username = request.user.username user_form.save() profile_form.save() accounts_formset.save() language_formset.save() if new_profile: redeem_invite(profile, request.session.get('invite-code')) messages.info(request, _(u'Your account has been created.')) elif user.username != old_username: # Notify the user that their old profile URL won't work. messages.info( request, _(u'You changed your username; please note your ' u'profile URL has also changed.')) return redirect('phonebook:profile_view', user.username) data = dict(profile_form=profile_form, user_form=user_form, accounts_formset=accounts_formset, user_groups=user_groups, profile=request.user.userprofile, apps=user.apiapp_set.filter(is_active=True), language_formset=language_formset, vouch_threshold=settings.CAN_VOUCH_THRESHOLD, mapbox_id=settings.MAPBOX_PROFILE_ID) # If there are form errors, don't send a 200 OK. status = 400 if any(f.errors for f in all_forms) else 200 return render(request, 'phonebook/edit_profile.html', data, status=status)
def view_profile(request, username): """View a profile by username.""" data = {} privacy_mappings = {'anonymous': PUBLIC, 'mozillian': MOZILLIANS, 'employee': EMPLOYEES, 'privileged': PRIVILEGED, 'myself': None} privacy_level = None profile_is_vouchable = False if (request.user.is_authenticated() and request.user.username == username): # own profile view_as = request.GET.get('view_as', 'myself') privacy_level = privacy_mappings.get(view_as, None) profile = UserProfile.objects.privacy_level(privacy_level).get(user__username=username) data['privacy_mode'] = view_as else: userprofile_query = UserProfile.objects.filter(user__username=username) public_profile_exists = userprofile_query.public().exists() profile_exists = userprofile_query.exists() profile_complete = userprofile_query.exclude(full_name='').exists() if not public_profile_exists: if not request.user.is_authenticated(): # you have to be authenticated to continue messages.warning(request, LOGIN_MESSAGE) return (login_required(view_profile, login_url=reverse('phonebook:home')) (request, username)) if not request.user.userprofile.is_vouched: # you have to be vouched to continue messages.error(request, GET_VOUCHED_MESSAGE) return redirect('phonebook:home') if not profile_exists or not profile_complete: raise Http404 profile = UserProfile.objects.get(user__username=username) profile.set_instance_privacy_level(PUBLIC) if request.user.is_authenticated(): profile.set_instance_privacy_level( request.user.userprofile.privacy_level) if (request.user.is_authenticated() and profile.is_vouchable(request.user.userprofile)): profile_is_vouchable = True vouch_form = forms.VouchForm(request.POST or None) data['vouch_form'] = vouch_form if vouch_form.is_valid(): # We need to re-fetch profile from database. profile = UserProfile.objects.get(user__username=username) profile.vouch(request.user.userprofile, vouch_form.cleaned_data['description']) # 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('phonebook:profile_view', profile.user.username) data['profile_is_vouchable'] = profile_is_vouchable data['shown_user'] = profile.user data['profile'] = profile data['groups'] = profile.get_annotated_groups() data['locale'] = request.locale # Only show pending groups if user is looking at their own profile, # or current user is a superuser if not (request.user.is_authenticated() and (request.user.username == username or request.user.is_superuser)): data['groups'] = [grp for grp in data['groups'] if not grp.pending] return render(request, 'phonebook/profile.html', data)
def logout(request): """View that logs out the user and redirects to home page.""" auth_logout(request) return redirect('phonebook:home')
def edit_profile(request): """Edit user profile view.""" # Don't user request.user user = User.objects.get(pk=request.user.id) profile = user.userprofile user_groups = profile.groups.all().order_by("name") user_skills = stringify_groups(profile.skills.all().order_by("name")) user_form = forms.UserForm(request.POST or None, instance=user) accounts_formset = forms.AccountsFormset(request.POST or None, instance=profile) new_profile = False form = forms.ProfileForm language_formset = forms.LanguagesFormset(request.POST or None, instance=profile, locale=request.locale) if not profile.is_complete: new_profile = True form = forms.RegisterForm profile_form = form(request.POST or None, request.FILES or None, instance=profile, initial=dict(skills=user_skills)) email_form = forms.EmailForm( request.POST or None, initial={"email": request.user.email, "user_id": request.user.id} ) all_forms = [user_form, profile_form, accounts_formset, email_form, language_formset] # Using ``list`` to force calling is_valid on all the forms, even if earlier # ones are not valid, so we detect and display all the errors. if all(list(f.is_valid() for f in all_forms)): old_username = request.user.username user_form.save() profile_form.save() accounts_formset.save() language_formset.save() # Notify the user that their old profile URL won't work. if new_profile: redeem_invite(profile, request.session.get("invite-code")) messages.info(request, _(u"Your account has been created.")) elif user.username != old_username: messages.info(request, _(u"You changed your username; please note your " u"profile URL has also changed.")) if email_form.email_changed(): return render(request, "phonebook/verify_email.html", {"email": email_form.cleaned_data["email"]}) return redirect("phonebook:profile_view", user.username) data = dict( profile_form=profile_form, user_form=user_form, accounts_formset=accounts_formset, email_form=email_form, user_groups=user_groups, my_vouches=UserProfile.objects.filter(vouched_by=profile), profile=request.user.userprofile, apps=user.apiapp_set.filter(is_active=True), language_formset=language_formset, mapbox_id=settings.MAPBOX_MAP_ID, ) # If there are form errors, don't send a 200 OK. status = 400 if any(f.errors for f in all_forms) else 200 return render(request, "phonebook/edit_profile.html", data, status=status)
def view_profile(request, username): """View a profile by username.""" data = {} privacy_mappings = { 'anonymous': PUBLIC, 'mozillian': MOZILLIANS, 'employee': EMPLOYEES, 'privileged': PRIVILEGED, 'myself': None } privacy_level = None if (request.user.is_authenticated() and request.user.username == username): # own profile view_as = request.GET.get('view_as', 'myself') privacy_level = privacy_mappings.get(view_as, None) profile = UserProfile.objects.privacy_level(privacy_level).get( user__username=username) data['privacy_mode'] = view_as else: userprofile_query = UserProfile.objects.filter(user__username=username) public_profile_exists = userprofile_query.public().exists() profile_exists = userprofile_query.exists() profile_complete = userprofile_query.exclude(full_name='').exists() if not public_profile_exists: if not request.user.is_authenticated(): # you have to be authenticated to continue messages.warning(request, LOGIN_MESSAGE) return (login_required(view_profile, login_url=reverse('phonebook:home'))( request, username)) if not request.user.userprofile.is_vouched: # you have to be vouched to continue messages.error(request, GET_VOUCHED_MESSAGE) return redirect('phonebook:home') if not profile_exists or not profile_complete: raise Http404 profile = UserProfile.objects.get(user__username=username) profile.set_instance_privacy_level(PUBLIC) if request.user.is_authenticated(): profile.set_instance_privacy_level( request.user.userprofile.privacy_level) if (request.user.is_authenticated() and profile.is_vouchable(request.user.userprofile)): vouch_form = forms.VouchForm(request.POST or None) data['vouch_form'] = vouch_form if vouch_form.is_valid(): # We need to re-fetch profile from database. profile = UserProfile.objects.get(user__username=username) profile.vouch(request.user.userprofile, vouch_form.cleaned_data['description']) # 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('phonebook:profile_view', profile.user.username) data['shown_user'] = profile.user data['profile'] = profile data['groups'] = profile.get_annotated_groups() # Only show pending groups if user is looking at their own profile, # or current user is a superuser if not (request.user.is_authenticated() and (request.user.username == username or request.user.is_superuser)): data['groups'] = [grp for grp in data['groups'] if not grp.pending] return render(request, 'phonebook/profile.html', data)
def edit_profile(request): """Edit user profile view.""" # Don't user request.user user = User.objects.get(pk=request.user.id) profile = user.userprofile user_groups = profile.groups.all().order_by('name') user_skills = stringify_groups(profile.skills.all().order_by('name')) user_form = forms.UserForm(request.POST or None, instance=user) accounts_formset = forms.AccountsFormset(request.POST or None, instance=profile) new_profile = False form = forms.ProfileForm language_formset = forms.LanguagesFormset(request.POST or None, instance=profile, locale=request.locale) if not profile.is_complete: new_profile = True form = forms.RegisterForm profile_form = form(request.POST or None, request.FILES or None, instance=profile, initial=dict(skills=user_skills)) email_form = forms.EmailForm(request.POST or None, initial={ 'email': request.user.email, 'user_id': request.user.id }) all_forms = [ user_form, profile_form, accounts_formset, email_form, language_formset ] # Using ``list`` to force calling is_valid on all the forms, even if earlier # ones are not valid, so we detect and display all the errors. if all(list(f.is_valid() for f in all_forms)): old_username = request.user.username user_form.save() profile_form.save() accounts_formset.save() language_formset.save() # Notify the user that their old profile URL won't work. if new_profile: redeem_invite(profile, request.session.get('invite-code')) messages.info(request, _(u'Your account has been created.')) elif user.username != old_username: messages.info( request, _(u'You changed your username; please note your ' u'profile URL has also changed.')) if email_form.email_changed(): return render(request, 'phonebook/verify_email.html', {'email': email_form.cleaned_data['email']}) return redirect('phonebook:profile_view', user.username) data = dict(profile_form=profile_form, user_form=user_form, accounts_formset=accounts_formset, email_form=email_form, user_groups=user_groups, my_vouches=UserProfile.objects.filter(vouched_by=profile), profile=request.user.userprofile, apps=user.apiapp_set.filter(is_active=True), language_formset=language_formset, mapbox_id=settings.MAPBOX_MAP_ID) # If there are form errors, don't send a 200 OK. status = 400 if any(f.errors for f in all_forms) else 200 return render(request, 'phonebook/edit_profile.html', data, status=status)
def login(request): if request.user.userprofile.is_complete: return redirect('phonebook:home') return redirect('phonebook:profile_edit')
def edit_profile(request): """Edit user profile view.""" # Don't user request.user user = User.objects.get(pk=request.user.id) profile = user.userprofile user_groups = profile.groups.all().order_by('name') user_skills = stringify_groups(profile.skills.all().order_by('name')) user_form = forms.UserForm(request.POST or None, instance=user) accounts_formset = forms.AccountsFormset(request.POST or None, instance=profile) new_profile = False form = forms.ProfileForm language_formset = forms.LanguagesFormset(request.POST or None, instance=profile, locale=request.locale) if not profile.is_complete: new_profile = True form = forms.RegisterForm profile_form = form(request.POST or None, request.FILES or None, instance=profile, initial={'skills': user_skills, 'saveregion': True if profile.geo_region else False, 'savecity': True if profile.geo_city else False, 'lat': profile.lat, 'lng': profile.lng}) email_form = forms.EmailForm(request.POST or None, initial={'email': request.user.email, 'user_id': request.user.id}) all_forms = [user_form, profile_form, accounts_formset, email_form, language_formset] # Using ``list`` to force calling is_valid on all the forms, even if earlier # ones are not valid, so we detect and display all the errors. if all(list(f.is_valid() for f in all_forms)): old_username = request.user.username user_form.save() profile_form.save() accounts_formset.save() language_formset.save() if new_profile: redeem_invite(profile, request.session.get('invite-code')) messages.info(request, _(u'Your account has been created.')) elif user.username != old_username: # Notify the user that their old profile URL won't work. messages.info(request, _(u'You changed your username; please note your ' u'profile URL has also changed.')) if email_form.email_changed(): return render(request, 'phonebook/verify_email.html', {'email': email_form.cleaned_data['email']}) return redirect('phonebook:profile_view', user.username) data = dict(profile_form=profile_form, user_form=user_form, accounts_formset=accounts_formset, email_form=email_form, user_groups=user_groups, profile=request.user.userprofile, apps=user.apiapp_set.filter(is_active=True), language_formset=language_formset, mapbox_id=settings.MAPBOX_PROFILE_ID) # If there are form errors, don't send a 200 OK. status = 400 if any(f.errors for f in all_forms) else 200 return render(request, 'phonebook/edit_profile.html', data, status=status)