Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,12 @@ Example `DB_PARAMS`:
{"dbname":"safefamily","user":"safefamily","password":"secret","host":"localhost","port":5432}
```

Accounts:
- `ALLOW_REGISTRATION`: new accounts are refused unless this is `True`. That
covers the register form, `POST /auth/register`, and first-time Google/GitHub
sign-in. Existing accounts can always log in. Set it to `True` only while
adding a family member, then remove it and restart the app.

Notesync:
- `NOTESYNC_API_KEY`
- `NOTESYNC_AUTH_CODE_TTL_SECONDS`
Expand Down
5 changes: 5 additions & 0 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ class Settings:
"APP_MOTTO",
)

# New accounts (form, API and first-time Google/GitHub sign-in) are refused
# unless this is "True". Existing accounts can always log in. Turn it on
# only while adding a family member, then off again.
ALLOW_REGISTRATION = os.environ.get("ALLOW_REGISTRATION", "False") == "True"

# Countdown page settings (date in YYYY-MM-DD)
COUNTDOWN_DATE = os.environ.get("COUNTDOWN_DATE", "")
COUNTDOWN_DESCRIPTION = os.environ.get("COUNTDOWN_DESCRIPTION", "")
Expand Down
7 changes: 7 additions & 0 deletions docs/lotto-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,13 @@ Open `/lotto` on your phone, tap **Choose / take photos**, then **Upload**.
* The ceiling lights make round white reflections on the glass. Tilt the phone
a little so they don't sit on a row of price corners. A little glare is OK:
real photos have it, so the model must learn it.
* **Crop before upload.** A tray photo usually catches the edge of the
neighbouring trays, and their tickets must not be counted twice. After you
choose photos, each one shows a preview: drag a frame around the tray, drag
inside the frame to move it, drag a corner to resize, or press **Use whole
photo** to undo. Only the framed part is uploaded, cut from the
full-resolution photo, so the price corners stay as sharp as in the original.
Photos you don't frame are uploaded untouched.
* **HEIC (iPhone's default format) is converted to JPEG in the browser**
before upload, because the training scripts can't read HEIC. iPhone Safari
usually sends JPEG anyway. A browser that can't decode HEIC (e.g. Chrome on
Expand Down
35 changes: 33 additions & 2 deletions src/safe_family/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Flask application factory for Safe Family project."""

from datetime import timedelta
from urllib.parse import urlsplit

from flask import Flask, jsonify, session
from flask import Flask, Response, jsonify, request, session
from sqlalchemy.exc import SQLAlchemyError

from config.logging import setup_logging
Expand All @@ -25,6 +26,33 @@
from src.safe_family.users.users import user_bp

MIN_SECRET_LENGTH = 32
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})


def reject_cross_site_writes() -> tuple[Response, int] | None:
"""Refuse state-changing requests that a browser sent from another site.

Browsers put the page's origin in the Origin header (or Referer) of every
cross-site POST. If it names a different host than ours, the request was
not made from our own pages (CSRF). Clients that send neither header
(the mobile app, scripts) are not browsers being tricked and pass through.
"""
if request.method in SAFE_METHODS:
return None
source = request.headers.get("Origin") or request.headers.get("Referer")
if not source:
return None
# A header with no host (e.g. "Origin: null" from a sandboxed frame) is an
# origin we can't vouch for, so it is refused like any other foreign one.
if urlsplit(source).netloc != request.host:
return jsonify({"error": "cross-site request blocked"}), 403
return None


def add_security_headers(response: Response) -> Response:
"""Stop browsers from guessing a different content type than we declared."""
response.headers.setdefault("X-Content-Type-Options", "nosniff")
return response


def _require_strong_secret(name: str, value: str | None) -> None:
Expand Down Expand Up @@ -89,10 +117,13 @@ def create_app():
jwt.init_app(app)
mail.init_app(app)

app.before_request(reject_cross_site_writes)
app.after_request(add_security_headers)

@app.context_processor
def inject_motto() -> dict:
"""Inject the app motto into all templates."""
return {"motto": settings.APP_MOTTO}
return {"motto": settings.APP_MOTTO, "registration_open": settings.ALLOW_REGISTRATION}

app.context_processor(inject_nav_user)

Expand Down
4 changes: 2 additions & 2 deletions src/safe_family/auto_git/auto_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def rule_auto_commit():
logger.exception("Error adding files to git: %d", e.returncode)


@auto_git_bp.route("/auto_push")
@auto_git_bp.post("/auto_push")
@admin_required
def auto_push():
"""Automatically commit and push block list changes to GitHub."""
Expand All @@ -90,7 +90,7 @@ def auto_push():
return redirect("/")


@auto_git_bp.route("/auto_import")
@auto_git_bp.post("/auto_import")
@admin_required
def auto_import():
"""Automatically import block list from files into the database."""
Expand Down
50 changes: 40 additions & 10 deletions src/safe_family/core/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
logger = logging.getLogger(__name__)
auth_bp = Blueprint("auth", __name__)
OAUTH_STATE_TTL_SECONDS = 600
MIN_PASSWORD_LENGTH = 8
REGISTRATION_CLOSED = "Registration is closed. Ask the admin to add you."


def require_api_key(view_func: Callable) -> Callable:
Expand Down Expand Up @@ -114,17 +116,30 @@ def build_notesync_callback_url(code: str, client: str = "ios") -> str:
@auth_bp.post("/register")
def register_user():
"""Register a new user."""
data = getattr(g, "_json_data", None) or request.get_json()
user = User.get_user_by_username(username=data.get("username"))
if not settings.ALLOW_REGISTRATION:
return jsonify({"message": REGISTRATION_CLOSED}), 403
data = getattr(g, "_json_data", None) or request.get_json(silent=True) or {}
username = (data.get("username") or "").strip()
email = (data.get("email") or "").strip()
password = data.get("password") or ""
if not username or not email:
return jsonify({"message": "Username and email are required"}), 400
if len(password) < MIN_PASSWORD_LENGTH:
return jsonify(
{"message": f"Password must be at least {MIN_PASSWORD_LENGTH} characters"},
), 400
user = User.get_user_by_username(username=username)

if user is not None:
return jsonify({"message": "Username already exists"}), 400
if User.query.filter_by(email=email).first() is not None:
return jsonify({"message": "Email already in use"}), 400
new_user = User(
username=data.get("username"),
email=data.get("email"),
username=username,
email=email,
role="user", # never trust a client-supplied role
)
new_user.set_password(data.get("password"))
new_user.set_password(password)
new_user.save()
return jsonify({"message": "User registered successfully"}), HTTP_CREATED

Expand Down Expand Up @@ -214,14 +229,17 @@ def logout():
@auth_bp.route("/session-register", methods=["GET", "POST"])
def session_register():
"""Register a new user via HTML form."""
if not settings.ALLOW_REGISTRATION:
flash(REGISTRATION_CLOSED, "warning")
return redirect("/auth/login-ui")
if request.method == "POST":
username = request.form["username"]
email = request.form["email"]
password = request.form["password"]
confirmed_password = request.form["confirm_password"]
if password != confirmed_password:
flash("Passwords do not match", "danger")
return render_template("register.html")
return render_template("auth/register.html")

json_data = {
"username": username,
Expand All @@ -235,10 +253,10 @@ def session_register():
# remove the temp data
del g._json_data # noqa: SLF001 - our own attr on flask.g # noqa: SLF001 - our own attr on flask.g

_data, status_code = response
data, status_code = response
if status_code != HTTP_CREATED:
flash("Invalid username or password", "danger")
return render_template("register.html")
flash(data.get_json().get("message", "Registration failed"), "danger")
return render_template("auth/register.html")
flash("Registration successful! Please log in.", "success")
return redirect("/auth/login-ui")
return render_template("/auth/register.html")
Expand Down Expand Up @@ -647,6 +665,10 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl
if not user:
user = User.query.filter_by(email=email).first()

if not user and not settings.ALLOW_REGISTRATION:
flash(REGISTRATION_CLOSED, "warning")
return redirect("/auth/login-ui")

if not user:
new_user = User(
id=github_id,
Expand Down Expand Up @@ -704,6 +726,10 @@ def google_callback():
if not user:
user = User.query.filter_by(email=email).first()

if not user and not settings.ALLOW_REGISTRATION:
flash(REGISTRATION_CLOSED, "warning")
return redirect("/auth/login-ui")

if not user:
new_user = User(
id=google_id,
Expand All @@ -730,12 +756,16 @@ def google_callback():
def notesync_callback():
"""Fallback page for notesync universal link callback."""
code = request.args.get("code", "")
plain = {"Content-Type": "text/plain; charset=utf-8"}
if not code:
return "Missing auth code. Return to the app and try again.", 400
return "Missing auth code. Return to the app and try again.", 400, plain
# The code comes straight from the URL: send it as plain text so a crafted
# link can never run script in the page (reflected XSS).
return (
(
"Auth code received. You can return to the app to finish login. "
f"If needed, copy this code: {code}"
),
200,
plain,
)
25 changes: 25 additions & 0 deletions src/safe_family/static/css/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -1989,3 +1989,28 @@ td form button {
margin: 0;
padding: 8px 16px;
}

.lotto-crops {
display: flex;
flex-direction: column;
gap: 16px;
}

.lotto-crop-editor {
display: flex;
flex-direction: column;
gap: 6px;
}

/* Height is capped so there is always page left to scroll with a finger:
touches on the canvas itself draw the crop frame instead of scrolling. */
.lotto-crop-editor canvas {
display: block;
align-self: flex-start;
max-width: 100%;
max-height: 70vh;
touch-action: none;
cursor: crosshair;
border-radius: var(--sf-radius-sm);
background: var(--sf-surface-3);
}
2 changes: 1 addition & 1 deletion src/safe_family/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@
class="{% if request.endpoint in ('index.calc_guide', 'index.recipes', 'index.recipe_detail') %}active{% endif %}">Sheet</a>
{% else %}
<a href="{{ url_for('auth.show_login_form') }}">Login</a>
<a href="{{ url_for('auth.session_register') }}">Register</a>
{% if registration_open %}<a href="{{ url_for('auth.session_register') }}">Register</a>{% endif %}
{% endif %}
</nav>
<div class="sf-user">
Expand Down
Loading
Loading