def serverControl(): req = request.json # Response block resBlock = {"msg": None, "is_running": None, "status": False} try: if isRequiredDataAvailable(req, ["address", "action"]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) try: res = requests.post(f'http://{req.get("address")}/alive/', json={"action": req.get("action")}) if not res.ok: raise Exception except Exception as e: resBlock['msg'] = "No response from the server" resBlock['is_running'] = False raise end(Exception) resJson = res.json() resBlock['msg'] = "Operation successful" resBlock['is_running'] = resJson.get('status') resBlock['status'] = True raise final(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def getServerInfo(address): addr: str = str(address) # Response block resBlock = {"msg": None, "is_running": None, "status": False} try: if addr == None or addr.strip() == '': resBlock['msg'] = "No JSON data found" raise end(Exception) try: res = requests.get(f'http://{addr}/alive/') if not res.ok: raise Exception except Exception as e: resBlock['msg'] = "No response from the server" resBlock['is_running'] = False raise end(Exception) resJson = res.json() resBlock['msg'] = "Operation successful" resBlock['is_running'] = resJson.get('status') resBlock['status'] = True raise final(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def removeUserAdmin(): req = request.json # Response Block resBlock = { "msg": None, "is_server_exists": False, "is_host_exists": False, "status": False } try: if isRequiredDataAvailable( req, ["host_name", "server_name", "server_address", "username" ]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('server_name') and server.get( 'address') == req.get('server_address'): resBlock['is_server_exists'] = True hosts = server.get('hosts') for host in hosts: if host.get('name') == req.get('host_name'): resBlock['is_host_exists'] = True admin = host['admin'] admin['name'] = '' ret, msg = app.DB.update_doc( {"address": server.get('address')}, {"hosts": hosts}, getenv('SERVER_COLLECTION')) if ret: resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) else: resBlock[ 'msg'] = "Failed to remove admin while saving into the database" raise end(Exception) raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def nCloudConfig(): data: dict = getNcloudConfig(app.DB) # Response block resBlock = {"msg": None, "data": None, "status": False} try: if data == None: resBlock['msg'] = "Config not found" raise end(Exception) if request.method == 'GET': resBlock['data'] = data resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) else: req = request.json if req == None: resBlock['msg'] = "No JSON data found" raise end(Exception) block: dict = {} for item in data: # Pattern - "autoStartSrvr": data.get('autoStartSrvr') if req.get('autoStartSrvr') == None else req.get('autoStartSrvr'), block.setdefault( item.__str__(), data.get(item.__str__()) if req.get(item.__str__()) == None else req.get(item.__str__())) ret, msg = app.DB.update_doc({"name": "admin"}, block, getenv('ADMIN_COLLECTION')) if ret == False: resBlock[ 'msg'] = "Failed while saving nCloud configs into database" raise end(Exception) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def getDIR(): req = request.args # Response Block resBlock = { "msg" : None, "is_server_exists" : False, "is_host_exists" : False, "data": [], "status" : False } try: if isRequiredDataAvailable(req, ["host_name", "server_name", "server_address", "username", "path"]) == False: resBlock['msg'] = "No Query data found" raise end(Exception) servers = getServers(app.DB) block:dict = get_default_path(req, servers) path:str = block.get('path') if block.get('is_exists') == False: resBlock['msg'] = "User doesn't exists into the host" raise end(Exception) if req.get('path').find(path) == 0: resBlock['msg'] = "Valid Path" resBlock['status'] = True #<Pending> #</Pending> raise final(Exception) else: resBlock['msg'] = "Invalid Path" raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def get_access_for_permission(): req = request.args # Response Block resBlock = { "msg" : None, "token" : None, "status" : False } tokenBLK = { "writable": False, "host_name": "", "server_address": "" } try: if isRequiredDataAvailable(req, ["server_name", "address", "host_name", "path"]) == False: resBlock['msg'] = "Missing data" raise end(Exception) servers = getServers(app.DB) targetHost = None for server in servers: if req.get("address") == server.get("address") and req.get("server_name") == server.get("name"): hosts = server.get('hosts') tokenBLK["server_address"] = server.get("address") for host in hosts: if req.get("host_name") == host.get("name") and req.get("path") == host.get("path"): targetHost = host tokenBLK["host_name"] = host.get("name") break break if targetHost == None: resBlock["msg"] = "Host not found" raise end(Exception) is_valid_user = True if get_jwt_identity() in targetHost.get("validUsers") else False is_shared_user = False if is_valid_user: tokenBLK["writable"] = targetHost.get("writable") if is_valid_user == False and targetHost.get("admin") != None: adminObj = targetHost.get("admin") tokenBLK["writable"] = adminObj.get("writable") is_shared_user = True if get_jwt_identity() in adminObj.get("sharedUsers") else False if is_valid_user or is_shared_user: resBlock["token"] = create_access_token(identity=get_jwt_claims(), user_claims=tokenBLK, expires_delta = timedelta(days = 300)) resBlock["msg"] = "Access granted" resBlock["status"] = True raise final(Exception) else: resBlock["msg"] = "User not found" raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def addUserAdmin(): req = request.json # Response Block resBlock = { "msg": None, "is_server_exists": False, "is_host_exists": False, "is_usename_exists_in_valid_user": False, "status": False } try: if isRequiredDataAvailable( req, ["host_name", "server_name", "server_address", "username" ]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) # Some other checks regarding username and KEY isExists, pending, isManager = dbOperation.userExists( req.get('username').strip().lower(), app.DB) if not (isExists and not isManager): resBlock['msg'] = "Username doesn't exists" raise end(Exception) servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('server_name') and server.get( 'address') == req.get('server_address'): resBlock['is_server_exists'] = True hosts = server.get('hosts') for host in hosts: if host.get('name') == req.get('host_name'): resBlock['is_host_exists'] = True if req.get('username') in host.get('validUsers'): resBlock['is_usename_exists_in_valid_user'] = True else: resBlock[ 'msg'] = "Username is not exists in host's valid users." raise end(Exception) admin = host['admin'] admin['name'] = req.get('username') ret, msg = app.DB.update_doc( {"address": server.get('address')}, {"hosts": hosts}, getenv('SERVER_COLLECTION')) if ret: resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) else: resBlock[ 'msg'] = "Failed to add admin while saving into the database" raise end(Exception) raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def changePermission(): req = request.json # Response Block resBlock = { "msg": None, "is_server_exists": False, "is_host_exists": False, "status": False } try: if isRequiredDataAvailable( req, ["host_name", "server_name", "server_address", "writable" ]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) # Some other checks regarding username and KEY isExists, pending, isManager = dbOperation.userExists( get_jwt_identity().strip().lower(), app.DB) manager = isManager if not (isExists or isManager): resBlock['msg'] = "Request is sent from unauthorized user" raise end(Exception) servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('server_name') and server.get( 'address') == req.get('server_address'): resBlock['is_server_exists'] = True hosts = server.get('hosts') for host in hosts: if host.get('name') == req.get('host_name'): resBlock['is_host_exists'] = True admin = host['admin'] if admin['name'] != get_jwt_identity( ) and manager != True: resBlock[ 'msg'] = "Request is sent from unauthorized user" raise end(Exception) admin['writable'] = True if req.get( 'writable') == True else False ret, msg = app.DB.update_doc( {"address": server.get('address')}, {"hosts": hosts}, getenv('SERVER_COLLECTION')) if ret: resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) else: resBlock[ 'msg'] = "Failed to update config while saving into the database" raise end(Exception) raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def changeConfigHost(): req = request.json # Response Block resBlock = { "msg" : None, "is_server_exists" : False, "is_host_exists" : False, "status" : False } try: if isRequiredDataAvailable(req, ["current_host_name", "server_name"]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) if req.get('validUsers') != None: req['validUsers'] = None servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('server_name'): resBlock['is_server_exists'] = True hosts = server.get('hosts') for host in hosts: if host.get('name') == req.get('current_host_name'): resBlock['is_host_exists'] = True try: res = requests.post(f'http://{server.get("address")}/host/config/', json = { "name" : req.get('name'), "path" : req.get('path'), "writable" : req.get('writable'), "public" : req.get('public'), "currentHostName" : req.get('current_host_name') }) if not res.ok: raise Exception except Exception as e: resBlock['msg'] = "Failed while changing config in host" raise end(Exception) for item in host: # Pattern - "autoStartSrvr": data.get('autoStartSrvr') if req.get('autoStartSrvr') == None else req.get('autoStartSrvr'), host.__setitem__(item.__str__(), host.get(item.__str__()) if req.get(item.__str__()) == None else req.get(item.__str__())) ret, msg = app.DB.update_doc({"address" : server.get('address')}, {"hosts" : hosts}, getenv('SERVER_COLLECTION')) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) resBlock['msg'] = "Host not found" raise end(Exception) resBlock['msg'] = "Server not found" raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def removeHost(): req = request.json # Response block resBlock = { "msg" : None, "is_server_exists" : None, "is_host_exists" : None, "status" : False } try: if isRequiredDataAvailable(request.json, ["name", "path", "server_name"]) == False: resBlock['msg'] = "Bad request" raise end(Exception) # Fetching all Pi Server_data from the database servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('server_name'): resBlock['is_server_exists'] = True if isServerAlive(server) == False: resBlock['msg'] = "Server needs to be online while creating host" raise end(Exception) # Checking if any host with same name or same path exists hosts = server.get('hosts') for host in hosts: if host.get('name') == req.get('name') and host.get('path') == req.get('path'): resBlock['is_host_exists'] = True try: res = requests.delete(f'http://{server.get("address")}/host/', json = { "name": req.get('name'), "path": req.get('path') }) if not res.ok: raise Exception except Exception as e: resBlock['msg'] = "Failed while removing host" raise end(Exception) hosts.remove(host) ret, msg = app.DB.update_doc({"address" : server.get('address')}, {"hosts" : hosts}, getenv('SERVER_COLLECTION')) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) resBlock['msg'] = "Host not found" resBlock['is_host_exists'] = False raise end(Exception) resBlock['msg'] = "Server not found" resBlock['is_server_exists'] = False raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def addUsersIntoHost(): # Assigning only json data req:dict = request.json # Response block resBlock = { "msg" : None, "error": [], "status": False } try: # Checking if the client sent json data with the request. if req == None or req.get('address') == None or req.get('address') == None or req.get('users') == None: resBlock['msg'] = "No JSON data found" raise end(Exception) # Fetching all Pi Server_data from the database servers = getServers(app.DB) # Decision variable to ensure that all the operations are executing successfully # 0 = No Error | 0 < = Error operationStatus = 0 operationLimit = 0 host_found = False server_found = False reqServer = None reqHost = None # Looping through the server data to add the username into each server's host for server in servers: if server.get('address') == req.get('address'): reqServer = server break # Checking if the server is exists or not if reqServer == None: resBlock['msg'] = "Server not found" raise end(Exception) # Checking if the server is alive or not if isServerAlive(server) == False: resBlock['msg'] = "Server is currently down" raise end(Exception) # Getting hosts hosts = reqServer.get('hosts') for host in hosts: if host.get('name') == req.get('hostname'): reqHost = host break # Checking if the server is exists or not if reqHost == None: resBlock['msg'] = "Host not found" raise final(Exception) validUsers = reqHost.get('validUsers') for user in req.get('users'): try: operationLimit += 1 # Sending request to the Pi Server to add or remove the username to all of it's hosts if request.method == 'POST': if user.lower() in validUsers: resBlock['error'].append({ "username" : user.lower(), "exists" : True }) continue userData:dict = app.DB.get_doc({"username": user.lower()}, getenv('USER_COLLECTION')) if userData == None: resBlock['error'].append({ "username" : user.lower(), "exists" : False, "inDB" : False }) continue res = requests.post(f'http://{server.get("address")}/user/', json = { "username" : user, "password" : userData.get("password"), "hostname" : req.get('hostname') }) if res.ok: validUsers.append(user.lower()) operationStatus += 1 else: raise Exception else: if user.lower() not in validUsers: resBlock['error'].append({ "username" : user.lower(), "exists" : False }) continue res = requests.delete(f'http://{server.get("address")}/user/', json = { "username" : user, "hostname" : req.get('hostname') }) if res.ok: validUsers.remove(user.lower()) operationStatus += 1 else: raise Exception except Exception as e: print(f'Exception :: {e}') resBlock['error'].append({ "username" : user.lower(), "exists" : True, "op_status" : False }) reqHost.setdefault('validUsers', validUsers) ret, msg = app.DB.update_doc({"address" : reqServer.get('address')}, {"hosts" : hosts}, getenv('SERVER_COLLECTION')) print(f'Operation state - {operationStatus}, \t Limit - {operationLimit}') if operationStatus == operationLimit: pass elif operationStatus > 0 and operationStatus < operationLimit: resBlock['msg'] = "Some targets are not completed" resBlock['status'] = True raise final(Exception) else: resBlock['msg'] = "Failed while adding users to the server" if request.method == 'POST' else "Failed while removing users from the server" raise end(Exception) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def getServerDataForUser(): req = request.args # Response block resBlock = {"msg": None, "data": [], "shared": [], "status": False} try: if req == None or req.get('username') == None: resBlock['msg'] = "No JSON data found" raise end(Exception) resServer = [] resShared = [] servers = getServers(app.DB) for server in servers: hosts = server.get('hosts') for host in hosts: admin = host.get('admin') is_you_user_admin = True if admin.get('name') == req.get( 'username') else False hdd = {"used": 0, "total": 0} alive = isServerAlive(server) if alive: try: res = requests.get( f'http://{server.get("address")}/host/info/', json={"path": host.get('path')}) if res.ok: hdd = res.json() else: raise Exception except Exception: print("Error Occurred :: While getting disk usage") if req.get('username') in host.get('validUsers') or host.get( 'public') == True: resServer.append({ "server_name": server.get('name'), "total": hdd.get("total"), "used": hdd.get("used"), "is_running": alive, "address": server.get('address'), "host_name": host.get('name'), "path": host.get('path'), "writable": host.get('writable'), "is_you_user_admin": is_you_user_admin, "admin": admin if is_you_user_admin == True else False, "validUsers": host.get("validUsers") if is_you_user_admin == True else [], "shared": { "writable": admin.get("writable"), "shared": admin.get("sharedUsers") } if is_you_user_admin else {} }) if req.get('username') in admin.get('sharedUsers'): resShared.append({ "server_name": server.get('name'), "total": hdd.get("total"), "used": hdd.get("used"), "is_running": alive, "address": server.get('address'), "host_name": host.get('name'), "path": host.get('path'), "admin_name": admin.get('name'), "writable": admin.get('writable') }) resBlock['data'] = resServer resBlock['shared'] = resShared resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def removeServer(): req = request.json # Response Block resBlock = { "msg": None, "is_server_exists": True, "is_server_running": False, "status": False } try: if isRequiredDataAvailable(req, ["name", "address"]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('name') and server.get( 'address') == req.get('address'): try: res = requests.get(f'http://{req.get("address")}/init/') if not res.ok: raise Exception resBlock['is_server_running'] = True res = requests.get(f'http://{req.get("address")}/reset/') if not res.ok: raise Exception except Exception as e: resBlock['msg'] = "Server is not running or not exists" resBlock['is_server_running'] = False raise end(Exception) # Removing server data from database ret, dummy = app.DB.remove( { "name": req.get('name'), "address": req.get('address'), }, getenv('SERVER_COLLECTION')) if ret == False: resBlock[ 'msg'] = "Error ocurred while removing from database" raise end(Exception) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) resBlock['msg'] = "Server not exists" resBlock['is_server_exists'] = False raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def changeServerConfig(): req = request.json # Response Block resBlock = { "msg": None, "is_server_name_exists": False, "is_server_address_exists": False, "is_server_running": False, "status": False } try: if isRequiredDataAvailable( req, ["current_name", "current_address"]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) if req.get('hosts') != None: req['hosts'] = None servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('current_name') and server.get( 'address') == req.get('current_address'): resBlock['msg'] = "Server already exists with this name" resBlock['is_server_name_exists'] = True resBlock['is_server_address_exists'] = True if req.get('address') != None: try: res = requests.get( f'http://{req.get("address")}/init/') if not res.ok: raise Exception resBlock['is_server_running'] = True except Exception as e: resBlock['msg'] = "Server is not running or not exists" resBlock['is_server_running'] = False raise end(Exception) updateBLK = { "name": server.get('name') if req.get('name') == None else req.get('name'), "address": server.get('address') if req.get('address') == None else req.get('address'), "address": server.get('address') if req.get('address') == None else req.get('address'), "autoStart": server.get('autoStart') if req.get('auto_start') == None else req.get('auto_start') } ret, msg = app.DB.update_doc({"name": req.get('current_name')}, updateBLK, getenv('SERVER_COLLECTION')) if ret == False: resBlock[ 'msg'] = "Failed while saving server configs into database" raise end(Exception) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) resBlock['msg'] = "Server not found" raise end(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))
def createServer(): req = request.json # Response Block resBlock = { "msg": None, "is_server_name_exists": False, "is_server_address_exists": False, "is_server_running": False, "status": False } try: if isRequiredDataAvailable(req, ["name", "address", "auto_start"]) == False: resBlock['msg'] = "No JSON data found" raise end(Exception) servers = getServers(app.DB) for server in servers: if server.get('name') == req.get('name'): resBlock['msg'] = "Server already exists with this name" resBlock['is_server_name_exists'] = True raise end(Exception) if server.get('address') == req.get('address'): resBlock['msg'] = "Server already exists with this path" resBlock['is_server_address_exists'] = True raise end(Exception) try: res = requests.get(f'http://{req.get("address")}/init/') if not res.ok: raise Exception except Exception as e: resBlock['msg'] = "Server is not running or not exists" resBlock['is_server_running'] = False raise end(Exception) # Saving server data into database ret, val = app.DB.insert([{ "name": req.get('name'), "address": req.get('address'), "autoStart": req.get('auto_start'), "hosts": [] }], getenv('SERVER_COLLECTION')) if ret == False: resBlock['msg'] = "Error ocurred while saving into database" raise end(Exception) resBlock['msg'] = "Operation successful" resBlock['status'] = True raise final(Exception) except end: return allowCors(jsonify(resBlock), 400) except final: return allowCors(jsonify(resBlock))