11import os
2+ import time
23import datetime
3- from flask import render_template , request , flash , blueprints , redirect , url_for
4+ import subprocess
5+ from flask import render_template , request , flash , blueprints , redirect , url_for , Response , session
46
57from src .config import app , db
68from src .models import UserCardSettings , UserDashboardSettings , UserProfile , GeneralSettings , PageToggleSettings
@@ -112,3 +114,54 @@ def settings():
112114 return render_template ("error/403.html" )
113115
114116 return render_template ("settings/settings.html" , settings = settings )
117+
118+ def check_sudo_password (sudo_password ):
119+ """
120+ Verify the given sudo password by executing a harmless sudo command.
121+ If the password is correct, it returns True. Otherwise, returns False.
122+
123+ :param sudo_password: The user's sudo password to validate.
124+ :return: True if the password is correct, otherwise False.
125+ """
126+ try :
127+ # Test if the sudo password is valid by running a safe sudo command
128+ result = subprocess .run (
129+ ['sudo' , '-S' , 'true' ],
130+ input = f'{ sudo_password } \n ' ,
131+ text = True ,
132+ stdout = subprocess .PIPE ,
133+ stderr = subprocess .PIPE
134+ )
135+ return result .returncode == 0
136+
137+ except Exception as e :
138+ # Log any exception that occurs while validating the sudo password
139+ return False , str (e )
140+
141+ @app .route ('/control' , methods = ['GET' , 'POST' ])
142+ def control ():
143+ if request .method == 'POST' :
144+ action = request .form .get ('action' )
145+ sudo_password = request .form .get ('sudo_password' , '' )
146+
147+ if action == 'shutdown' :
148+ command = ['sudo' , '-S' , 'shutdown' , '-h' , 'now' ]
149+ success_message = "Server is shutting down..."
150+ error_message = "Failed to shutdown: {}"
151+ elif action == 'reboot' :
152+ command = ['sudo' , '-S' , 'reboot' ]
153+ success_message = "Server is rebooting..."
154+ error_message = "Failed to reboot: {}"
155+ else :
156+ flash ("Invalid action!" , 'danger' )
157+ return redirect (url_for ('control' ))
158+
159+ try :
160+ # Execute the command with the sudo password
161+ result = subprocess .run (command , input = sudo_password .encode (), check = True , capture_output = True , text = True )
162+ flash (success_message , 'info' )
163+ except subprocess .CalledProcessError as e :
164+ flash (error_message .format (e ), 'danger' )
165+
166+ # Render the control form on GET request
167+ return render_template ("settings/control.html" )
0 commit comments