Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a966d0bc8e | ||
|
|
753339c28a | ||
|
|
1d641288e5 | ||
|
|
e58a58e766 | ||
|
|
e0bcda6e7c | ||
|
|
f4419f6a72 |
@@ -143,6 +143,12 @@ def serve_menu_js() -> FileResponse:
|
||||
return FileResponse(static_path / "menu.js")
|
||||
|
||||
|
||||
@app.get("/auth-utils.js", include_in_schema=False)
|
||||
def serve_auth_utils_js() -> FileResponse:
|
||||
"""Serve the shared auth utilities JavaScript."""
|
||||
return FileResponse(static_path / "auth-utils.js")
|
||||
|
||||
|
||||
@app.get("/api/")
|
||||
def read_root(token: Annotated[str, Depends(verify_token)]) -> dict:
|
||||
"""API root endpoint (requires authentication)."""
|
||||
|
||||
@@ -6,7 +6,7 @@ import logging
|
||||
from baby_monitor.repositories.interfaces import (
|
||||
TokenRepositoryInterface,
|
||||
)
|
||||
from baby_monitor.repositories.token.memory_token import (
|
||||
from baby_monitor.repositories.token import (
|
||||
InMemoryTokenRepository,
|
||||
)
|
||||
|
||||
@@ -43,7 +43,7 @@ def _initialize_token_repository() -> TokenRepositoryInterface:
|
||||
) from e
|
||||
|
||||
try:
|
||||
from baby_monitor.repositories.token.redis_token import (
|
||||
from baby_monitor.repositories.token import (
|
||||
RedisTokenRepository,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Token repository implementations and configurations."""
|
||||
|
||||
from .default_ttl import DEFAULT_TTL
|
||||
from .memory_token import InMemoryTokenRepository
|
||||
from .redis_token import RedisTokenRepository
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_TTL",
|
||||
"InMemoryTokenRepository",
|
||||
"RedisTokenRepository",
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Definition of Token default TTL."""
|
||||
|
||||
DEFAULT_TTL = 28800 # seconds -> 8 hours
|
||||
@@ -3,6 +3,7 @@
|
||||
from datetime import datetime, timedelta, UTC
|
||||
|
||||
from baby_monitor.repositories.interfaces import TokenRepositoryInterface
|
||||
from baby_monitor.repositories.token import DEFAULT_TTL
|
||||
|
||||
|
||||
class InMemoryTokenRepository(TokenRepositoryInterface):
|
||||
@@ -16,9 +17,8 @@ class InMemoryTokenRepository(TokenRepositoryInterface):
|
||||
def __init__(self) -> None:
|
||||
# token -> (user_id, expiry_time)
|
||||
self._tokens: dict[str, tuple[int, datetime]] = {}
|
||||
self._default_ttl = 3600 # Store default TTL for sliding expiration
|
||||
|
||||
def store(self, token: str, user_id: int, ttl: int = 3600) -> None:
|
||||
def store(self, token: str, user_id: int, ttl: int = DEFAULT_TTL) -> None:
|
||||
"""Store a token with TTL (time to live in seconds)."""
|
||||
expiry = datetime.now(UTC) + timedelta(seconds=ttl)
|
||||
self._tokens[token] = (user_id, expiry)
|
||||
@@ -39,7 +39,7 @@ class InMemoryTokenRepository(TokenRepositoryInterface):
|
||||
return None
|
||||
|
||||
# Sliding expiration: extend the token lifetime
|
||||
new_expiry = datetime.now(UTC) + timedelta(seconds=self._default_ttl)
|
||||
new_expiry = datetime.now(UTC) + timedelta(seconds=DEFAULT_TTL)
|
||||
self._tokens[token] = (user_id, new_expiry)
|
||||
|
||||
return user_id
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
from typing import Any
|
||||
|
||||
from baby_monitor.repositories.interfaces import TokenRepositoryInterface
|
||||
from baby_monitor.repositories.token import DEFAULT_TTL
|
||||
|
||||
|
||||
class RedisTokenRepository(TokenRepositoryInterface):
|
||||
"""
|
||||
Redis-based token storage.
|
||||
|
||||
Requires redis package: pip install redis
|
||||
Set REDIS_URI environment variable (e.g., redis://localhost:6379/0)
|
||||
This implementation uses Redis to store tokens with TTL. Implements sliding expiration.
|
||||
"""
|
||||
|
||||
def __init__(self, redis_client: Any) -> None:
|
||||
@@ -21,9 +21,8 @@ class RedisTokenRepository(TokenRepositoryInterface):
|
||||
redis_client: Redis client instance from redis.from_url()
|
||||
"""
|
||||
self.redis = redis_client
|
||||
self.default_ttl = 3600 # Store default TTL for sliding expiration
|
||||
|
||||
def store(self, token: str, user_id: int, ttl: int = 3600) -> None:
|
||||
def store(self, token: str, user_id: int, ttl: int = DEFAULT_TTL) -> None:
|
||||
"""Store a token with TTL (time to live in seconds)."""
|
||||
key = f"token:{token}"
|
||||
self.redis.setex(key, ttl, str(user_id))
|
||||
@@ -37,7 +36,7 @@ class RedisTokenRepository(TokenRepositoryInterface):
|
||||
user_id_str = self.redis.get(key)
|
||||
if user_id_str:
|
||||
# Sliding expiration: extend the token lifetime
|
||||
self.redis.expire(key, self.default_ttl)
|
||||
self.redis.expire(key, DEFAULT_TTL)
|
||||
return int(user_id_str)
|
||||
return None
|
||||
|
||||
|
||||
@@ -211,12 +211,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Get child ID from URL if editing
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
|
||||
@@ -424,35 +424,33 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated and is admin
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
let allUsers = [];
|
||||
let userToDelete = null;
|
||||
|
||||
// Verify user is admin and load data
|
||||
// Load data
|
||||
fetch("/api/me", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((user) => {
|
||||
if (!user.is_admin) {
|
||||
alert("Access denied. Admin privileges required.");
|
||||
window.location.href = "/";
|
||||
}
|
||||
// Load users after verifying admin status
|
||||
loadUsers();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error verifying admin status:", error);
|
||||
window.location.href = "/login.html";
|
||||
});
|
||||
.then((response) => response.json())
|
||||
.then((user) => {
|
||||
if (!user.is_admin) {
|
||||
alert("Access denied. Admin privileges required.");
|
||||
window.location.href = "/";
|
||||
}
|
||||
// Load users after verifying admin status
|
||||
loadUsers();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error verifying admin status:", error);
|
||||
window.location.href = "/login.html";
|
||||
});
|
||||
|
||||
async function loadUsers() {
|
||||
const container = document.getElementById("userListContainer");
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Redirect to login page with return URL
|
||||
* @param {string} returnUrl - The URL to return to after login (defaults to current page)
|
||||
*/
|
||||
function redirectToLogin(returnUrl) {
|
||||
const url = returnUrl || window.location.pathname + window.location.search;
|
||||
window.location.href = `/login.html?return=${encodeURIComponent(url)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has valid token, redirect to login if not
|
||||
* @returns {string|null} - Returns token if valid, redirects to login if not
|
||||
*/
|
||||
function getToken() {
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
redirectToLogin();
|
||||
return null;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
@@ -266,12 +266,10 @@
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
|
||||
<script src="/menu.js"></script>
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Initialize burger menu
|
||||
initBurgerMenu({ includeHome: true });
|
||||
|
||||
@@ -303,12 +303,10 @@
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
|
||||
<script src="/menu.js"></script>
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Initialize burger menu
|
||||
initBurgerMenu({ includeHome: true });
|
||||
|
||||
@@ -236,59 +236,47 @@
|
||||
</div>
|
||||
|
||||
<script src="/menu.js"></script>
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
const token = localStorage.getItem("access_token");
|
||||
const token = getToken();
|
||||
const username = localStorage.getItem("username");
|
||||
|
||||
// Check if user is logged in
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
} else {
|
||||
// Fetch current user info including admin status
|
||||
fetch("/api/me", {
|
||||
// Fetch current user info including admin status
|
||||
fetch("/api/me", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((user) => {
|
||||
if (!user) return; // Early exit if redirected
|
||||
|
||||
// Initialize burger menu
|
||||
initBurgerMenu({
|
||||
includeHome: true,
|
||||
});
|
||||
|
||||
// Check if user has any children
|
||||
return fetch("/api/children", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
} else {
|
||||
// Token invalid, redirect to login
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("username");
|
||||
window.location.href = "/login.html";
|
||||
throw new Error("Authentication failed");
|
||||
.then((response) => response.json())
|
||||
.then((children) => {
|
||||
// If no children, show welcome message with option to add
|
||||
if (children.length === 0) {
|
||||
showNoChildrenMessage();
|
||||
return;
|
||||
}
|
||||
})
|
||||
.then((user) => {
|
||||
// Initialize burger menu
|
||||
initBurgerMenu({
|
||||
includeHome: true,
|
||||
});
|
||||
|
||||
// Check if user has any children
|
||||
return fetch("/api/children", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((children) => {
|
||||
// If no children, show welcome message with option to add
|
||||
if (children.length === 0) {
|
||||
showNoChildrenMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
// Load feeding status and show content
|
||||
loadFeedingStatus(children);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error:", error);
|
||||
// Load feeding status and show content
|
||||
loadFeedingStatus(children);
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error:", error);
|
||||
});
|
||||
|
||||
function showNoChildrenMessage() {
|
||||
const content = document.getElementById("content");
|
||||
|
||||
@@ -242,12 +242,10 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Determine return URL based on referrer
|
||||
function getReturnUrl() {
|
||||
|
||||
@@ -199,12 +199,10 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Determine return URL based on referrer
|
||||
function getReturnUrl() {
|
||||
|
||||
@@ -189,12 +189,10 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Determine return URL based on referrer
|
||||
function getReturnUrl() {
|
||||
|
||||
@@ -82,10 +82,36 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Check if redirected due to expired session
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const returnUrl = params.get("return");
|
||||
|
||||
const form = document.getElementById("loginForm");
|
||||
const messageDiv = document.getElementById("message");
|
||||
const loginButton = document.getElementById("loginButton");
|
||||
|
||||
// Show session expired message if redirected from another page
|
||||
if (returnUrl) {
|
||||
showMessage("Your session has expired. Please log in again.", "error");
|
||||
}
|
||||
|
||||
// Clear user-specific cache data on login
|
||||
function clearUserCache() {
|
||||
const keysToRemove = [
|
||||
'lastDiaperChildFilter',
|
||||
'lastFeedingChildFilter',
|
||||
'lastSleepChildFilter',
|
||||
'lastDiaperTimeRange',
|
||||
'lastFeedingTimeRange'
|
||||
];
|
||||
|
||||
keysToRemove.forEach(key => {
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
console.log('Cleared user cache on login');
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -109,13 +135,23 @@
|
||||
|
||||
if (response.ok) {
|
||||
showMessage(data.message, "success");
|
||||
|
||||
// Store token in localStorage
|
||||
localStorage.setItem("access_token", data.access_token);
|
||||
localStorage.setItem("username", data.username);
|
||||
|
||||
// Clear stale user preferences from previous sessions
|
||||
clearUserCache();
|
||||
|
||||
// Redirect based on is_admin from login response
|
||||
// Check for return URL parameter
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const returnUrl = params.get("return");
|
||||
|
||||
// Redirect based on return URL or is_admin from login response
|
||||
setTimeout(() => {
|
||||
if (data.is_admin === true) {
|
||||
if (returnUrl) {
|
||||
window.location.href = returnUrl;
|
||||
} else if (data.is_admin === true) {
|
||||
window.location.href = "/admin.html";
|
||||
} else {
|
||||
window.location.href = "/";
|
||||
|
||||
@@ -469,11 +469,9 @@
|
||||
</div>
|
||||
|
||||
<script src="/menu.js"></script>
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Initialize burger menu
|
||||
initBurgerMenu({ includeHome: true });
|
||||
@@ -495,7 +493,7 @@
|
||||
currentUser = await userResponse.json();
|
||||
document.getElementById("username").value = currentUser.username;
|
||||
} else {
|
||||
window.location.href = "/login.html";
|
||||
redirectToLogin();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -852,8 +850,10 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Load data on page load
|
||||
loadData();
|
||||
// Load data on page load (only if authenticated)
|
||||
if (token) {
|
||||
loadData();
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -313,13 +313,9 @@
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
|
||||
<script src="/menu.js"></script>
|
||||
<script src="/auth-utils.js"></script>
|
||||
<script>
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
// Check if user is logged in
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
const token = getToken();
|
||||
|
||||
// Initialize burger menu
|
||||
initBurgerMenu({ includeHome: true });
|
||||
@@ -345,13 +341,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
document
|
||||
.getElementById("timeRangeFilter")
|
||||
.addEventListener("change", function () {
|
||||
// Save selection to localStorage
|
||||
localStorage.setItem("lastSleepTimeRange", this.value);
|
||||
loadData();
|
||||
});
|
||||
function attachTimeRangeListener() {
|
||||
const timeRangeFilter = document.getElementById("timeRangeFilter");
|
||||
if (timeRangeFilter) {
|
||||
timeRangeFilter.addEventListener("change", function () {
|
||||
// Save selection to localStorage
|
||||
localStorage.setItem("lastSleepTimeRange", this.value);
|
||||
renderCharts();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
@@ -443,6 +442,9 @@
|
||||
attachChildFilterListener();
|
||||
}
|
||||
|
||||
// Always attach time range listener after recreating the controls
|
||||
attachTimeRangeListener();
|
||||
|
||||
renderCharts();
|
||||
} catch (error) {
|
||||
console.error("Error loading data:", error);
|
||||
|
||||
Reference in New Issue
Block a user