ruff and prettier fixes
This commit is contained in:
@@ -6,6 +6,7 @@ from datetime import datetime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
Base = DeclarativeBase
|
||||
else:
|
||||
from baby_monitor.repositories.dependencies.get_database import Base
|
||||
|
||||
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
Base = DeclarativeBase
|
||||
else:
|
||||
from baby_monitor.repositories.dependencies.get_database import Base
|
||||
@@ -21,9 +22,7 @@ class Invitation(Base):
|
||||
|
||||
__tablename__ = "invitations"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer, primary_key=True, autoincrement=True
|
||||
)
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
token: Mapped[str] = mapped_column(String, unique=True, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False
|
||||
@@ -32,9 +31,7 @@ class Invitation(Base):
|
||||
DateTime(timezone=True), nullable=False
|
||||
)
|
||||
created_by_user_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
is_consumed: Mapped[bool] = mapped_column(
|
||||
Boolean, default=False, nullable=False
|
||||
)
|
||||
is_consumed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
consumed_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
|
||||
@@ -34,9 +34,7 @@ class SQLiteInvitationRepository(InvitationRepositoryInterface):
|
||||
# Convert timezone-aware datetimes to naive UTC for SQLite
|
||||
created_at_utc = datetime.now(UTC).replace(tzinfo=None)
|
||||
expires_at_utc = (
|
||||
expires_at.replace(tzinfo=None)
|
||||
if expires_at.tzinfo
|
||||
else expires_at
|
||||
expires_at.replace(tzinfo=None) if expires_at.tzinfo else expires_at
|
||||
)
|
||||
|
||||
invitation = Invitation(
|
||||
@@ -60,9 +58,7 @@ class SQLiteInvitationRepository(InvitationRepositoryInterface):
|
||||
Returns:
|
||||
True if valid and not consumed, False otherwise
|
||||
"""
|
||||
invitation = (
|
||||
self.db.query(Invitation).filter(Invitation.token == token).first()
|
||||
)
|
||||
invitation = self.db.query(Invitation).filter(Invitation.token == token).first()
|
||||
|
||||
if not invitation:
|
||||
return False
|
||||
@@ -88,9 +84,7 @@ class SQLiteInvitationRepository(InvitationRepositoryInterface):
|
||||
Returns:
|
||||
True if successfully consumed, False if invalid or already used
|
||||
"""
|
||||
invitation = (
|
||||
self.db.query(Invitation).filter(Invitation.token == token).first()
|
||||
)
|
||||
invitation = self.db.query(Invitation).filter(Invitation.token == token).first()
|
||||
|
||||
if not invitation:
|
||||
return False
|
||||
@@ -114,7 +108,5 @@ class SQLiteInvitationRepository(InvitationRepositoryInterface):
|
||||
def cleanup_expired(self) -> None:
|
||||
"""Remove expired invitation tokens from storage."""
|
||||
now_utc = datetime.now(UTC).replace(tzinfo=None)
|
||||
self.db.query(Invitation).filter(
|
||||
Invitation.expires_at < now_utc
|
||||
).delete()
|
||||
self.db.query(Invitation).filter(Invitation.expires_at < now_utc).delete()
|
||||
self.db.commit()
|
||||
|
||||
@@ -52,9 +52,7 @@ def verify_token(
|
||||
|
||||
def verify_admin(
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
user_repo: Annotated[
|
||||
UserRepositoryInterface, Depends(get_user_repository)
|
||||
],
|
||||
user_repo: Annotated[UserRepositoryInterface, Depends(get_user_repository)],
|
||||
) -> int:
|
||||
"""Verify the user is an admin and return user_id."""
|
||||
# First try to get user from database
|
||||
@@ -63,9 +61,7 @@ def verify_admin(
|
||||
if user:
|
||||
# Database user - check is_admin field
|
||||
if not user.get("is_admin", False):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="Admin access required"
|
||||
)
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
return user_id
|
||||
|
||||
# If not in database but has valid token with user_id=1,
|
||||
@@ -80,12 +76,8 @@ def verify_admin(
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login(
|
||||
credentials: LoginRequest,
|
||||
token_repo: Annotated[
|
||||
TokenRepositoryInterface, Depends(get_token_repository)
|
||||
],
|
||||
user_repo: Annotated[
|
||||
UserRepositoryInterface, Depends(get_user_repository)
|
||||
],
|
||||
token_repo: Annotated[TokenRepositoryInterface, Depends(get_token_repository)],
|
||||
user_repo: Annotated[UserRepositoryInterface, Depends(get_user_repository)],
|
||||
creds_repo: Annotated[
|
||||
CredentialsRepositoryInterface, Depends(get_credentials_repository)
|
||||
],
|
||||
@@ -114,9 +106,7 @@ def login(
|
||||
)
|
||||
|
||||
# Fallback to admin credentials from environment
|
||||
if creds_repo.verify_admin_credentials(
|
||||
credentials.username, credentials.password
|
||||
):
|
||||
if creds_repo.verify_admin_credentials(credentials.username, credentials.password):
|
||||
# Generate a secure random token
|
||||
access_token = secrets.token_urlsafe(32)
|
||||
# Store token with user_id (hardcoded 1 for admin)
|
||||
@@ -129,9 +119,7 @@ def login(
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=401, detail="Invalid username or password"
|
||||
)
|
||||
raise HTTPException(status_code=401, detail="Invalid username or password")
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
@@ -162,15 +150,11 @@ def verify_invitation(
|
||||
@router.post("/register", response_model=RegisterResponse)
|
||||
def register(
|
||||
request: RegisterRequest,
|
||||
user_repo: Annotated[
|
||||
UserRepositoryInterface, Depends(get_user_repository)
|
||||
],
|
||||
user_repo: Annotated[UserRepositoryInterface, Depends(get_user_repository)],
|
||||
invitation_repo: Annotated[
|
||||
InvitationRepositoryInterface, Depends(get_invitation_repository)
|
||||
],
|
||||
token_repo: Annotated[
|
||||
TokenRepositoryInterface, Depends(get_token_repository)
|
||||
],
|
||||
token_repo: Annotated[TokenRepositoryInterface, Depends(get_token_repository)],
|
||||
) -> RegisterResponse:
|
||||
"""
|
||||
Register a new user with an invitation token.
|
||||
@@ -218,9 +202,7 @@ def register(
|
||||
@router.get("/me")
|
||||
def get_current_user(
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
user_repo: Annotated[
|
||||
UserRepositoryInterface, Depends(get_user_repository)
|
||||
],
|
||||
user_repo: Annotated[UserRepositoryInterface, Depends(get_user_repository)],
|
||||
creds_repo: Annotated[
|
||||
CredentialsRepositoryInterface, Depends(get_credentials_repository)
|
||||
],
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Baby Monitor - Admin</title>
|
||||
<style>
|
||||
* {
|
||||
@@ -12,7 +12,9 @@
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
@@ -55,7 +57,7 @@
|
||||
}
|
||||
|
||||
.section h2::before {
|
||||
content: '🔗';
|
||||
content: "🔗";
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
@@ -68,7 +70,9 @@
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
transition:
|
||||
transform 0.2s,
|
||||
box-shadow 0.2s;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -120,7 +124,7 @@
|
||||
background: white;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-family: "Courier New", monospace;
|
||||
font-size: 13px;
|
||||
word-break: break-all;
|
||||
color: #333;
|
||||
@@ -148,7 +152,7 @@
|
||||
|
||||
.info-box {
|
||||
background: #e7f3ff;
|
||||
border-left: 4px solid #2196F3;
|
||||
border-left: 4px solid #2196f3;
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
margin-top: 15px;
|
||||
@@ -190,7 +194,7 @@
|
||||
|
||||
<div class="section">
|
||||
<h2>Generate Invitation Link</h2>
|
||||
<p style="color: #666; margin-bottom: 15px; font-size: 14px;">
|
||||
<p style="color: #666; margin-bottom: 15px; font-size: 14px">
|
||||
Create a secure one-time link to invite a new user to register.
|
||||
</p>
|
||||
<button class="button" id="generateBtn" onclick="generateLink()">
|
||||
@@ -206,62 +210,60 @@
|
||||
</button>
|
||||
</div>
|
||||
<div class="info-box">
|
||||
ℹ️ This link expires in 24 hours and can only be used once.
|
||||
Share it securely with the intended user.
|
||||
ℹ️ This link expires in 24 hours and can only be used once. Share it
|
||||
securely with the intended user.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="error" class="error"></div>
|
||||
</div>
|
||||
|
||||
<button class="button logout-button" onclick="logout()">
|
||||
Logout
|
||||
</button>
|
||||
<button class="button logout-button" onclick="logout()">Logout</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Check if user is authenticated and is admin
|
||||
const token = localStorage.getItem('access_token');
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = '/login.html';
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
|
||||
// Verify user is admin
|
||||
fetch('/api/me', {
|
||||
fetch("/api/me", {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
}
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(user => {
|
||||
.then((response) => response.json())
|
||||
.then((user) => {
|
||||
if (!user.is_admin) {
|
||||
alert('Access denied. Admin privileges required.');
|
||||
window.location.href = '/';
|
||||
alert("Access denied. Admin privileges required.");
|
||||
window.location.href = "/";
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error verifying admin status:', error);
|
||||
window.location.href = '/login.html';
|
||||
.catch((error) => {
|
||||
console.error("Error verifying admin status:", error);
|
||||
window.location.href = "/login.html";
|
||||
});
|
||||
|
||||
async function generateLink() {
|
||||
const btn = document.getElementById('generateBtn');
|
||||
const linkContainer = document.getElementById('linkContainer');
|
||||
const linkText = document.getElementById('linkText');
|
||||
const errorDiv = document.getElementById('error');
|
||||
const btn = document.getElementById("generateBtn");
|
||||
const linkContainer = document.getElementById("linkContainer");
|
||||
const linkText = document.getElementById("linkText");
|
||||
const errorDiv = document.getElementById("error");
|
||||
|
||||
// Disable button and show loading state
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Generating...';
|
||||
errorDiv.classList.remove('show');
|
||||
btn.textContent = "Generating...";
|
||||
errorDiv.classList.remove("show");
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/generate-invitation', {
|
||||
method: 'POST',
|
||||
const response = await fetch("/api/admin/generate-invitation", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -276,39 +278,41 @@
|
||||
|
||||
// Display the link
|
||||
linkText.textContent = inviteUrl;
|
||||
linkContainer.classList.add('show');
|
||||
|
||||
linkContainer.classList.add("show");
|
||||
} catch (error) {
|
||||
errorDiv.textContent = `Error: ${error.message}`;
|
||||
errorDiv.classList.add('show');
|
||||
errorDiv.classList.add("show");
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Generate New Invitation Link';
|
||||
btn.textContent = "Generate New Invitation Link";
|
||||
}
|
||||
}
|
||||
|
||||
function copyLink() {
|
||||
const linkText = document.getElementById('linkText').textContent;
|
||||
const copyBtn = document.getElementById('copyBtn');
|
||||
const linkText = document.getElementById("linkText").textContent;
|
||||
const copyBtn = document.getElementById("copyBtn");
|
||||
|
||||
navigator.clipboard.writeText(linkText).then(() => {
|
||||
navigator.clipboard
|
||||
.writeText(linkText)
|
||||
.then(() => {
|
||||
// Show success state
|
||||
copyBtn.textContent = '✓ Copied!';
|
||||
copyBtn.classList.add('copied');
|
||||
copyBtn.textContent = "✓ Copied!";
|
||||
copyBtn.classList.add("copied");
|
||||
|
||||
// Reset after 2 seconds
|
||||
setTimeout(() => {
|
||||
copyBtn.textContent = 'Copy';
|
||||
copyBtn.classList.remove('copied');
|
||||
copyBtn.textContent = "Copy";
|
||||
copyBtn.classList.remove("copied");
|
||||
}, 2000);
|
||||
}).catch(err => {
|
||||
alert('Failed to copy link: ' + err);
|
||||
})
|
||||
.catch((err) => {
|
||||
alert("Failed to copy link: " + err);
|
||||
});
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('access_token');
|
||||
window.location.href = '/login.html';
|
||||
localStorage.removeItem("access_token");
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -129,9 +129,7 @@
|
||||
<div class="menu-backdrop" id="menuBackdrop"></div>
|
||||
|
||||
<div class="menu-overlay" id="menuOverlay">
|
||||
<div class="menu-item logout" id="menuLogout">
|
||||
🚪 Logout
|
||||
</div>
|
||||
<div class="menu-item logout" id="menuLogout">🚪 Logout</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Baby Monitor - Register</title>
|
||||
<style>
|
||||
* {
|
||||
@@ -12,7 +12,9 @@
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
@@ -80,7 +82,9 @@
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
transition:
|
||||
transform 0.2s,
|
||||
box-shadow 0.2s;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
@@ -145,13 +149,17 @@
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.info-box {
|
||||
background: #e7f3ff;
|
||||
border-left: 4px solid #2196F3;
|
||||
border-left: 4px solid #2196f3;
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 20px;
|
||||
@@ -178,7 +186,7 @@
|
||||
<div class="container">
|
||||
<div id="loadingContainer" class="loading-container">
|
||||
<div class="spinner"></div>
|
||||
<p style="color: #666;">Validating invitation...</p>
|
||||
<p style="color: #666">Validating invitation...</p>
|
||||
</div>
|
||||
|
||||
<div id="registerContainer" class="hidden">
|
||||
@@ -199,7 +207,7 @@
|
||||
minlength="3"
|
||||
autocomplete="username"
|
||||
placeholder="Choose a username"
|
||||
>
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
@@ -212,7 +220,7 @@
|
||||
minlength="8"
|
||||
autocomplete="new-password"
|
||||
placeholder="Choose a strong password"
|
||||
>
|
||||
/>
|
||||
<div class="password-requirements">
|
||||
<ul>
|
||||
<li>At least 8 characters long</li>
|
||||
@@ -231,7 +239,7 @@
|
||||
minlength="8"
|
||||
autocomplete="new-password"
|
||||
placeholder="Re-enter your password"
|
||||
>
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="button" id="submitBtn">
|
||||
@@ -245,13 +253,13 @@
|
||||
<p class="subtitle">This invitation link is invalid or has expired</p>
|
||||
<div class="info-box">
|
||||
This could mean:
|
||||
<ul style="margin: 10px 0 0 20px; color: #555;">
|
||||
<ul style="margin: 10px 0 0 20px; color: #555">
|
||||
<li>The invitation has already been used</li>
|
||||
<li>The invitation has expired (24 hours)</li>
|
||||
<li>The invitation link is incorrect</li>
|
||||
</ul>
|
||||
</div>
|
||||
<p style="text-align: center; color: #666; margin-top: 20px;">
|
||||
<p style="text-align: center; color: #666; margin-top: 20px">
|
||||
Please contact an administrator for a new invitation link.
|
||||
</p>
|
||||
</div>
|
||||
@@ -262,10 +270,10 @@
|
||||
|
||||
// Extract token from URL query parameters
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
invitationToken = urlParams.get('token');
|
||||
invitationToken = urlParams.get("token");
|
||||
|
||||
// Validate token on page load
|
||||
window.addEventListener('DOMContentLoaded', async () => {
|
||||
window.addEventListener("DOMContentLoaded", async () => {
|
||||
if (!invitationToken) {
|
||||
showInvalidToken();
|
||||
return;
|
||||
@@ -273,7 +281,9 @@
|
||||
|
||||
try {
|
||||
// Verify the invitation token
|
||||
const response = await fetch(`/api/verify-invitation?token=${encodeURIComponent(invitationToken)}`);
|
||||
const response = await fetch(
|
||||
`/api/verify-invitation?token=${encodeURIComponent(invitationToken)}`,
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
showRegisterForm();
|
||||
@@ -281,51 +291,54 @@
|
||||
showInvalidToken();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error validating invitation:', error);
|
||||
console.error("Error validating invitation:", error);
|
||||
showInvalidToken();
|
||||
}
|
||||
});
|
||||
|
||||
function showRegisterForm() {
|
||||
document.getElementById('loadingContainer').classList.add('hidden');
|
||||
document.getElementById('registerContainer').classList.remove('hidden');
|
||||
document.getElementById("loadingContainer").classList.add("hidden");
|
||||
document.getElementById("registerContainer").classList.remove("hidden");
|
||||
}
|
||||
|
||||
function showInvalidToken() {
|
||||
document.getElementById('loadingContainer').classList.add('hidden');
|
||||
document.getElementById('invalidTokenContainer').classList.remove('hidden');
|
||||
document.getElementById("loadingContainer").classList.add("hidden");
|
||||
document
|
||||
.getElementById("invalidTokenContainer")
|
||||
.classList.remove("hidden");
|
||||
}
|
||||
|
||||
async function handleRegister(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const username = document.getElementById('username').value;
|
||||
const password = document.getElementById('password').value;
|
||||
const confirmPassword = document.getElementById('confirmPassword').value;
|
||||
const errorDiv = document.getElementById('error');
|
||||
const successDiv = document.getElementById('success');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const username = document.getElementById("username").value;
|
||||
const password = document.getElementById("password").value;
|
||||
const confirmPassword =
|
||||
document.getElementById("confirmPassword").value;
|
||||
const errorDiv = document.getElementById("error");
|
||||
const successDiv = document.getElementById("success");
|
||||
const submitBtn = document.getElementById("submitBtn");
|
||||
|
||||
// Clear previous messages
|
||||
errorDiv.classList.remove('show');
|
||||
successDiv.classList.remove('show');
|
||||
errorDiv.classList.remove("show");
|
||||
successDiv.classList.remove("show");
|
||||
|
||||
// Validate passwords match
|
||||
if (password !== confirmPassword) {
|
||||
errorDiv.textContent = 'Passwords do not match!';
|
||||
errorDiv.classList.add('show');
|
||||
errorDiv.textContent = "Passwords do not match!";
|
||||
errorDiv.classList.add("show");
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable submit button
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Creating Account...';
|
||||
submitBtn.textContent = "Creating Account...";
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/register', {
|
||||
method: 'POST',
|
||||
const response = await fetch("/api/register", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: username,
|
||||
@@ -338,29 +351,31 @@
|
||||
|
||||
if (response.ok) {
|
||||
// Store the access token and username
|
||||
localStorage.setItem('access_token', data.access_token);
|
||||
localStorage.setItem('username', data.username);
|
||||
localStorage.setItem("access_token", data.access_token);
|
||||
localStorage.setItem("username", data.username);
|
||||
|
||||
// Show success message
|
||||
successDiv.textContent = 'Account created successfully! Redirecting...';
|
||||
successDiv.classList.add('show');
|
||||
successDiv.textContent =
|
||||
"Account created successfully! Redirecting...";
|
||||
successDiv.classList.add("show");
|
||||
|
||||
// Redirect to home page after a brief delay
|
||||
setTimeout(() => {
|
||||
window.location.href = '/';
|
||||
window.location.href = "/";
|
||||
}, 1500);
|
||||
} else {
|
||||
errorDiv.textContent = data.detail || 'Registration failed. Please try again.';
|
||||
errorDiv.classList.add('show');
|
||||
errorDiv.textContent =
|
||||
data.detail || "Registration failed. Please try again.";
|
||||
errorDiv.classList.add("show");
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Create Account';
|
||||
submitBtn.textContent = "Create Account";
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error);
|
||||
errorDiv.textContent = 'An error occurred. Please try again.';
|
||||
errorDiv.classList.add('show');
|
||||
console.error("Registration error:", error);
|
||||
errorDiv.textContent = "An error occurred. Please try again.";
|
||||
errorDiv.classList.add("show");
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Create Account';
|
||||
submitBtn.textContent = "Create Account";
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user