def hera(request): form = FlushForm(initial={'flushprefix': settings.SITE_URL}) boxes = [] configured = False # Default to not showing the form. for i in settings.HERA: hera = get_hera(i) r = {'location': urlparse(i['LOCATION'])[1], 'stats': False} if hera: r['stats'] = hera.getGlobalCacheInfo() configured = True boxes.append(r) if not configured: messages.error(request, "Hera is not (or mis-)configured.") form = None if request.method == 'POST' and hera: form = FlushForm(request.POST) if form.is_valid(): expressions = request.POST['flushlist'].splitlines() for url in expressions: num = flush_urls([url], request.POST['flushprefix'], True) msg = ("Flushed %d objects from front end cache for: %s" % (len(num), url)) log.info("[Hera] (user:%s) %s" % (request.user, msg)) messages.success(request, msg) return render(request, 'zadmin/hera.html', {'form': form, 'boxes': boxes})
def register(request): if waffle.switch_is_active('fxa-auth'): return login(request) if request.user.is_authenticated(): messages.info(request, _('You are already logged in to an account.')) form = None elif request.method == 'POST': form = forms.UserRegisterForm(request.POST) mkt_user = UserProfile.objects.filter(email=form.data['email'], password='') if form.is_valid(): try: u = form.save(commit=False) u.set_password(form.cleaned_data['password']) u.generate_confirmationcode() u.lang = request.LANG u.save() log.info(u'Registered new account for user (%s)', u) log_cef('New Account', 5, request, username=u.username, signature='AUTHNOTICE', msg='User created a new account') u.email_confirmation_code() msg = _('Congratulations! Your user account was ' 'successfully created.') messages.success(request, msg) msg = _(u'An email has been sent to your address {0} to ' 'confirm your account. Before you can log in, you ' 'have to activate your account by clicking on the ' 'link provided in this email.').format(u.email) messages.info(request, _('Confirmation Email Sent'), msg) except IntegrityError, e: # I was unable to reproduce this, but I suspect it happens # when they POST twice quickly and the slaves don't have the # new info yet (total guess). Anyway, I'm assuming the # first one worked properly, so this is still a success # case to the end user so we just log it... log.error('Failed to register new user (%s): %s' % (u, e)) return http.HttpResponseRedirect(reverse('users.login')) elif mkt_user.exists(): f = PasswordResetForm() f.users_cache = [mkt_user[0]] f.save(use_https=request.is_secure(), email_template_name='users/email/pwreset.ltxt', request=request) return render(request, 'users/newpw_sent.html', {}) else: messages.error(request, _('There are errors in this form'), _('Please correct them and resubmit.'))
def notify(request, job): job = get_object_or_404(ValidationJob, pk=job) notify_form = NotifyForm(request.POST, text='validation') if not notify_form.is_valid(): messages.error(request, notify_form) else: tasks.notify_compatibility.delay(job, notify_form.cleaned_data) return redirect(reverse('zadmin.validation'))
def edit(request): # Don't use request.user since it has too much caching. amouser = UserProfile.objects.get(pk=request.user.id) if request.method == 'POST': # ModelForm alters the instance you pass in. We need to keep a copy # around in case we need to use it below (to email the user) original_email = amouser.email form = forms.UserEditForm(request.POST, request.FILES, request=request, instance=amouser) if form.is_valid(): messages.success(request, _('Profile Updated')) if amouser.email != original_email: l = {'user': amouser, 'mail1': original_email, 'mail2': amouser.email} log.info(u"User (%(user)s) has requested email change from " u"(%(mail1)s) to (%(mail2)s)" % l) messages.info( request, _('Email Confirmation Sent'), _(u'An email has been sent to {0} to confirm your new ' u'email address. For the change to take effect, you ' u'need to click on the link provided in this email. ' u'Until then, you can keep logging in with your ' u'current email address.').format(amouser.email)) token, hash_ = EmailResetCode.create(amouser.id, amouser.email) url = '%s%s' % (settings.SITE_URL, reverse('users.emailchange', args=[amouser.id, token, hash_])) t = loader.get_template('users/email/emailchange.ltxt') c = {'domain': settings.DOMAIN, 'url': url} send_mail( _('Please confirm your email address ' 'change at %s' % settings.DOMAIN), t.render(Context(c)), None, [amouser.email], use_blacklist=False, real_email=True) # Reset the original email back. We aren't changing their # address until they confirm the new one amouser.email = original_email form.save() return redirect('users.edit') else: messages.error( request, _('Errors Found'), _('There were errors in the changes you made. Please correct ' 'them and resubmit.')) else: form = forms.UserEditForm(instance=amouser, request=request) return render(request, 'users/edit.html', {'form': form, 'amouser': amouser})
def render_error(request, error, next_path=None, format=None): if format == 'json': status = ERROR_STATUSES.get(error, 422) return Response({'error': error}, status=status) else: if not is_safe_url(next_path): next_path = None messages.error( request, fxa_error_message(LOGIN_ERROR_MESSAGES[error]), extra_tags='fxa') redirect_view = 'users.login' return HttpResponseRedirect( urlparams(reverse(redirect_view), to=next_path))
def render_error(request, error, next_path=None, format=None): if format == "json": status = ERROR_STATUSES.get(error, 422) return Response({"error": error}, status=status) else: if not is_safe_url(next_path): next_path = None messages.error(request, fxa_error_message(LOGIN_ERROR_MESSAGES[error]), extra_tags="fxa") if request.user.is_authenticated(): redirect_view = "users.migrate" else: redirect_view = "users.login" return HttpResponseRedirect(urlparams(reverse(redirect_view), to=next_path))
def confirm(request, user, token): if not user.confirmationcode: return redirect('users.login') if user.confirmationcode != token: log.info(u"Account confirmation failed for user (%s)", user) messages.error(request, _('Invalid confirmation code!')) return redirect('users.login') user.confirmationcode = '' user.save() messages.success(request, _('Successfully verified!')) log.info(u"Account confirmed for user (%s)", user) return redirect('users.login')
def render_error(request, error, next_path=None, format=None): if format == 'json': status = ERROR_STATUSES.get(error, 422) response = Response({'error': error}, status=status) else: if not is_safe_url(next_path): next_path = None messages.error( request, fxa_error_message(LOGIN_ERROR_MESSAGES[error]), extra_tags='fxa') if next_path is None: response = HttpResponseRedirect(reverse('users.login')) else: response = HttpResponseRedirect(next_path) return response
def render_error(request, error, next_path=None, format=None): if format == 'json': status = ERROR_STATUSES.get(error, 422) response = Response({'error': error}, status=status) else: if not is_safe_url(next_path, allowed_hosts=(settings.DOMAIN, )): next_path = None messages.error(request, fxa_error_message(LOGIN_ERROR_MESSAGES[error], LOGIN_HELP_URL), extra_tags='fxa') if next_path is None: response = HttpResponseRedirect('/') else: response = HttpResponseRedirect(next_path) return response
def render_error(request, error, next_path=None, format=None): if format == 'json': status = ERROR_STATUSES.get(error, 422) return Response({'error': error}, status=status) else: if not is_safe_url(next_path): next_path = None messages.error(request, fxa_error_message(LOGIN_ERROR_MESSAGES[error]), extra_tags='fxa') if request.user.is_authenticated(): redirect_view = 'users.migrate' else: redirect_view = 'users.login' return HttpResponseRedirect( urlparams(reverse(redirect_view), to=next_path))
def render_error(request, error, next_path=None, format=None): if format == 'json': status = ERROR_STATUSES.get(error, 422) response = Response({'error': error}, status=status) else: if not is_safe_url(next_path, allowed_hosts=(settings.DOMAIN,)): next_path = None messages.error( request, fxa_error_message(LOGIN_ERROR_MESSAGES[error], LOGIN_HELP_URL), extra_tags='fxa') if next_path is None: response = HttpResponseRedirect('/') else: response = HttpResponseRedirect(next_path) return response
def langpacks(request): if request.method == 'POST': try: tasks.fetch_langpacks.delay(request.POST['path']) except ValueError: messages.error(request, 'Invalid language pack sub-path provided.') return redirect('zadmin.langpacks') addons = (Addon.objects.no_cache() .filter(addonuser__user__email=settings.LANGPACK_OWNER_EMAIL, type=amo.ADDON_LPAPP) .order_by('name')) data = {'addons': addons, 'base_url': settings.LANGPACK_DOWNLOAD_BASE, 'default_path': settings.LANGPACK_PATH_DEFAULT % ( 'firefox', amo.FIREFOX.latest_version)} return render(request, 'zadmin/langpack_update.html', data)
def t_shirt(request): if not waffle.switch_is_active('t-shirt-orders'): raise http.Http404() user = request.user eligible = tshirt_eligible(user) if request.method == 'POST': if not eligible: messages.error(request, _("We're sorry, but you are not eligible to " "request a t-shirt at this time.")) return redirect('users.t-shirt') if not user.t_shirt_requested: user.update(t_shirt_requested=datetime.now()) return render(request, 'users/t-shirt.html', {'eligible': eligible, 'user': user})
def edit(request): # Don't use request.user since it has too much caching. amouser = UserProfile.objects.get(pk=request.user.id) if request.method == "POST": # ModelForm alters the instance you pass in. We need to keep a copy # around in case we need to use it below (to email the user) form = forms.UserEditForm(request.POST, request.FILES, request=request, instance=amouser) if form.is_valid(): messages.success(request, _("Profile Updated")) form.save() return redirect("users.edit") else: messages.error( request, _("Errors Found"), _("There were errors in the changes you made. Please correct " "them and resubmit."), ) else: form = forms.UserEditForm(instance=amouser, request=request) return render(request, "users/edit.html", {"form": form, "amouser": amouser})
def edit(request): # Don't use request.user since it has too much caching. amouser = UserProfile.objects.get(pk=request.user.id) if request.method == 'POST': # ModelForm alters the instance you pass in. We need to keep a copy # around in case we need to use it below (to email the user) form = forms.UserEditForm(request.POST, request.FILES, request=request, instance=amouser) if form.is_valid(): messages.success(request, ugettext('Profile Updated')) form.save() return redirect('users.edit') else: messages.error( request, ugettext('Errors Found'), ugettext('There were errors in the changes you made. ' 'Please correct them and resubmit.')) else: form = forms.UserEditForm(instance=amouser, request=request) return render(request, 'users/edit.html', {'form': form, 'amouser': amouser})
def t_shirt(request): if not waffle.switch_is_active('t-shirt-orders'): raise http.Http404() user = request.user eligible = tshirt_eligible(user) if request.method == 'POST': if not eligible: messages.error( request, _("We're sorry, but you are not eligible to " "request a t-shirt at this time.")) return redirect('users.t-shirt') if not user.t_shirt_requested: user.update(t_shirt_requested=datetime.now()) return render(request, 'users/t-shirt.html', { 'eligible': eligible, 'user': user })
def _login(request, template=None, data=None, dont_redirect=False): data = data or {} # In case we need it later. See below. get_copy = request.GET.copy() if 'to' in request.GET: request = _clean_next_url(request) if request.user.is_authenticated(): return http.HttpResponseRedirect( request.GET.get('to', settings.LOGIN_REDIRECT_URL)) data['login_source_form'] = (waffle.switch_is_active('fxa-auth') and not request.POST) limited = getattr(request, 'limited', 'recaptcha_shown' in request.POST) user = None login_status = None if 'username' in request.POST: try: # We are doing all this before we try and validate the form. user = UserProfile.objects.get(email=request.POST['username']) limited = ( (user.failed_login_attempts >= settings.LOGIN_RATELIMIT_USER) or limited) login_status = False except UserProfile.DoesNotExist: log.info('Authentication failure, username invalid (%s)' % request.POST['username']) pass partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited) r = auth.views.login(request, template_name=template, redirect_field_name='to', authentication_form=partial_form, extra_context=data) if isinstance(r, http.HttpResponseRedirect): # Django's auth.views.login has security checks to prevent someone from # redirecting to another domain. Since we want to allow this in # certain cases, we have to make a new response object here to replace # the above. request.GET = get_copy request = _clean_next_url(request) next_path = request.GET['to'] if waffle.switch_is_active('fxa-auth'): if next_path == '/': next_path = None next_path = urlparams(reverse('users.migrate'), to=next_path) r = http.HttpResponseRedirect(next_path) # Succsesful log in according to django. Now we do our checks. I do # the checks here instead of the form's clean() because I want to use # the messages framework and it's not available in the request there. if user.deleted: logout(request) log.warning(u'Attempt to log in with deleted account (%s)' % user) messages.error(request, _('Wrong email address or password!')) data.update({'form': partial_form()}) user.log_login_attempt(False) log.info('Authentication Failure, account is deactivated (%s)' % request.user) return render(request, template, data) if user.confirmationcode: logout(request) log.info(u'Attempt to log in with unconfirmed account (%s)' % user) msg1 = _(u'A link to activate your user account was sent by email ' u'to your address {0}. You have to click it before you ' u'can log in.').format(user.email) url = "%s%s" % (settings.SITE_URL, reverse('users.confirm.resend', args=[user.id])) msg2 = _('If you did not receive the confirmation email, make ' 'sure your email service did not mark it as "junk ' 'mail" or "spam". If you need to, you can have us ' '<a href="%s">resend the confirmation message</a> ' 'to your email address mentioned above.') % url messages.error(request, _('Activation Email Sent'), msg1) messages.info(request, _('Having Trouble?'), msg2, title_safe=True, message_safe=True) data.update({'form': partial_form()}) user.log_login_attempt(False) return render(request, template, data) rememberme = request.POST.get('rememberme', None) if rememberme: request.session.set_expiry(settings.SESSION_COOKIE_AGE) log.debug( u'User (%s) logged in successfully with "remember me" set' % user) login_status = True if dont_redirect: # We're recalling the middleware to re-initialize user ACLMiddleware().process_request(request) r = render(request, template, data) if login_status is not None: user.log_login_attempt(login_status) log.info('Authentication Failure, incorrect password (%s)' % request.POST['username']) return r
def _login(request, template=None, data=None, dont_redirect=False): data = data or {} # In case we need it later. See below. get_copy = request.GET.copy() if 'to' in request.GET: request = _clean_next_url(request) if request.user.is_authenticated(): return http.HttpResponseRedirect( request.GET.get('to', settings.LOGIN_REDIRECT_URL)) data['login_source_form'] = (waffle.switch_is_active('fxa-auth') and not request.POST) limited = getattr(request, 'limited', 'recaptcha_shown' in request.POST) user = None login_status = None if 'username' in request.POST: try: # We are doing all this before we try and validate the form. user = UserProfile.objects.get(email=request.POST['username']) limited = ((user.failed_login_attempts >= settings.LOGIN_RATELIMIT_USER) or limited) login_status = False except UserProfile.DoesNotExist: log_cef('Authentication Failure', 5, request, username=request.POST['username'], signature='AUTHFAIL', msg='The username was invalid') pass partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited) r = auth.views.login(request, template_name=template, redirect_field_name='to', authentication_form=partial_form, extra_context=data) if isinstance(r, http.HttpResponseRedirect): # Django's auth.views.login has security checks to prevent someone from # redirecting to another domain. Since we want to allow this in # certain cases, we have to make a new response object here to replace # the above. request.GET = get_copy request = _clean_next_url(request) next_path = request.GET['to'] if waffle.switch_is_active('fxa-auth'): if next_path == '/': next_path = None next_path = urlparams(reverse('users.migrate'), to=next_path) r = http.HttpResponseRedirect(next_path) # Succsesful log in according to django. Now we do our checks. I do # the checks here instead of the form's clean() because I want to use # the messages framework and it's not available in the request there. if user.deleted: logout(request) log.warning(u'Attempt to log in with deleted account (%s)' % user) messages.error(request, _('Wrong email address or password!')) data.update({'form': partial_form()}) user.log_login_attempt(False) log_cef('Authentication Failure', 5, request, username=request.user, signature='AUTHFAIL', msg='Account is deactivated') return render(request, template, data) if user.confirmationcode: logout(request) log.info(u'Attempt to log in with unconfirmed account (%s)' % user) msg1 = _(u'A link to activate your user account was sent by email ' u'to your address {0}. You have to click it before you ' u'can log in.').format(user.email) url = "%s%s" % (settings.SITE_URL, reverse('users.confirm.resend', args=[user.id])) msg2 = _('If you did not receive the confirmation email, make ' 'sure your email service did not mark it as "junk ' 'mail" or "spam". If you need to, you can have us ' '<a href="%s">resend the confirmation message</a> ' 'to your email address mentioned above.') % url messages.error(request, _('Activation Email Sent'), msg1) messages.info(request, _('Having Trouble?'), msg2, title_safe=True, message_safe=True) data.update({'form': partial_form()}) user.log_login_attempt(False) return render(request, template, data) rememberme = request.POST.get('rememberme', None) if rememberme: request.session.set_expiry(settings.SESSION_COOKIE_AGE) log.debug( u'User (%s) logged in successfully with "remember me" set' % user) login_status = True if dont_redirect: # We're recalling the middleware to re-initialize user ACLMiddleware().process_request(request) r = render(request, template, data) if login_status is not None: user.log_login_attempt(login_status) log_cef('Authentication Failure', 5, request, username=request.POST['username'], signature='AUTHFAIL', msg='The password was incorrect') return r