Exemplo n.º 1
0
def getFolder():
    req = request.args

    token = req.get("token")
    tokenData = decode_token(token)

    tokenIdentity = tokenData.get("identity")

    if tokenIdentity.get("username") != get_jwt_identity():
        return allowCors(jsonify({"msg": "Corrupted user"}), 400)

    path = req.get('path')

    if path:
        path = path.strip()

    if path == None or path == '':
        return allowCors(jsonify({"path": None, "data": []}))

    if not Path(path).exists():
        return allowCors(jsonify({"path": None, "data": []}))

    data = Directories.getDirData(req.get('path'))

    return allowCors(jsonify(data))
Exemplo n.º 2
0
def uploadFile():
    files = request.files
    req = request.args

    token = req.get("token")
    tokenData = decode_token(token)

    tokenIdentity = tokenData.get("identity")
    payload = tokenData.get("user_claims")

    if tokenIdentity.get("username") != get_jwt_identity():
        return allowCors(jsonify({"msg": "Corrupted user"}), 400)

    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    host = app.SambaManager.getHost(payload.get("host_name"))

    if host == None:
        return allowCors(
            jsonify({"msg": "Token Host is not same as requested host."}))

    if host.get("writable") == False:
        return allowCors(jsonify({"msg": "You dont have write permission."}))

    if isValidPath(req, host.get("path")):
        files['file'].save(path.join(req.get('path'), files['file'].filename))
        changeOwner(path.join(req.get('path'), files['file'].filename))
        return allowCors(jsonify({"msg": "Success"}))
    else:
        return allowCors(jsonify({"msg": "Invalid Path"}), 400)
Exemplo n.º 3
0
def heelo():
    req = request.args

    mainToken = decode_token(req.get("m_token"))
    token = req.get("token")

    tokenData = decode_token(token)

    tokenIdentity = tokenData.get("identity")

    if tokenIdentity.get("username") != mainToken.get("identity"):
        return allowCors(jsonify({"msg": "Corrupted user"}), 400)

    payload = tokenData.get("user_claims")

    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    host = app.SambaManager.getHost(payload.get("host_name"))

    if host == None:
        return allowCors(
            jsonify({"msg": "Token Host is not same as requested host."}))

    if isValidPath({"path": safe_join(req.get('path'), req.get('file_name'))},
                   host.get("path"), False):
        return send_from_directory(Path(req.get('path')),
                                   filename=req.get('file_name'),
                                   as_attachment=True)
    else:
        return allowCors(jsonify({"msg": "Invalid Path"}), 400)
Exemplo n.º 4
0
def hostConfigOps():
    if isRequiredDataAvailable(request.json, ["currentHostName"]) == False:
        return allowCors(jsonify({"msg": "bad request"}), 400)

    req = request.json

    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    uPublic = None
    if req.get('public') != None:
        uPublic = "Yes" if req.get('public') == True else "No"

    uWritable = None
    if req.get('writable') != None:
        uWritable = "Yes" if req.get('writable') == True else "No"

    ret = app.SambaManager.updateHost(name=req.get('name'),
                                      path=req.get('path'),
                                      writable=uWritable,
                                      public=uPublic,
                                      hostname=req.get('currentHostName'),
                                      wipeData=req.get('wipeData'))

    if ret == False:
        return allowCors(jsonify({"msg": "Requested Host not found."}), 404)

    app.SambaManager.forceUser(getCurrentUser())

    app.SambaManager.pushIntoConf()

    SMB.reloadSMBD()

    return allowCors(jsonify({"msg": f'Successfully updated the host'}))
Exemplo n.º 5
0
def hostOps():
    if isRequiredDataAvailable(request.json, ["name", "path"]) == False:
        return allowCors(jsonify({"msg": "bad request"}), 400)

    req = request.json

    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    operationCounter = 0

    if request.method == 'POST':
        if isRequiredDataAvailable(
                request.json, ["name", "path", "writable", "public"]) == False:
            return allowCors(jsonify({"msg": "bad request"}), 400)

        if app.SambaManager.createNewHost(
                Host(
                    data={
                        "name":
                        req.get('name'),
                        "path":
                        req.get('path'),
                        "writable": (
                            "Yes" if req.get('writable') == True else "No"),
                        "create mask":
                        '0777',
                        "directory mask":
                        '0777',
                        "public":
                        "Yes" if req.get('public') == True else "No",
                        "valid users": []
                    })) == False:
            operationCounter += 1
    else:
        if app.SambaManager.removeHost(
                req.get('name'),
                True if req.get('removeAll') == True else False) == False:
            operationCounter += 1

    app.SambaManager.forceUser(getCurrentUser())

    app.SambaManager.pushIntoConf()

    SMB.reloadSMBD()

    if operationCounter == 0:
        return allowCors(
            jsonify({
                "msg":
                f'{req.get("name")} is {"added into" if request.method == "POST" else "removed from"} the server'
            }))

    return allowCors(
        jsonify({
            "msg":
            f'{req.get("name")} is failed while {"adding into" if request.method == "POST" else "removing from"} the server'
        }))
Exemplo n.º 6
0
    def decorator(*args, **kwargs):
        data = request.json
        if data == None or data.get('address') == None:
            return allowCors(jsonify({"msg": "bad request"}), 400)
        else:
            address = data.get('address')

        output, err = subprocess.Popen(['hostname', '-i'],
                                       stdout=subprocess.PIPE).communicate()
        ip = output.decode().strip()

        return func(*args, **kwargs) if ip in address else allowCors(
            jsonify({"msg": "bad request"}), 400)
