Files
pretix_cgo/src/pretix/helpers/security.py
T
54eadaffcc Improve admin-facing email templates (#6216)
* Improve subject lines for admin-facing emails

A few of the current subjects are ambiguous about the expected
action, and some omit context that would help in an inbox preview
(which event, which address). The rewrites bring them closer to
common conventions in modern transactional email (verb-led,
recipient-addressed, with recipient-meaningful variables). Two
themes:

- Action-required emails lead with the action verb. "Reset your
  password", "Confirm event cancellation and bulk refund", and
  "Confirm <address> as a sender address" tell the recipient up
  front what's expected, where "Password recovery", "Bulk-refund
  confirmation" and "Sender address verification" did not.

- Surface the relevant variable when the email is about something
  specific. "Data shredding completed for <event>" is more useful
  than the generic version when an admin manages several events.
  "You've been invited to join <organizer>" names the inviting
  organizer. "Confirm <address> as a sender address" names the
  address.

The remaining rewrites are lighter rewordings. "New sign-in to
your account" replaces "Login from new source detected" because
"source" is jargon a non-technical recipient wouldn't recognise.
"Changes to your account" replaces "Account information changed"
because the possessive frames the email as being about the
recipient's own account.

Also fixes a hardcoded "pretix" in the confirmation-code subject.

* Standardise admin email sign-offs as "Thanks, The <instance> Team"

The current sign-offs ("Best regards, Your <instance> team") have
a formal tone. A review of the last ~20 transactional emails in
my inbox showed most senders use something friendlier:

- Thanks: Deliveroo, Starling Bank, GitHub, Cloudflare
- Thank you: AWS
- Sincerely: Google Workspace

A small minority (e.g., Sentry) had no sign-off at all. "Thanks"
was the most common, and among that group "The <instance> Team"
was the consistent phrasing rather than "Your <instance> team".

Two templates (cancel_confirm, export_failed) didn't have a
sign-off; they now get one for consistency. Notification emails
are deliberately excluded: they're system alerts rather than
direct correspondence.

* Add anti-phishing notice to admin emails containing confirmation codes

Three admin emails send the recipient a confirmation code to
enter back into a form: confirmation_code, email_setup, and
cancel_confirm. Only confirmation_code had an anti-phishing
warning, and its wording was awkward ("Please do never give this
code to another person. Our support team will never ask for this
code.").

This commit standardises the warning across all three:

> Don't share this code with anyone. The <instance> team will
> never ask you for it.

* Add structured details to login-notice email

The single-sentence body ("The login was performed using <agent>
on <os> from <country>.") is replaced with a labelled bullet list:
Time, Browser, Operating system, Device, Country.

Time and Device are new fields. Device is omitted when ua-parser
can't identify the device, Country when GeoIP isn't available,
so the user only sees fields with real values.

* Restructure notification.txt for clearer layout

- Attributes: bullet list instead of paragraph-per-attribute.

- Actions: label gets a colon, URL on its own paragraph (was
  4-space-indented code block).

- Footer: separated by --- and bulleted (manage / disable
  links). "Click here X" phrasing dropped (incidentally moots
  a missing-"to" typo).

- Minor whitespace fix: detail-block endif now matches the
  placement of the rest of the template.

notification.html's footer text is also updated, only to match
the new .txt wording (link labels and intro line). No
structural changes to the HTML template.

* Improve confirmation-code email reason strings

- Drop the redundant "to confirm" opener.

- Replace hardcoded "your pretix account" in email_verify
  with "{instance}".

* Polish admin email body copy

A small wording and formatting pass on the admin email bodies,
in three loosely-grouped themes:

1. Sentence case for body text (previously lowercase after
   "Hello,"), matching standard English convention.

2. Light restructuring where helpful: bullet lists for sets
   of labelled facts; 4-space-indented code blocks for codes
   the recipient is meant to type back.

3. Phrasing polish. Some sentences tightened or shortened.
   Largely matters of taste, but generally read smoother.

---------

Co-authored-by: Raphael Michel <michel@pretix.eu>
2026-07-06 17:25:52 +02:00

203 lines
7.5 KiB
Python

#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
import hashlib
import logging
import time
from django.conf import settings
from django.contrib.auth import login as auth_login
from django.contrib.gis import geoip2
from django.core.cache import cache
from django.utils.formats import date_format
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from django_countries.fields import Country
from geoip2.errors import AddressNotFoundError
from pretix.base.i18n import language
from pretix.base.services.mail import mail
from pretix.helpers.http import get_client_ip
from pretix.helpers.urls import mainreverse_absolute
logger = logging.getLogger(__name__)
class SessionInvalid(Exception):
pass
class SessionReauthRequired(Exception):
pass
class Session2FASetupRequired(Exception):
pass
class SessionPasswordChangeRequired(Exception):
pass
def get_user_agent_hash(request):
return hashlib.sha256(request.headers['User-Agent'].encode()).hexdigest()
_geoip = None
def get_geoip() -> geoip2.GeoIP2:
# See https://code.djangoproject.com/ticket/36988#ticket
global _geoip
geoip2.SUPPORTED_DATABASE_TYPES.add("Geoacumen-Country")
if not _geoip:
_geoip = geoip2.GeoIP2()
return _geoip
def _get_country(request):
try:
res = get_geoip().country(get_client_ip(request))
except AddressNotFoundError:
return None
return res['country_code']
def assert_session_valid(request):
if not settings.PRETIX_LONG_SESSIONS or not request.session.get('pretix_auth_long_session', False):
last_used = request.session.get('pretix_auth_last_used', time.time())
if time.time() - request.session.get('pretix_auth_login_time',
time.time()) > settings.PRETIX_SESSION_TIMEOUT_ABSOLUTE:
request.session['pretix_auth_login_time'] = 0
raise SessionInvalid()
if time.time() - last_used > settings.PRETIX_SESSION_TIMEOUT_RELATIVE:
raise SessionReauthRequired()
if 'User-Agent' in request.headers:
if 'pinned_user_agent' in request.session:
if request.session.get('pinned_user_agent') != get_user_agent_hash(request):
logger.info(f"Backend session for user {request.user.pk} terminated due to user agent change. "
f"New agent: \"{request.headers['User-Agent']}\"")
raise SessionInvalid()
else:
request.session['pinned_user_agent'] = get_user_agent_hash(request)
if settings.HAS_GEOIP:
client_ip = get_client_ip(request)
hashed_client_ip = hashlib.sha256(client_ip.encode()).hexdigest()
country = cache.get_or_set(f'geoip_country_{hashed_client_ip}', lambda: _get_country(request), timeout=300)
if 'pinned_country' in request.session:
if request.session.get('pinned_country') != country:
logger.info(f"Backend session for user {request.user.pk} terminated due to country change. "
f"Old country: \"{request.session.get('pinned_country')}\" New country: \"{country}\"")
raise SessionInvalid()
else:
request.session['pinned_country'] = country
request.session['pretix_auth_last_used'] = int(time.time())
if request.user.needs_password_change:
raise SessionPasswordChangeRequired()
force_2fa = not request.user.require_2fa and (
settings.PRETIX_OBLIGATORY_2FA is True or
(settings.PRETIX_OBLIGATORY_2FA == "staff" and request.user.is_staff) or
cache.get_or_set(
f'user_2fa_team_{request.user.pk}',
lambda: request.user.teams.filter(require_2fa=True).exists(),
timeout=300
)
)
if force_2fa:
raise Session2FASetupRequired()
return True
def handle_login_source(user, request):
from ua_parser import user_agent_parser
parsed_string = user_agent_parser.Parse(request.headers.get("User-Agent", ""))
country = None
if settings.HAS_GEOIP:
client_ip = get_client_ip(request)
hashed_client_ip = hashlib.sha256(client_ip.encode()).hexdigest()
country = cache.get_or_set(f'geoip_country_{hashed_client_ip}', lambda: _get_country(request), timeout=300)
if country == "None":
country = None
src, created = user.known_login_sources.update_or_create(
agent_type=parsed_string.get("user_agent").get("family"),
os_type=parsed_string.get("os").get("family"),
device_type=parsed_string.get("device").get("family"),
country=country,
defaults={
"last_seen": now(),
}
)
if created:
user.log_action('pretix.control.auth.user.new_source', user=user, data={
"agent_type": src.agent_type,
"os_type": src.os_type,
"device_type": src.device_type,
"country": str(src.country) if src.country else "?",
})
if user.known_login_sources.count() > 1:
# Do not send on first login or first login after introduction of this feature:
with language(user.locale):
mail(
user.email,
_('New sign-in to your account'),
'pretixcontrol/email/login_notice.txt',
{
'when': date_format(src.last_seen, 'DATETIME_FORMAT'),
'agent': src.agent_type,
'os': src.os_type,
# ua-parser returns "Other" for unidentified desktop devices.
'device': src.device_type if src.device_type and src.device_type != 'Other' else None,
'country': Country(str(country)).name if country else None,
'instance': settings.PRETIX_INSTANCE_NAME,
'url': mainreverse_absolute('control:user.settings')
},
event=None,
user=user,
locale=user.locale
)
def session_login(request, user, keep_logged_in=False):
auth_login(request, user)
session_reauth(request)
request.session["pretix_auth_long_session"] = (
settings.PRETIX_LONG_SESSIONS and keep_logged_in
)
def session_reauth(request):
t = int(time.time())
request.session['pretix_auth_login_time'] = t
request.session['pretix_auth_last_used'] = t