🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Admin users list: provider column + editable email (#134)
sassanixdf65fb27de2d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 74a9bd2..749ebbb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## 1.0.5 - Unreleased+- **Admin users list: sign-in provider shown, email editable (#134):** the admin Users list now has a Provider column (Local / OIDC) so it is obvious how each account signs in — the API reports the provider without exposing the raw OIDC subject. The Edit User dialog's email field, previously shown disabled, is now editable: an admin can fix a user's email without touching the database, with format and uniqueness validation.+- **Product photo comes first in the Add Warranty form (#146):** the photo upload lived on the Documents tab, at the end of the flow, so users photographing a receipt had to read its purchase date and serial number in a separate program while filling the form. The photo upload (with its preview) now opens the Product tab: upload the receipt or product photo first, then read the details straight off the preview as you type.- **Claims can no longer be added to a voided warranty:** a voided warranty's coverage is dead, but the app still let new claims be filed against it. Claim creation now returns a clear error (code `warranty_voided`), the claims view hides the Add Claim button for voided warranties and explains why, and claims recorded before the void stay fully editable — un-voiding restores claim creation.diff --git a/backend/admin_routes.py b/backend/admin_routes.pyindex 743bccd..0cf1762 100644--- a/backend/admin_routes.py+++ b/backend/admin_routes.py@@ -1,6 +1,7 @@from flask import Blueprint, request, jsonify, current_appfrom datetime import datetime, dateimport os+import reimport logging# Use try-except pattern for imports to handle both Docker and development environments@@ -42,8 +43,8 @@ def get_all_users():# Try to get users with is_owner column, fall back to without it if column doesn't existtry:cur.execute('''- SELECT id, username, email, first_name, last_name, is_active, is_admin, is_owner, created_at, last_login- FROM users+ SELECT id, username, email, first_name, last_name, is_active, is_admin, is_owner, created_at, last_login, oidc_sub+ FROM usersORDER BY created_at DESC''')users = cur.fetchall()@@ -65,7 +66,12 @@ def get_all_users():for row in users:user_dict = dict(zip(columns, row))-++ # Expose how the user signs in, without exposing the+ # raw OIDC subject identifier.+ oidc_sub = user_dict.pop('oidc_sub', None)+ user_dict['auth_provider'] = 'oidc' if oidc_sub else 'local'+# Add is_owner field if it wasn't included in the queryif not has_owner_column:user_dict['is_owner'] = False@@ -124,17 +130,37 @@ def update_user(user_id):if 'is_active' in data and data['is_active'] is False:return jsonify({"message": "The application owner's account cannot be deactivated."}), 403+ # Validate an email change up front: format plus+ # uniqueness across the other accounts.+ new_email = None+ if 'email' in data:+ raw_email = data.get('email')+ if (not isinstance(raw_email, str)+ or len(raw_email.strip()) > 255+ or not re.match(r'^[^@\s]+@[^@\s]+\.[^@\s]+$',+ raw_email.strip())):+ return jsonify({"message": "Invalid email address"}), 400+ new_email = raw_email.strip()+ cur.execute('SELECT id FROM users WHERE email = %s AND id != %s',+ (new_email, user_id))+ if cur.fetchone():+ return jsonify({"message": "Email address is already in use by another account"}), 400+# Update fieldsupdates = []params = []-+if 'is_admin' in data:updates.append('is_admin = %s')params.append(bool(data['is_admin']))-+if 'is_active' in data:updates.append('is_active = %s')params.append(bool(data['is_active']))++ if new_email is not None:+ updates.append('email = %s')+ params.append(new_email)if not updates:return jsonify({"message": "No fields to update"}), 400@@ -153,6 +179,8 @@ def update_user(user_id):details_list.append(f"admin status to {data['is_admin']}")if 'is_active' in data:details_list.append(f"active status to {data['is_active']}")+ if new_email is not None:+ details_list.append("email address")if details_list:details = 'Updated user: set ' + ', '.join(details_list)create_audit_log('UPDATE_USER', target_type='User', target_id=user_id, details=details)diff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex f535049..92a5d11 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -1035,7 +1035,7 @@<div class="form-group"><label for="editEmail">Email</label>- <input type="email" id="editEmail" class="form-control" disabled>+ <input type="email" id="editEmail" class="form-control"></div><div class="form-group">@@ -1154,6 +1154,7 @@<th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 40px;">ID</th><th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 120px;">Username</th><th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 180px;">Email</th>+ <th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 90px;">Provider</th><th style="padding: 12px 8px; text-align: left; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 120px;">Name</th><th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 80px;">Admin</th><th style="padding: 12px 8px; text-align: center; font-weight: 600; color: var(--text-color); border-right: 1px solid var(--border-color); min-width: 80px;">Active</th>diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex 5bfc509..3e38d1f 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -2082,6 +2082,17 @@ async function loadUsers() {emailCell.textContent = user.email;emailCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-size: 0.9em;';row.appendChild(emailCell);++ // Auth provider (Local / OIDC)+ const providerCell = document.createElement('td');+ const providerBadge = document.createElement('span');+ const isOidc = user.auth_provider === 'oidc';+ providerBadge.className = `badge ${isOidc ? 'badge-primary' : 'badge-secondary'}`;+ providerBadge.textContent = isOidc ? 'OIDC' : 'Local';+ providerBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';+ providerCell.appendChild(providerBadge);+ providerCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';+ row.appendChild(providerCell);// Nameconst nameCell = document.createElement('td');@@ -2304,7 +2315,8 @@ async function saveUserChanges() {},body: JSON.stringify({is_active: editUserActive.checked,- is_admin: editUserAdmin.checked+ is_admin: editUserAdmin.checked,+ email: editEmail.value.trim()})});diff --git a/tests/test_admin_users.py b/tests/test_admin_users.pynew file mode 100644index 0000000..e8fef59--- /dev/null+++ b/tests/test_admin_users.py@@ -0,0 +1,67 @@+"""Admin user management (#134): the users list exposes each account's+auth provider, and an admin can correct a user's email address."""+import pytest+++def _find_user(client, admin_headers, username):+ r = client.get("/api/admin/users", headers=admin_headers)+ assert r.status_code == 200, r.get_data(as_text=True)+ for user in r.get_json():+ if user["username"] == username:+ return user+ raise AssertionError(f"user {username} not in admin list")+++def test_users_list_includes_auth_provider(client, admin_user, user_factory):+ plain = user_factory()+ user = _find_user(client, admin_user["headers"], plain["username"])+ assert user["auth_provider"] == "local"+ # The raw OIDC subject must never leak into the list payload.+ assert "oidc_sub" not in user+++def test_admin_can_change_user_email(client, admin_user, user_factory):+ plain = user_factory()+ user = _find_user(client, admin_user["headers"], plain["username"])++ r = client.put(f"/api/admin/users/{user['id']}",+ headers=admin_user["headers"],+ json={"email": "[email protected]"})+ assert r.status_code == 200, r.get_data(as_text=True)++ user = _find_user(client, admin_user["headers"], plain["username"])+ assert user["email"] == "[email protected]"+++def test_admin_email_change_validation(client, admin_user, user_factory):+ first = user_factory()+ second = user_factory()+ first_rec = _find_user(client, admin_user["headers"], first["username"])+ second_rec = _find_user(client, admin_user["headers"], second["username"])++ # Malformed address.+ r = client.put(f"/api/admin/users/{second_rec['id']}",+ headers=admin_user["headers"],+ json={"email": "not-an-email"})+ assert r.status_code == 400, r.get_data(as_text=True)++ # Address already used by another account.+ r = client.put(f"/api/admin/users/{second_rec['id']}",+ headers=admin_user["headers"],+ json={"email": first_rec["email"]})+ assert r.status_code == 400, r.get_data(as_text=True)++ # Keeping one's own current address is not a conflict.+ r = client.put(f"/api/admin/users/{second_rec['id']}",+ headers=admin_user["headers"],+ json={"email": second_rec["email"]})+ assert r.status_code == 200, r.get_data(as_text=True)+++def test_non_admin_cannot_use_admin_endpoints(client, user_factory):+ plain = user_factory()+ r = client.get("/api/admin/users", headers=plain["headers"])+ assert r.status_code in (401, 403)+ r = client.put("/api/admin/users/1", headers=plain["headers"],+ json={"email": "[email protected]"})+ assert r.status_code in (401, 403)