Exemplo n.º 7
0
def getSizeOfHost():
    resBlock = {"total": 0, "used": 0, "status": False}

    req = request.json
    host_path = req.get('path')

    if host_path != None and Path(host_path).exists() and Path(
            host_path).is_dir():
        hdd = psutil.disk_usage(host_path)
        resBlock['total'] = hdd.total
        resBlock['used'] = hdd.used
        resBlock['status'] = True
        return allowCors(jsonify(resBlock))
    else:
        return allowCors(jsonify(resBlock), 400)
Exemplo n.º 8
0
def getFolder():
    req = request.json
    path = req.get('path')

    if path:
        path = path.strip()

    if path == None or path == '':
        return allowCors(jsonify({"path": None, "data": []}))

    if not Path(path).exists():
        return allowCors(jsonify({"path": None, "data": []}))

    data = Directories.getDirData(req.get('path'))

    return allowCors(jsonify(data))
Exemplo n.º 9
0
def userOps():
    data = request.json

    is_required_data_available = isRequiredDataAvailable(
        data, ["username", "password", "hostname"
               ]) if request.method == 'POST' else isRequiredDataAvailable(
                   data, ["username", "hostname"])

    if is_required_data_available == False:
        return allowCors(jsonify({"msg": "bad request"}), 400)

    username = data.get('username')
    password = data.get('password')
    hostname = data.get('hostname')

    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    app.SambaManager.forceUser(getCurrentUser())

    operationCounter = 0

    if request.method == 'POST':
        if app.SambaManager.addValidUser(hostname, username) == False:
            operationCounter += 1
    else:
        if app.SambaManager.removeValidUser(hostname, username) == False:
            operationCounter += 1

    app.SambaManager.pushIntoConf()

    if request.method == 'POST':
        SMB.addUser(username)
        SMB.add_SMBUser(username, password)

    SMB.reloadSMBD()

    if operationCounter == 0:
        return allowCors(
            jsonify(
                {"msg":
                 f'{username} is added into the host \t\t[{hostname}]'}))

    return allowCors(
        jsonify(
            {"msg": f'{username} is failed to while adding into {hostname}'}),
        401)
Exemplo n.º 10
0
def downloadFile(image_name):
    try:
        x = send_from_directory(Path('D:/save/'),
                                filename=image_name,
                                as_attachment=True)
        return x
    except Exception as e:
        print('Exception Ocurred :: ' + e)

    return allowCors(jsonify({"msg": "Success"}))
Exemplo n.º 11
0
def resetServer():
    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    for host in app.SambaManager.Hosts:
        app.SambaManager.removeHost(host.get('name'))

    app.SambaManager.pushIntoConf()

    SMB.restartSMBD()

    return allowCors(jsonify({"msg": "Sucessful"}))
Exemplo n.º 12
0
def alive():
    if request.method == 'GET':
        if isAlive():
            return allowCors(jsonify({"msg": "It is alive.", "status": True}))
        else:
            return allowCors(jsonify({"msg": "It's dead.", "status": False}))
    else:
        data = request.json
        if data.get('action') == True:
            if wake():
                return allowCors(
                    jsonify({
                        "msg": "Server started..",
                        "status": True
                    }))
            else:
                return allowCors(
                    jsonify({
                        "msg": "Failed while starting",
                        "status": False
                    }))
        elif data.get('action') == False:
            if kill():
                return allowCors(
                    jsonify({
                        "msg": "Server stopped",
                        "status": True
                    }))
            else:
                return allowCors(
                    jsonify({
                        "msg": "Error Occured while killing service",
                        "status": False
                    }))
Exemplo n.º 13
0
def removeFile():
    req = request.json

    token = req.get("token")

    tokenData = decode_token(token)

    tokenIdentity = tokenData.get("identity")

    if tokenIdentity.get("username") != get_jwt_identity():
        return allowCors(jsonify({"msg": "Corrupted user"}), 400)

    payload = tokenData.get("user_claims")

    #LOAD ALL CONFIGS from smb.conf
    app.SambaManager.loadConfigs()

    host = app.SambaManager.getHost(payload.get("host_name"))

    if host == None:
        return allowCors(
            jsonify({"msg": "Token Host is not same as requested host."}), 400)

    if host.get("writable") == False and not payload.get("writable"):
        return allowCors(jsonify({"msg": "You dont have write permission."}),
                         400)

    if isValidPath({"path": req.get('path')}, host.get("path")):
        fullPath = safe_join(req.get('path'), req.get('file_name'))
        exit_code = os.system(f'del /f \"{fullPath}\"') if platform.system(
        ) != 'Windows' else os.system(f'rm -rf \"{fullPath}\"')

        if exit_code == 0 and changeOwner(fullPath):
            return allowCors(jsonify({"msg": "File Removed"}))
        else:
            return allowCors(
                jsonify({"msg": f'Error ocurred with exit {exit_code}'}), 400)
    else:
        return allowCors(jsonify({"msg": "Invalid Path"}), 400)
Exemplo n.º 14
0
def uploadFile():
    files = request.files

    files['image'].save(path.join('D:/save/', files['image'].filename))

    return allowCors(jsonify({"msg": "Success"}))
Exemplo n.º 15
0
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))
Exemplo n.º 16
0
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))
Exemplo n.º 17
0
def init():
    return allowCors(jsonify({}))
Exemplo n.º 18
0
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))
Exemplo n.º 19
0
def pending():
    return allowCors(jsonify({}))