@ -3,7 +3,7 @@ from functools import wraps
from flask import Blueprint , flash , redirect , render_template , request , session , url_for
from app . db import get_db
from app . auth . utils import create_device_directories , slugify_device_name
from app . auth . utils import create_device_directories , remove_device_directories , slugify_device_name
bp = Blueprint ( " main " , __name__ )
@ -133,3 +133,67 @@ def add_device():
flash ( " Device added successfully. " , " success " )
return redirect ( url_for ( " main.dashboard " ) )
@bp . route ( " /devices/delete/<int:device_id> " , methods = [ " POST " ] )
@portal_session_required
def delete_device ( device_id : int ) :
db = get_db ( )
with db . cursor ( ) as cur :
cur . execute (
"""
SELECT id , device_name , device_type , relative_path
FROM devices
WHERE id = % s AND tenant_id = % s
""" ,
( device_id , session [ " otb_tenant_id " ] ) ,
)
device = cur . fetchone ( )
if not device :
flash ( " Device not found. " , " warning " )
return redirect ( url_for ( " main.dashboard " ) )
cur . execute (
"""
SELECT COUNT ( * ) AS file_count
FROM files
WHERE tenant_id = % s AND device_id = % s AND is_deleted = 0
""" ,
( session [ " otb_tenant_id " ] , device_id ) ,
)
file_count = cur . fetchone ( ) [ " file_count " ]
if file_count and int ( file_count ) > 0 :
flash ( " This device cannot be removed because files are still linked to it. " , " warning " )
return redirect ( url_for ( " main.dashboard " ) )
cur . execute (
"""
DELETE FROM devices
WHERE id = % s AND tenant_id = % s
""" ,
( device_id , session [ " otb_tenant_id " ] ) ,
)
cur . execute (
"""
INSERT INTO audit_logs (
tenant_id , user_id , actor_type , event_type , ip_address , user_agent , event_detail
) VALUES ( % s , % s , ' user ' , ' device_deleted ' , % s , % s , % s )
""" ,
(
session [ " otb_tenant_id " ] ,
session [ " otb_user_id " ] ,
request . headers . get ( " X-Forwarded-For " , request . remote_addr ) ,
request . headers . get ( " User-Agent " , " " ) ,
f " Deleted device ' { device [ ' device_name ' ] } ' ( { device [ ' device_type ' ] } ) at { device [ ' relative_path ' ] } " ,
) ,
)
db . commit ( )
remove_device_directories ( session [ " otb_tenant_slug " ] , device [ " relative_path " ] )
flash ( " Device removed successfully. " , " success " )
return redirect ( url_for ( " main.dashboard " ) )