Update AppImage

This commit is contained in:
MacRimi
2025-11-07 20:05:29 +01:00
parent beefdd280f
commit 6836777629
6 changed files with 184 additions and 290 deletions

View File

@@ -7,7 +7,17 @@ import { AuthSetup } from "../components/auth-setup"
import { getApiUrl } from "../lib/api-config" import { getApiUrl } from "../lib/api-config"
export default function Home() { export default function Home() {
const [authState, setAuthState] = useState<"loading" | "setup" | "login" | "authenticated">("loading") const [authStatus, setAuthStatus] = useState<{
loading: boolean
authEnabled: boolean
authConfigured: boolean
authenticated: boolean
}>({
loading: true,
authEnabled: false,
authConfigured: false,
authenticated: false,
})
useEffect(() => { useEffect(() => {
checkAuthStatus() checkAuthStatus()
@@ -15,80 +25,61 @@ export default function Home() {
const checkAuthStatus = async () => { const checkAuthStatus = async () => {
try { try {
const token = localStorage.getItem("proxmenux-auth-token")
const response = await fetch(getApiUrl("/api/auth/status"), { const response = await fetch(getApiUrl("/api/auth/status"), {
method: "GET", headers: token ? { Authorization: `Bearer ${token}` } : {},
headers: {
"Content-Type": "application/json",
},
}) })
const data = await response.json() const data = await response.json()
if (!data.auth_enabled) { console.log("[v0] Auth status:", data)
// Auth no está habilitada, permitir acceso directo
setAuthState("authenticated")
return
}
// Auth está habilitada, verificar si hay token válido const authenticated = data.auth_enabled ? data.authenticated : true
const token = localStorage.getItem("proxmenux-auth-token")
if (!token) { setAuthStatus({
setAuthState("login") loading: false,
return authEnabled: data.auth_enabled,
} authConfigured: data.auth_configured,
authenticated,
// Verificar que el token sea válido
const verifyResponse = await fetch(getApiUrl("/api/auth/verify"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}) })
if (verifyResponse.ok) {
setAuthState("authenticated")
} else {
// Token inválido, limpiar y pedir login
localStorage.removeItem("proxmenux-auth-token")
localStorage.removeItem("proxmenux-saved-username")
localStorage.removeItem("proxmenux-saved-password")
setAuthState("login")
}
} catch (error) { } catch (error) {
console.error("Error checking auth status:", error) console.error("[v0] Failed to check auth status:", error)
// En caso de error, mostrar setup setAuthStatus({
setAuthState("setup") loading: false,
authEnabled: false,
authConfigured: false,
authenticated: true,
})
} }
} }
const handleSetupComplete = () => { const handleAuthComplete = () => {
setAuthState("login") checkAuthStatus()
} }
const handleLoginSuccess = () => { const handleLoginSuccess = () => {
setAuthState("authenticated") checkAuthStatus()
} }
if (authState === "loading") { if (authStatus.loading) {
return ( return (
<div className="min-h-screen bg-background flex items-center justify-center"> <div className="min-h-screen bg-background flex items-center justify-center">
<div className="text-center"> <div className="text-center space-y-4">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div> <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
<p className="mt-4 text-muted-foreground">Loading...</p> <p className="text-muted-foreground">Loading...</p>
</div> </div>
</div> </div>
) )
} }
if (authState === "setup") { if (authStatus.authEnabled && !authStatus.authenticated) {
return <AuthSetup onComplete={handleSetupComplete} />
}
if (authState === "login") {
return <Login onLogin={handleLoginSuccess} /> return <Login onLogin={handleLoginSuccess} />
} }
return <ProxmoxDashboard /> // Show dashboard in all other cases
return (
<>
{!authStatus.authConfigured && <AuthSetup onComplete={handleAuthComplete} />}
<ProxmoxDashboard />
</>
)
} }

View File

@@ -2,11 +2,10 @@
import type React from "react" import type React from "react"
import { useState, useEffect } from "react" import { useState } from "react"
import { Button } from "./ui/button" import { Button } from "./ui/button"
import { Input } from "./ui/input" import { Input } from "./ui/input"
import { Label } from "./ui/label" import { Label } from "./ui/label"
import { Checkbox } from "./ui/checkbox"
import { Lock, User, AlertCircle, Server } from "lucide-react" import { Lock, User, AlertCircle, Server } from "lucide-react"
import { getApiUrl } from "../lib/api-config" import { getApiUrl } from "../lib/api-config"
import Image from "next/image" import Image from "next/image"
@@ -18,49 +17,15 @@ interface LoginProps {
export function Login({ onLogin }: LoginProps) { export function Login({ onLogin }: LoginProps) {
const [username, setUsername] = useState("") const [username, setUsername] = useState("")
const [password, setPassword] = useState("") const [password, setPassword] = useState("")
const [rememberMe, setRememberMe] = useState(false)
const [error, setError] = useState("") const [error, setError] = useState("")
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
useEffect(() => {
const savedUsername = localStorage.getItem("proxmenux-saved-username")
const savedPassword = localStorage.getItem("proxmenux-saved-password")
if (savedUsername && savedPassword) {
setUsername(savedUsername)
setPassword(savedPassword)
setRememberMe(true)
// Auto-login si hay credenciales guardadas
handleAutoLogin(savedUsername, savedPassword)
}
}, [])
const handleAutoLogin = async (user: string, pass: string) => {
try {
const response = await fetch(getApiUrl("/api/auth/login"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: user, password: pass, remember_me: true }),
})
const data = await response.json()
if (response.ok && data.token) {
localStorage.setItem("proxmenux-auth-token", data.token)
onLogin()
}
} catch (err) {
console.log("Auto-login failed, showing login form")
}
}
const handleLogin = async (e: React.FormEvent) => { const handleLogin = async (e: React.FormEvent) => {
e.preventDefault() e.preventDefault()
setError("") setError("")
if (!username || !password) { if (!username || !password) {
setError("Por favor, introduce usuario y contraseña") setError("Please enter username and password")
return return
} }
@@ -70,30 +35,20 @@ export function Login({ onLogin }: LoginProps) {
const response = await fetch(getApiUrl("/api/auth/login"), { const response = await fetch(getApiUrl("/api/auth/login"), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, remember_me: rememberMe }), body: JSON.stringify({ username, password }),
}) })
const data = await response.json() const data = await response.json()
if (!response.ok) { if (!response.ok) {
throw new Error(data.error || "Fallo en el login") throw new Error(data.error || "Login failed")
} }
// Save token // Save token
localStorage.setItem("proxmenux-auth-token", data.token) localStorage.setItem("proxmenux-auth-token", data.token)
if (rememberMe) {
localStorage.setItem("proxmenux-saved-username", username)
localStorage.setItem("proxmenux-saved-password", password)
} else {
// Limpiar credenciales guardadas si no se marcó recordar
localStorage.removeItem("proxmenux-saved-username")
localStorage.removeItem("proxmenux-saved-password")
}
onLogin() onLogin()
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Fallo en el login") setError(err instanceof Error ? err.message : "Login failed")
} finally { } finally {
setLoading(false) setLoading(false)
} }
@@ -173,18 +128,6 @@ export function Login({ onLogin }: LoginProps) {
</div> </div>
</div> </div>
<div className="flex items-center space-x-2">
<Checkbox
id="remember-me"
checked={rememberMe}
onCheckedChange={(checked) => setRememberMe(checked as boolean)}
disabled={loading}
/>
<Label htmlFor="remember-me" className="text-sm font-normal cursor-pointer select-none">
Remember me
</Label>
</div>
<Button type="submit" className="w-full bg-blue-500 hover:bg-blue-600" disabled={loading}> <Button type="submit" className="w-full bg-blue-500 hover:bg-blue-600" disabled={loading}>
{loading ? "Signing in..." : "Sign In"} {loading ? "Signing in..." : "Sign In"}
</Button> </Button>

View File

@@ -1,7 +1,5 @@
"use client" "use client"
import type React from "react"
import { useState, useEffect, useMemo, useCallback } from "react" import { useState, useEffect, useMemo, useCallback } from "react"
import { Badge } from "./ui/badge" import { Badge } from "./ui/badge"
import { Button } from "./ui/button" import { Button } from "./ui/button"
@@ -55,13 +53,9 @@ interface FlaskSystemData {
interface FlaskSystemInfo { interface FlaskSystemInfo {
hostname: string hostname: string
uptime_seconds: number node_id: string
uptime_formatted: string uptime: string
health: { health_status: "healthy" | "warning" | "critical"
status: string
summary: string
}
timestamp: string
} }
export function ProxmoxDashboard() { export function ProxmoxDashboard() {
@@ -80,7 +74,6 @@ export function ProxmoxDashboard() {
const [showNavigation, setShowNavigation] = useState(true) const [showNavigation, setShowNavigation] = useState(true)
const [lastScrollY, setLastScrollY] = useState(0) const [lastScrollY, setLastScrollY] = useState(0)
const [showHealthModal, setShowHealthModal] = useState(false) const [showHealthModal, setShowHealthModal] = useState(false)
const [isAuthenticated, setIsAuthenticated] = useState(false)
const fetchSystemData = useCallback(async () => { const fetchSystemData = useCallback(async () => {
const apiUrl = getApiUrl("/api/system-info") const apiUrl = getApiUrl("/api/system-info")
@@ -101,26 +94,14 @@ export function ProxmoxDashboard() {
const data: FlaskSystemInfo = await response.json() const data: FlaskSystemInfo = await response.json()
const uptimeValue = const uptimeValue =
data.uptime_formatted && typeof data.uptime_formatted === "string" && data.uptime_formatted.trim() !== "" data.uptime && typeof data.uptime === "string" && data.uptime.trim() !== "" ? data.uptime : "N/A"
? data.uptime_formatted
: "N/A"
const healthStatus = data.health?.status || "healthy"
const mappedStatus =
healthStatus === "OK"
? "healthy"
: healthStatus === "WARNING"
? "warning"
: healthStatus === "CRITICAL"
? "critical"
: "healthy"
setSystemStatus({ setSystemStatus({
status: mappedStatus as "healthy" | "warning" | "critical", status: data.health_status || "healthy",
uptime: uptimeValue, uptime: uptimeValue,
lastUpdate: new Date().toLocaleTimeString("en-US", { hour12: false }), lastUpdate: new Date().toLocaleTimeString("en-US", { hour12: false }),
serverName: data.hostname || "Unknown", serverName: data.hostname || "Unknown",
nodeId: data.hostname || "Unknown", nodeId: data.node_id || "Unknown",
}) })
setIsServerConnected(true) setIsServerConnected(true)
} catch (error) { } catch (error) {
@@ -203,18 +184,6 @@ export function ProxmoxDashboard() {
setIsRefreshing(false) setIsRefreshing(false)
} }
const handleLogout = (e: React.MouseEvent) => {
e.stopPropagation()
localStorage.removeItem("proxmenux-auth-token")
localStorage.removeItem("proxmenux-saved-username")
localStorage.removeItem("proxmenux-saved-password")
window.location.href = "/"
}
useEffect(() => {
setIsAuthenticated(!!localStorage.getItem("proxmenux-auth-token"))
}, [])
const statusIcon = useMemo(() => { const statusIcon = useMemo(() => {
switch (systemStatus.status) { switch (systemStatus.status) {
case "healthy": case "healthy":
@@ -287,16 +256,18 @@ export function ProxmoxDashboard() {
className="border-b border-border bg-card sticky top-0 z-50 shadow-sm cursor-pointer hover:bg-accent/5 transition-colors" className="border-b border-border bg-card sticky top-0 z-50 shadow-sm cursor-pointer hover:bg-accent/5 transition-colors"
onClick={() => setShowHealthModal(true)} onClick={() => setShowHealthModal(true)}
> >
<div className="container mx-auto px-4 md:px-6 py-4"> <div className="container mx-auto px-4 md:px-6 py-4 md:py-4">
<div className="flex items-start justify-between gap-4"> {/* Logo and Title */}
<div className="flex items-center space-x-3"> <div className="flex items-start justify-between gap-3">
<div className="w-12 h-12 relative flex items-center justify-center bg-primary/10"> {/* Logo and Title */}
<div className="flex items-center space-x-2 md:space-x-3 min-w-0">
<div className="w-16 h-16 md:w-10 md:h-10 relative flex items-center justify-center bg-primary/10 flex-shrink-0">
<Image <Image
src="/images/proxmenux-logo.png" src="/images/proxmenux-logo.png"
alt="ProxMenux Logo" alt="ProxMenux Logo"
width={48} width={64}
height={48} height={64}
className="object-contain" className="object-contain md:w-10 md:h-10"
priority priority
onError={(e) => { onError={(e) => {
console.log("[v0] Logo failed to load, using fallback icon") console.log("[v0] Logo failed to load, using fallback icon")
@@ -308,25 +279,36 @@ export function ProxmoxDashboard() {
} }
}} }}
/> />
<Server className="h-6 w-6 text-primary absolute fallback-icon hidden" /> <Server className="h-8 w-8 md:h-6 md:w-6 text-primary absolute fallback-icon hidden" />
</div> </div>
<div> <div className="min-w-0">
<h1 className="text-xl font-semibold text-foreground">ProxMenux Monitor</h1> <h1 className="text-lg md:text-xl font-semibold text-foreground truncate">ProxMenux Monitor</h1>
<p className="text-sm text-muted-foreground hidden md:block">Proxmox System Dashboard</p> <p className="text-xs md:text-sm text-muted-foreground">Proxmox System Dashboard</p>
<div className="flex items-center space-x-2 mt-1"> <div className="lg:hidden flex items-center gap-1 text-xs text-muted-foreground mt-0.5">
<Server className="h-3 w-3 text-muted-foreground" /> <Server className="h-3 w-3" />
<span className="text-xs text-muted-foreground">Node: {systemStatus.serverName}</span> <span className="truncate">Node: {systemStatus.serverName}</span>
</div> </div>
</div> </div>
</div> </div>
<div className="flex items-center space-x-2 md:space-x-4"> {/* Desktop Actions */}
<div className="hidden md:flex items-center space-x-4"> <div className="hidden lg:flex items-center space-x-4">
<div className="flex items-center space-x-2">
<Server className="h-4 w-4 text-muted-foreground" />
<div className="text-sm">
<div className="font-medium text-foreground">Node: {systemStatus.serverName}</div>
</div>
</div>
<Badge variant="outline" className={statusColor}> <Badge variant="outline" className={statusColor}>
{statusIcon} {statusIcon}
<span className="ml-1 capitalize">{systemStatus.status}</span> <span className="ml-1 capitalize">{systemStatus.status}</span>
</Badge> </Badge>
<div className="text-sm text-muted-foreground whitespace-nowrap">
Uptime: {systemStatus.uptime || "N/A"}
</div>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
@@ -337,13 +319,20 @@ export function ProxmoxDashboard() {
disabled={isRefreshing} disabled={isRefreshing}
className="border-border/50 bg-transparent hover:bg-secondary" className="border-border/50 bg-transparent hover:bg-secondary"
> >
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} /> <RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`} />
Refresh
</Button> </Button>
<div onClick={(e) => e.stopPropagation()}>
<ThemeToggle />
</div>
</div> </div>
<div className="flex md:hidden items-center space-x-2"> {/* Mobile Actions */}
<Badge variant="outline" className={statusColor}> <div className="flex lg:hidden items-center gap-2">
<Badge variant="outline" className={`${statusColor} text-xs px-2`}>
{statusIcon} {statusIcon}
<span className="ml-1 capitalize hidden sm:inline">{systemStatus.status}</span>
</Badge> </Badge>
<Button <Button
@@ -354,11 +343,10 @@ export function ProxmoxDashboard() {
refreshData() refreshData()
}} }}
disabled={isRefreshing} disabled={isRefreshing}
className="h-9 w-9 p-0" className="h-8 w-8 p-0"
> >
<RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} /> <RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
</Button> </Button>
</div>
<div onClick={(e) => e.stopPropagation()}> <div onClick={(e) => e.stopPropagation()}>
<ThemeToggle /> <ThemeToggle />
@@ -366,7 +354,10 @@ export function ProxmoxDashboard() {
</div> </div>
</div> </div>
<div className="mt-2 text-right text-sm text-muted-foreground">Uptime: {systemStatus.uptime}</div> {/* Mobile Server Info */}
<div className="lg:hidden mt-2 flex items-center justify-end text-xs text-muted-foreground">
<span className="whitespace-nowrap">Uptime: {systemStatus.uptime || "N/A"}</span>
</div>
</div> </div>
</header> </header>

View File

@@ -5,7 +5,7 @@ import { Button } from "./ui/button"
import { Input } from "./ui/input" import { Input } from "./ui/input"
import { Label } from "./ui/label" import { Label } from "./ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card"
import { Shield, Lock, User, AlertCircle, CheckCircle, Info } from "lucide-react" import { Shield, Lock, User, AlertCircle, CheckCircle, Info, LogOut } from "lucide-react"
import { getApiUrl } from "../lib/api-config" import { getApiUrl } from "../lib/api-config"
export function Settings() { export function Settings() {
@@ -98,7 +98,7 @@ export function Settings() {
const handleDisableAuth = async () => { const handleDisableAuth = async () => {
if ( if (
!confirm( !confirm(
"¿Estás seguro de que quieres deshabilitar la autenticación? Esto eliminará la protección por contraseña de tu dashboard y tendrás que configurarla de nuevo si quieres reactivarla.", "Are you sure you want to disable authentication? This will remove password protection from your dashboard.",
) )
) { ) {
return return
@@ -109,35 +109,31 @@ export function Settings() {
setSuccess("") setSuccess("")
try { try {
const token = localStorage.getItem("proxmenux-auth-token")
const response = await fetch(getApiUrl("/api/auth/disable"), { const response = await fetch(getApiUrl("/api/auth/disable"), {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("proxmenux-auth-token")}`, Authorization: `Bearer ${token}`,
}, },
}) })
const data = await response.json() const data = await response.json()
if (!response.ok) { if (!response.ok) {
throw new Error(data.error || "Failed to disable authentication") throw new Error(data.message || "Failed to disable authentication")
} }
localStorage.removeItem("proxmenux-auth-token") localStorage.removeItem("proxmenux-auth-token")
localStorage.removeItem("proxmenux-saved-username")
localStorage.removeItem("proxmenux-saved-password")
localStorage.removeItem("proxmenux-auth-setup-complete") localStorage.removeItem("proxmenux-auth-setup-complete")
setSuccess("¡Autenticación deshabilitada correctamente! La página se recargará...") setSuccess("Authentication disabled successfully! Reloading...")
// Recargar la página después de 1.5 segundos
setTimeout(() => { setTimeout(() => {
window.location.reload() window.location.reload()
}, 1500) }, 1000)
} catch (err) { } catch (err) {
setError( setError(err instanceof Error ? err.message : "Failed to disable authentication. Please try again.")
err instanceof Error ? err.message : "No se pudo deshabilitar la autenticación. Por favor, inténtalo de nuevo.",
)
} finally { } finally {
setLoading(false) setLoading(false)
} }
@@ -202,6 +198,7 @@ export function Settings() {
const handleLogout = () => { const handleLogout = () => {
localStorage.removeItem("proxmenux-auth-token") localStorage.removeItem("proxmenux-auth-token")
localStorage.removeItem("proxmenux-auth-setup-complete")
window.location.reload() window.location.reload()
} }
@@ -338,6 +335,7 @@ export function Settings() {
{authEnabled && ( {authEnabled && (
<div className="space-y-3"> <div className="space-y-3">
<Button onClick={handleLogout} variant="outline" className="w-full bg-transparent"> <Button onClick={handleLogout} variant="outline" className="w-full bg-transparent">
<LogOut className="h-4 w-4 mr-2" />
Logout Logout
</Button> </Button>

View File

@@ -26,7 +26,6 @@ AUTH_CONFIG_FILE = CONFIG_DIR / "auth.json"
JWT_SECRET = "proxmenux-monitor-secret-key-change-in-production" JWT_SECRET = "proxmenux-monitor-secret-key-change-in-production"
JWT_ALGORITHM = "HS256" JWT_ALGORITHM = "HS256"
TOKEN_EXPIRATION_HOURS = 24 TOKEN_EXPIRATION_HOURS = 24
TOKEN_EXPIRATION_DAYS_REMEMBER = 30 # Token más largo para "recordar contraseña"
def ensure_config_dir(): def ensure_config_dir():
@@ -95,18 +94,15 @@ def verify_password(password, password_hash):
return hash_password(password) == password_hash return hash_password(password) == password_hash
def generate_token(username, remember_me=False): # Añadido parámetro remember_me def generate_token(username):
"""Generate a JWT token for the given username""" """Generate a JWT token for the given username"""
if not JWT_AVAILABLE: if not JWT_AVAILABLE:
return None return None
expiration_delta = timedelta(days=TOKEN_EXPIRATION_DAYS_REMEMBER) if remember_me else timedelta(hours=TOKEN_EXPIRATION_HOURS)
payload = { payload = {
'username': username, 'username': username,
'exp': datetime.utcnow() + expiration_delta, 'exp': datetime.utcnow() + timedelta(hours=TOKEN_EXPIRATION_HOURS),
'iat': datetime.utcnow(), 'iat': datetime.utcnow()
'remember_me': remember_me # Guardar preferencia en el token
} }
try: try:
@@ -151,7 +147,7 @@ def get_auth_status():
config = load_auth_config() config = load_auth_config()
return { return {
"auth_enabled": config.get("enabled", False), "auth_enabled": config.get("enabled", False),
"auth_configured": config.get("configured", False), "auth_configured": config.get("configured", False), # Frontend expects this field name
"declined": config.get("declined", False), "declined": config.get("declined", False),
"username": config.get("username") if config.get("enabled") else None, "username": config.get("username") if config.get("enabled") else None,
"authenticated": False # Will be set to True by the route handler if token is valid "authenticated": False # Will be set to True by the route handler if token is valid
@@ -206,16 +202,15 @@ def disable_auth():
Disable authentication (different from decline - can be re-enabled) Disable authentication (different from decline - can be re-enabled)
Returns (success: bool, message: str) Returns (success: bool, message: str)
""" """
config = { config = load_auth_config()
"enabled": False, config["enabled"] = False
"username": None, config["username"] = None
"password_hash": None, config["password_hash"] = None
"declined": False, config["declined"] = False
"configured": False config["configured"] = False
}
if save_auth_config(config): if save_auth_config(config):
return True, "Authentication disabled successfully" return True, "Authentication disabled"
else: else:
return False, "Failed to save configuration" return False, "Failed to save configuration"
@@ -239,7 +234,7 @@ def enable_auth():
return False, "Failed to save configuration" return False, "Failed to save configuration"
def change_password(current_password, new_password): # Corregido nombre del parámetro def change_password(old_password, new_password):
""" """
Change the authentication password Change the authentication password
Returns (success: bool, message: str) Returns (success: bool, message: str)
@@ -249,7 +244,7 @@ def change_password(current_password, new_password): # Corregido nombre del par
if not config.get("enabled"): if not config.get("enabled"):
return False, "Authentication is not enabled" return False, "Authentication is not enabled"
if not verify_password(current_password, config.get("password_hash", "")): if not verify_password(old_password, config.get("password_hash", "")):
return False, "Current password is incorrect" return False, "Current password is incorrect"
if len(new_password) < 6: if len(new_password) < 6:
@@ -263,7 +258,7 @@ def change_password(current_password, new_password): # Corregido nombre del par
return False, "Failed to save new password" return False, "Failed to save new password"
def authenticate(username, password, remember_me=False): # Añadido parámetro remember_me def authenticate(username, password):
""" """
Authenticate a user with username and password Authenticate a user with username and password
Returns (success: bool, token: str or None, message: str) Returns (success: bool, token: str or None, message: str)
@@ -279,7 +274,7 @@ def authenticate(username, password, remember_me=False): # Añadido parámetro
if not verify_password(password, config.get("password_hash", "")): if not verify_password(password, config.get("password_hash", "")):
return False, None, "Invalid username or password" return False, None, "Invalid username or password"
token = generate_token(username, remember_me) token = generate_token(username)
if token: if token:
return True, token, "Authentication successful" return True, token, "Authentication successful"
else: else:

View File

@@ -33,47 +33,28 @@ def auth_setup():
username = data.get('username') username = data.get('username')
password = data.get('password') password = data.get('password')
if not username or not password:
return jsonify({"success": False, "error": "Username and password are required"}), 400
success, message = auth_manager.setup_auth(username, password) success, message = auth_manager.setup_auth(username, password)
if success:
# Generate token for immediate login
token = auth_manager.generate_token(username)
return jsonify({"success": True, "message": message, "token": token})
else:
return jsonify({"success": False, "error": message}), 400
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@auth_bp.route('/api/auth/skip', methods=['POST'])
def auth_skip():
"""Skip authentication setup (user declined)"""
try:
success, message = auth_manager.decline_auth()
if success: if success:
return jsonify({"success": True, "message": message}) return jsonify({"success": True, "message": message})
else: else:
return jsonify({"success": False, "error": message}), 400 return jsonify({"success": False, "message": message}), 400
except Exception as e: except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500 return jsonify({"success": False, "message": str(e)}), 500
@auth_bp.route('/api/auth/decline', methods=['POST']) @auth_bp.route('/api/auth/decline', methods=['POST'])
def auth_decline(): def auth_decline():
"""Decline authentication setup (deprecated, use /api/auth/skip)""" """Decline authentication setup"""
try: try:
success, message = auth_manager.decline_auth() success, message = auth_manager.decline_auth()
if success: if success:
return jsonify({"success": True, "message": message}) return jsonify({"success": True, "message": message})
else: else:
return jsonify({"success": False, "error": message}), 400 return jsonify({"success": False, "message": message}), 400
except Exception as e: except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500 return jsonify({"success": False, "message": str(e)}), 500
@auth_bp.route('/api/auth/login', methods=['POST']) @auth_bp.route('/api/auth/login', methods=['POST'])
@@ -83,19 +64,15 @@ def auth_login():
data = request.json data = request.json
username = data.get('username') username = data.get('username')
password = data.get('password') password = data.get('password')
remember_me = data.get('remember_me', False) # Soporte para "recordar contraseña"
success, token, message = auth_manager.authenticate(username, password, remember_me) success, token, message = auth_manager.authenticate(username, password)
if success: if success:
response_data = {"success": True, "token": token, "message": message} return jsonify({"success": True, "token": token, "message": message})
if remember_me:
response_data["remember_me"] = True # Indicar al frontend que guarde las credenciales
return jsonify(response_data)
else: else:
return jsonify({"success": False, "error": message}), 401 return jsonify({"success": False, "message": message}), 401
except Exception as e: except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500 return jsonify({"success": False, "message": str(e)}), 500
@auth_bp.route('/api/auth/enable', methods=['POST']) @auth_bp.route('/api/auth/enable', methods=['POST'])
@@ -107,9 +84,9 @@ def auth_enable():
if success: if success:
return jsonify({"success": True, "message": message}) return jsonify({"success": True, "message": message})
else: else:
return jsonify({"success": False, "error": message}), 400 return jsonify({"success": False, "message": message}), 400
except Exception as e: except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500 return jsonify({"success": False, "message": str(e)}), 500
@auth_bp.route('/api/auth/disable', methods=['POST']) @auth_bp.route('/api/auth/disable', methods=['POST'])
@@ -117,21 +94,17 @@ def auth_disable():
"""Disable authentication""" """Disable authentication"""
try: try:
token = request.headers.get('Authorization', '').replace('Bearer ', '') token = request.headers.get('Authorization', '').replace('Bearer ', '')
if not token: if not token or not auth_manager.verify_token(token):
return jsonify({"success": False, "error": "Authentication required"}), 401 return jsonify({"success": False, "message": "Unauthorized"}), 401
username = auth_manager.verify_token(token)
if not username:
return jsonify({"success": False, "error": "Invalid or expired token"}), 401
success, message = auth_manager.disable_auth() success, message = auth_manager.disable_auth()
if success: if success:
return jsonify({"success": True, "message": message}) return jsonify({"success": True, "message": message})
else: else:
return jsonify({"success": False, "error": message}), 400 return jsonify({"success": False, "message": message}), 400
except Exception as e: except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500 return jsonify({"success": False, "message": str(e)}), 500
@auth_bp.route('/api/auth/change-password', methods=['POST']) @auth_bp.route('/api/auth/change-password', methods=['POST'])
@@ -139,25 +112,28 @@ def auth_change_password():
"""Change authentication password""" """Change authentication password"""
try: try:
data = request.json data = request.json
current_password = data.get('current_password') # Corregido el nombre del campo old_password = data.get('old_password')
new_password = data.get('new_password') new_password = data.get('new_password')
# Verify current authentication success, message = auth_manager.change_password(old_password, new_password)
token = request.headers.get('Authorization', '').replace('Bearer ', '')
if not token:
return jsonify({"success": False, "error": "Authentication required"}), 401
username = auth_manager.verify_token(token)
if not username:
return jsonify({"success": False, "error": "Invalid or expired token"}), 401
success, message = auth_manager.change_password(current_password, new_password)
if success: if success:
# Generate new token return jsonify({"success": True, "message": message})
new_token = auth_manager.generate_token(username)
return jsonify({"success": True, "message": message, "token": new_token})
else: else:
return jsonify({"success": False, "error": message}), 400 return jsonify({"success": False, "message": message}), 400
except Exception as e: except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500 return jsonify({"success": False, "message": str(e)}), 500
@auth_bp.route('/api/auth/skip', methods=['POST'])
def auth_skip():
"""Skip authentication setup (same as decline)"""
try:
success, message = auth_manager.decline_auth()
if success:
return jsonify({"success": True, "message": message})
else:
return jsonify({"success": False, "message": message}), 400
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500