def update_post_views(post, request, timeout=settings.POST_VIEW_TIMEOUT): """ Views are updated per interval. """ # Get the ip. ip = helpers.get_ip(request) # Keys go by IP and post ip. cache_key = f"{ip}-{post.id}" # Found hit no need to increment the views if cache.get(cache_key): return # Insert a new view into database. PostView.objects.create(ip=ip, post=post) # Separately increment post view. Post.objects.filter(id=post.id).update(view_count=F('view_count') + 1) # Set the cache. cache.set(cache_key, 1, timeout) # Drop the post related cache for logged in users. if request.user.is_authenticated: delete_post_cache(post) return post
def user_login(request): form = forms.LoginForm() if request.method == "POST": form = forms.LoginForm(data=request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] next_url = request.POST.get('next', settings.LOGIN_REDIRECT_URL) user = User.objects.filter(email__iexact=email).order_by('-id').first() message, valid_user = validate_login(email=email, password=password) if valid_user: login(request, user, backend="django.contrib.auth.backends.ModelBackend") ipaddr = get_ip(request) text = f"user {user.id} ({user.email}) logged in from {ipaddr}" return redirect(next_url) else: messages.error(request, mark_safe(message)) messages.error(request, mark_safe(form.errors)) context = dict(form=form, tab="login", social_login=SocialApp.objects.all()) return render(request, "accounts/login.html", context=context)
def middleware(request): user, session = request.user, request.session # Views for anonymous users are not analzed further. if user.is_anonymous: return get_response(request) # Banned and suspended will be logged out. if auth.is_suspended(user=user): messages.error(request, f"Account is {user.profile.get_state_display()}") logout(request) update_status(user=user) # Find out the time since the last visit. elapsed = (now() - user.profile.last_login).total_seconds() # Update information since the last visit. if elapsed > settings.SESSION_UPDATE_SECONDS: # Detect user location if not set in the profile. ip = helpers.get_ip(request) # Detect user location if not set in the profile. if not user.profile.location: detect_location.spool(ip=ip, user_id=user.id) # Set the last login time. Profile.objects.filter(user=user).update(last_login=now()) # Compute latest counts. counts = auth.get_counts(user=user) # Set the session. request.session[settings.SESSION_COUNT_KEY] = counts # Trigger award generation. tasks.create_user_awards.spool(user_id=user.id) # Can process response here after its been handled by the view response = get_response(request) return response
def set_planet_count(request): """ """ # Get the ip ip = get_ip(request) # Try to fetch count from cache. planets = cache.get(ip) if planets is None: # Get latest blog posts date = now() - timedelta(weeks=1) planets = BlogPost.objects.filter(rank__gte=date)[:100].count() # Expire counts cache in 24 hours expire = 3600 * 24 cache.set(ip, planets, expire) counts = dict(planet_count=planets) # Set the session. request.session[settings.SESSION_COUNT_KEY] = counts
def middleware(request): # Start timer. start = time.time() # Performs the request response = get_response(request) # Elapsed time. delta = int((time.time() - start) * 1000) # Generate timing message. msg = f'time={delta}ms for path={request.path}' if delta > 1000: ip = helpers.get_ip(request) uid = request.user.profile.uid if request.user.is_authenticated else '0' #agent = request.META.get('HTTP_USER_AGENT', None) logger.warning(f"SLOW: {msg} IP:{ip} uid:{uid}") elif settings.DEBUG: logger.info(f'{msg}') return response
def middleware(request): user = request.user # Only check anonymous users if user.is_anonymous: ip = helpers.get_ip(request) triplet = helpers.ip_triplet(request) if triplet in settings.WHITELIST_IP: return get_response(request) # Check if the user should be rate limited within a given time period. limited = is_ratelimited(request=request, fn=get_response, key=settings.RATELIMIT_KEY, rate=settings.RATELIMIT_RATE, increment=True) # Redirect to static page if limit reached # Might spam the logger view # auth.db_logger(text=f'user banned ip={ip}', ipaddr=ip) if limited: return redirect('/static/message.txt') return get_response(request)