Skip to content

Commit

Permalink
malpliigas rendimento-mezuradon far Sentry por neensalutintaj uzantoj…
Browse files Browse the repository at this point in the history
… (ref 1f135f8)
  • Loading branch information
interDist committed Jun 12, 2024
1 parent 580ac0e commit cbf7af9
Show file tree
Hide file tree
Showing 8 changed files with 220 additions and 203 deletions.
11 changes: 4 additions & 7 deletions core/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.conf import settings
from django.contrib.auth.views import (
LogoutView, PasswordResetCompleteView, PasswordResetDoneView,
PasswordResetCompleteView, PasswordResetDoneView,
)
from django.urls import include, path, re_path
from django.utils.translation import pgettext_lazy
Expand All @@ -9,7 +8,8 @@
from .forms import SystemPasswordResetForm, SystemPasswordResetRequestForm

from .views import ( # isort:skip
HomeView, RegisterView, LoginView, AccountRestoreRequestView,
HomeView,
RegisterView, LoginView, AccountRestoreRequestView, LogoutView,
PasswordResetView, PasswordResetConfirmView,
UsernameRemindView, UsernameRemindDoneView,
AgreementView, AgreementRejectView,
Expand All @@ -36,10 +36,7 @@
AccountRestoreRequestView.as_view(), name='login_restore'),
path(
pgettext_lazy("URL", 'logout/'),
LogoutView.as_view(
redirect_field_name=settings.REDIRECT_FIELD_NAME,
),
name='logout'),
LogoutView.as_view(), name='logout'),

path(
pgettext_lazy("URL", 'agreement/'), include([
Expand Down
38 changes: 37 additions & 1 deletion core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.contrib import messages
from django.contrib.auth import authenticate, get_user_model, login, logout
from django.contrib.auth.views import (
LoginView as LoginBuiltinView,
LoginView as LoginBuiltinView, LogoutView as LogoutBuiltinView,
PasswordChangeDoneView as PasswordChangeDoneBuiltinView,
PasswordChangeView as PasswordChangeBuiltinView,
PasswordResetConfirmView as PasswordResetConfirmBuiltinView,
Expand Down Expand Up @@ -128,6 +128,42 @@ def get_redirect_url(self):
else:
return redirect_to

def render_to_response(self, context, **response_kwargs) -> HttpResponse:
# The view is rendered, which means that the user is not logged in.
response = super().render_to_response(context, **response_kwargs)
response.delete_cookie(
'seen_at',
domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH,
)
return response

def form_valid(self, form) -> HttpResponse:
# User successfully logged in.
response = super().form_valid(form)
response.set_cookie(
'seen_at', str(int(datetime.now().timestamp())),
max_age=(
settings.SESSION_COOKIE_AGE
if not settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
else None
),
domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE, httponly=True, samesite='Lax',
)
return response


class LogoutView(LogoutBuiltinView):
redirect_field_name = settings.REDIRECT_FIELD_NAME

def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
response.delete_cookie(
'seen_at',
domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH,
)
return response


class RegisterView(generic.CreateView):
model = User
Expand Down
19 changes: 17 additions & 2 deletions pasportaservo/settings/sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,25 +38,31 @@ class TracesSampler:
+ r'|facebookexternalhit|feedfetcher|feedburner',
re.IGNORECASE
)
authenticated_user_cookie_re = re.compile(r'\bseen_at=[A-Za-z0-9]')

def __call__(self, sampling_context: SamplingContext) -> float:
if sampling_context['parent_sampled'] is not None:
return sampling_context['parent_sampled']

request_info = (
request_info: tuple[str, str] = (
sampling_context['wsgi_environ'].get('PATH_INFO', ''),
sampling_context['wsgi_environ'].get('REQUEST_METHOD'),
)

bot_match = re.search(
self.robot_crawler_re,
sampling_context['wsgi_environ'].get('HTTP_USER_AGENT', ''))
if bot_match or request_info[0].startswith((STATIC_URL, MEDIA_URL)):
if (
bot_match
or request_info[0].startswith((STATIC_URL, MEDIA_URL))
or not request_info[0].endswith('/')
):
return 0

if not hasattr(self, 'paths'):
self.configure_paths()
sampling_rate = 0
reduced_sampling_if_anonymous = False

match request_info:
case (path, method) \
Expand All @@ -65,13 +71,22 @@ def __call__(self, sampling_context: SamplingContext) -> float:
case (path, _) \
if path.startswith(self.paths['exploration']):
sampling_rate = 0.75
reduced_sampling_if_anonymous = True
case (path, method) \
if path.startswith(self.paths['interesting']):
sampling_rate = 0.50 if method == 'POST' else 0.40
reduced_sampling_if_anonymous = True
case (path, _) \
if path.startswith(self.paths['action_link']):
sampling_rate = 1.00

if reduced_sampling_if_anonymous and sampling_rate > 0:
user_match = re.search(
self.authenticated_user_cookie_re,
sampling_context['wsgi_environ'].get('HTTP_COOKIE', ''))
if not user_match:
sampling_rate *= 0.25

return sampling_rate

def trim_path(self, path: str) -> str:
Expand Down
1 change: 1 addition & 0 deletions tests/views/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def test_view_form(self):
self,
user=self.user if self.view_page.redirects_unauthenticated else None,
reuse_for_lang=lang)
assert 'object' in page.form
# Verify that the expected form class is in use on the view.
self.assertIsNotNone(page.form['object'])
self.assertIsInstance(page.form['object'], page.form_class)
Expand Down
2 changes: 1 addition & 1 deletion tests/views/pages/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .account import AccountSettingsPage, RegisterPage
from .account import AccountSettingsPage, LoginPage, RegisterPage
from .admin import MassMailPage, MassMailResultPage
from .general import (
AboutPage, FAQPage, HomePage, OkayPage, PrivacyPage, TCPage,
Expand Down
28 changes: 26 additions & 2 deletions tests/views/pages/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from lxml.html import HtmlElement
from pyquery import PyQuery

from core.forms import UserRegistrationForm
from core.views import AccountSettingsView, RegisterView
from core.forms import UserAuthenticationForm, UserRegistrationForm
from core.views import AccountSettingsView, LoginView, RegisterView

from .base import PageTemplate, PageWithFormTemplate

Expand Down Expand Up @@ -35,6 +35,30 @@ class RegisterPage(PageWithFormTemplate):
}


class LoginPage(PageWithFormTemplate):
view_class = LoginView
form_class = UserAuthenticationForm
url = reverse_lazy('login')
explicit_url = {
'en': '/login/',
'eo': '/ensaluti/',
}
template = 'registration/login.html'
title = {
'en': "Log in & Find accommodation | Pasporta Servo",
'eo': "Ensalutu & Trovu loĝejon | Pasporta Servo",
}
redirects_unauthenticated = False
redirects_logged_in = True
form = {
'selector': ".login",
'title': {
'en': "Log In",
'eo': "Ensaluto",
},
}


class AccountSettingsPage(PageTemplate):
view_class = AccountSettingsView
url = reverse_lazy('account_settings')
Expand Down
2 changes: 1 addition & 1 deletion tests/views/pages/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ class _RenderedFormDefinitionBase(TypedDict):
title: dict[str, str]

class RenderedFormDefinition(_RenderedFormDefinitionBase, total=False):
object: type[Form] | type[ModelForm] | None
object: Form | ModelForm | None

form_class: type[Form] | type[ModelForm]
form: RenderedFormDefinition = {
Expand Down
Loading

0 comments on commit cbf7af9

Please sign in to comment.