Exemplo n.º 1
0
def updateChildren(parentId, deletingParent=False):
    """
    Sets field 'hasParentChanged' to true on all dashboards that are clones of 
    the changing dashboard.
    If the dashboard is being deleted(or private) then it unsets the parent field.
    """
    Dashboard.objects(parent=parentId).update(set__hasParentChanged=True)
    if deletingParent:
        Dashboard.objects(parent=parentId).update(unset__parent=1)
Exemplo n.º 2
0
def ignore_parent(request, id):
    """
    Ajax call to ignore that the parent of the dashboard has been changed.
    Called from dashboard.html
    """
    try:
        Dashboard.objects(id=id).update(set__hasParentChanged=False)
    except:
        return respondWithError("An error occured while updating dashboard. Please try again later.", True)
    return respondWithSuccess("success")
Exemplo n.º 3
0
def renameDashboard(id, name, userId):
    """
    Renames the given dashboard
    """
    if not name:
        return "You must give a name to the dashboard."
    if Dashboard.objects(name=name, analystId=userId):
        return "You already have a dashboard with that name."
    Dashboard.objects(id=id).update(set__name=name)
    return True
Exemplo n.º 4
0
def create_dashboard(drop=False):
    from cripts.dashboards.dashboard import SavedSearch, Dashboard
    if drop:
        Dashboard.drop_collection()
        SavedSearch.drop_collection()
    defaultDashboard = Dashboard.objects(name="Default",
                                         analystId__not__exists=1,
                                         isPublic=True).first()
    if not defaultDashboard:
        defaultDashboard = Dashboard()
        defaultDashboard.name = "Default"
        defaultDashboard.isPublic = True
        defaultDashboard.save()
        for title in [
                "Counts",
        ]:
            savedSearch = SavedSearch()
            savedSearch.name = title
            savedSearch.dashboard = defaultDashboard.id
            savedSearch.isDefaultOnDashboard = True
            savedSearch.tableColumns = getColumnsForTable(title)
            if title == "Counts":
                savedSearch.sizex = 10

            savedSearch.save()
        print "Default Dashboard Created."
    else:
        print "Default Dashboard already exists."
Exemplo n.º 5
0
def get_dashboard(user,dashId=None):
    """
    Gets a specific dashbaord for the user. If dashId is provided it looks it up.
    If dashId is not provided or the dashboard does not exist, it gets the user's
    default dashboard. If that dashboard does not exist, it first looks for a 
    user-modified child of the public Default dashboard. Finally it will retrieve 
    the public default dashboard if no others exist.
    """
    dashboard = None
    if dashId:
        dashboard = Dashboard.objects(id=dashId).first()
        if not dashboard:
            return {'success': False,
                'message': "The dashboard you selected no longer exists."}
    elif user.defaultDashboard:
        try:
            dashboard = Dashboard.objects(id=user.defaultDashboard).first()
        except:
            user.defaultDashboard = None
            user.save()
    if not dashboard:
        dashboard = Dashboard.objects(name="Default", analystId__not__exists=1, isPublic=True).first()
        if dashboard:
            cloneOfDefault = Dashboard.objects(parent=dashboard.id, analystId=user.id).first()
            if cloneOfDefault:
                dashboard = cloneOfDefault
        else:
            return {'success': False,
                'message': "No Default Dashboard. Run 'manage.py create_default_dashboard' to create."}
    dashId = dashboard.id
    tables = []
    savedTables = SavedSearch.objects(dashboard=dashId, isPinned=True)
    for table in savedTables:
        tables.append(createTableObject(user, table=table))
    otherDashboardIds = []
    otherDashboards = {}
    for dash in Dashboard.objects(id__ne=dashId, analystId=user.id):
        otherDashboardIds.append(dash.id)
        otherDashboards[dash.id] = dash.name
    otherSearches = []
    for search in SavedSearch.objects(dashboard__in=otherDashboardIds, isPinned=True) :
        otherSearches.append({
                        "id":search.id,
                        "dash":otherDashboards[search.dashboard],
                        "name":search.name
                        })
    return {"success": True,
            "tables": tables,
            "dashboards": getDashboardsForUser(user),
            "currentDash": str(dashId),
            'parentHasChanged':dashboard.hasParentChanged,
            'parent':dashboard.parent,
            'dashTheme':dashboard.theme,
            "otherSearches":otherSearches,
            "userId": dashboard.analystId}
Exemplo n.º 6
0
def changeTheme(id, theme):
    """
    Changes theme of the dashboard. 
    CURRENTLY UNUSED.
    """
    try:
        Dashboard.objects(id=id).update(set__theme=theme)
    except Exception as e:
        print e
        return False
    return "Dashboard updated successfully."
Exemplo n.º 7
0
def ignore_parent(request, id):
    """
    Ajax call to ignore that the parent of the dashboard has been changed.
    Called from dashboard.html
    """
    try:
        Dashboard.objects(id=id).update(set__hasParentChanged=False)
    except:
        return respondWithError(
            "An error occured while updating dashboard. Please try again later.",
            True)
    return respondWithSuccess("success")
Exemplo n.º 8
0
def deleteDashboard(id):
    """
    Deletes the dashboard with the given id and updates clones of it.
    Also deletes all saved searches affiliated with it
    """
    try:
        dashboard = Dashboard.objects(id=id).first()
        name = dashboard.name
        if dashboard.isPublic:
            updateChildren(id, deletingParent=True)
        SavedSearch.objects(dashboard=id).delete()
        Dashboard.objects(id=id).delete()
    except Exception as e:
        print e
        return False
    return name
Exemplo n.º 9
0
def delete_table(userId, id):
    """
    Deletes a table from the db. Only can be called via the saved_search.html
    """
    try:
        savedSearch = SavedSearch.objects(id=id).first()
        tableName = savedSearch.name
        doDelete = True
        message = tableName+" deleted successfully!"
        if savedSearch.isDefaultOnDashboard:
            dashboards = []
            for dash in Dashboard.objects(analystId=userId):
                dashboards.append(dash.id)
            if SavedSearch.objects(dashboard__in=dashboards, isDefaultOnDashboard=True, name=tableName).count() == 1:
                savedSearch.col = 1
                savedSearch.row = 1
                savedSearch.isPinned = False
                savedSearch.save()
                doDelete = False
                message = tableName+" is now hidden."
        if doDelete:
            dashId = savedSearch.dashboard
            savedSearch.delete()
            deleteDashboardIfEmpty(dashId)
    except Exception as e:
        print e
        return {'success': False,
                'message': "Search could not be found. Please refresh and try again."}
    return {'success': True,'message': message, 'wasDeleted': doDelete}
Exemplo n.º 10
0
def generate_search_for_saved_table(user, id=None,request=None):
    """
    Called by edit_save_search in views.py. This is for editing a previously
    saved table or one of the default dashboard tables
    """
    from cripts.core.handlers import data_query
    response = {}
    savedSearch = None
    try:
        savedSearch = SavedSearch.objects(id=id).first()
        if not savedSearch:
            response['Result'] = "ERROR"
            response['Message'] = "Error finding table, please try again later."
            return response
    except:
        savedSearch = SavedSearch()
        savedSearch.isDefaultOnDashboard = True
        savedSearch.name = id.replace("_", " ")
        id = None
    results = []
    records = []
    term = ""
    url = ""
    if not savedSearch.isDefaultOnDashboard:
        objType = get_obj_type_from_string(savedSearch.objType)
        resp = get_query_without_request(objType, user.username, savedSearch.searchTerm, "global")
        if resp['Result'] == "ERROR":
            return resp
        formatted_query = resp['query']
        term = resp['term']
        resp = data_query(objType, user.username, query=formatted_query, count=True)
        results.append({'count': resp['count'],
                                      'name': savedSearch.objType}) 
    else:
        results = {"name":savedSearch.name,
                   "count":str(len(records)),
                   "type":get_obj_name_from_title(savedSearch.name)}
        #special url to get the records of a default dashboard since their queries are different 
        url = reverse("cripts.dashboards.views.get_dashboard_table_data", 
                      kwargs={"tableName":str(savedSearch.name.replace(" ", "_"))})
    args = {'term': term,
            'results': results,
            'dataUrl':url,
            'Result': "OK"
            }
    if savedSearch:
        args.update({'tableId':id,
                'tableName': savedSearch.name,
                'columns': savedSearch.tableColumns,
                'sortBy': savedSearch.sortBy,
                'sizex' : savedSearch.sizex,
                'maxRows': savedSearch.maxRows,
                'isDefaultOnDashboard': savedSearch.isDefaultOnDashboard,
                })
        if savedSearch.dashboard:
            args["currentDash"] = str(savedSearch.dashboard)
            args["dashtheme"] = Dashboard.objects(id=savedSearch.dashboard).first().theme
    return args
Exemplo n.º 11
0
def save_search(request):
    """
    Ajax call to save the table. Only called from the saved_search.html
    """
    dashId = request.GET.get('dashId', None)
    newDashName = request.GET.get('newDashName', None)
    tableId = request.GET.get("tableId", None)
    errorMessage = None
    clone = False
    try:
        if newDashName:
            newDash = createNewDashboard(request.user.id, newDashName)
            if not newDash:
                raise(Exception, "Dashboard already exists")
            dashboard = newDash
        elif dashId:
            dashboard = Dashboard.objects(id=dashId).first()
            if dashboard.isPublic and dashboard.analystId != request.user.id:
                newDash = cloneDashboard(request.user.id, dashboard, cloneSearches = True, skip=tableId)
                dashboard = newDash
                clone = True
                newDashName = newDash.name
            elif dashboard.isPublic:
                updateChildren(dashboard.id)
        else:
            errorMessage = "Error finding dashboard. Please refresh and try again."
    except Exception as e:
        print e
        errorMessage = "You already have a dashboard with that name."
    if errorMessage:
        return respondWithError(errorMessage, True)
    userId = request.GET.get('userId', None)
    tableName = request.GET.get('tableName', None)
    searchTerm = request.GET.get('query', None)
    objType = request.GET.get('object_type', None)
    columns = json.loads(request.GET.get("columns", ""))
    sortBy = request.GET.get("sortBy", None)
    isDefault = request.GET.get("isDefaultOnDashboard", "False")
    sizex = request.GET.get("sizex", None)
    maxRows = request.GET.get("maxRows", None)
    if isDefault.lower() == "true":
        isDefault = True
    else:
        isDefault = False
    if sortBy:
        sortBy = json.loads(sortBy)
    response = save_data(userId, columns, tableName, searchTerm, objType, sortBy,
                         tableId, sizex=sizex, isDefaultOnDashboard=isDefault,
                         maxRows=maxRows,
                         dashboard=dashboard, clone=clone)
    if newDashName:
        response["newDashId"] = str(newDash.id)
        response["newDashName"] = newDash.name
        response["isClone"] = clone
        response["newDashUrl"] = reverse("cripts.dashboards.views.dashboard",
                                          kwargs={"dashId":newDash.id})
    return httpResponse(response)
Exemplo n.º 12
0
def save_new_dashboard(request):
    """
    Ajax call to save the dashboard and the positioning and width of the
    tables on it. Called from the dashboard.html
    """
    data = json.loads(request.POST.get('data', ''))
    userId = request.POST.get('userId', None)
    dashId = request.POST.get('dashId', None)
    user = request.user
    clone = False
    if not dashId:
        return respondWithError(
            "Error finding dashboard. Please refresh and try again.", True)
    else:
        dashboard = Dashboard.objects(id=dashId).first()
        if dashboard.isPublic and dashboard.analystId != user.id:
            dashboard = cloneDashboard(userId, dashboard)
            if not dashboard:
                return respondWithError(
                    "You already have a dashboard with that name.", True)
            clone = True
            if not user.defaultDashboard:
                setDefaultDashboard(user, dashboard.id)
        elif dashboard.isPublic:
            updateChildren(dashboard.id)
    for table in data:
        isDefault = False
        if table['isDefault'].lower() == "true":
            isDefault = True
        sortBy = None
        if 'sortDirection' in table and 'sortField' in table:
            sortBy = {
                'field': table['sortField'],
                'direction': table['sortDirection']
            }
        response = save_data(userId,
                             table['columns'],
                             table['tableName'],
                             tableId=table['id'],
                             isDefaultOnDashboard=isDefault,
                             sortBy=sortBy,
                             dashboard=dashboard,
                             clone=clone,
                             row=table['row'],
                             grid_col=table['col'],
                             sizex=table['sizex'],
                             sizey=table['sizey'])
        if not response['success']:
            return httpResponse(response)
    return httpResponse({
        "success": True,
        "clone": clone,
        "dashId": str(dashboard.id),
        "message": "Dashboard saved successfully!"
    })
Exemplo n.º 13
0
def setDefaultDashboard(user, dashId):
    """
    Sets the users default dashboard
    """
    try:
        name = Dashboard.objects(id=dashId).first().name
        user.defaultDashboard = dashId
        user.save()
        return name
    except:
        return False
Exemplo n.º 14
0
def createNewDashboard(userId, name):
    """
    Creates a new dashboard for the user
    """
    if Dashboard.objects(analystId=userId,name=name):
        return
    newDash = Dashboard()
    newDash.name = name
    newDash.analystId = userId
    newDash.save()
    return newDash
Exemplo n.º 15
0
def cloneDashboard(userId, dashboard, cloneSearches=False, skip=None):
    """
    Clones a public dashboard to a user-modified version of if.
    cloneSearches will clone all affiliated searches with the dashboard.
    Skip will skip a specific table if cloning searches
    """
    if Dashboard.objects(analystId=userId,name=dashboard.name):
        return
    newDash = Dashboard()
    newDash.name = dashboard.name
    newDash.theme = dashboard.theme
    newDash.analystId = userId
    newDash.parent = dashboard.id
    newDash.save()
    if cloneSearches:
        for search in SavedSearch.objects(dashboard = dashboard.id):
            if skip != str(search.id):
                cloneSavedSearch(search, newDash.id)
    return newDash
Exemplo n.º 16
0
def getDashboardsForUser(user):
    """
    Gets all the users dashboards and public dashboards. It will then remove 
    all public dashboards that have been cloned by the user
    """
    dashboards = Dashboard.objects(Q(analystId=user.id) | Q(isPublic=True))
    parents = []
    userDashboards = []
    #get all id's of parent dashboards
    for dash in dashboards:
        if dash.parent:
            parents.append(dash.parent)
    #remove any parent from the list to prevent duplicate dashboards
    for dash in dashboards:
        if not dash.id in parents:
            userDashboards.append(dash)
    return userDashboards
Exemplo n.º 17
0
def save_new_dashboard(request):
    """
    Ajax call to save the dashboard and the positioning and width of the
    tables on it. Called from the dashboard.html
    """
    data = json.loads(request.POST.get('data', ''))
    userId = request.POST.get('userId', None)
    dashId = request.POST.get('dashId', None)
    user = request.user
    clone = False
    if not dashId:
        return respondWithError("Error finding dashboard. Please refresh and try again.", True)
    else:
        dashboard = Dashboard.objects(id=dashId).first()
        if dashboard.isPublic and dashboard.analystId != user.id:
            dashboard = cloneDashboard(userId, dashboard)
            if not dashboard:
                return respondWithError("You already have a dashboard with that name.", True)
            clone = True
            if not user.defaultDashboard:
                setDefaultDashboard(user, dashboard.id)
        elif dashboard.isPublic:
            updateChildren(dashboard.id)
    for table in data:
        isDefault = False
        if table['isDefault'].lower() == "true":
            isDefault = True
        sortBy = None
        if 'sortDirection' in table and 'sortField' in table:
            sortBy = {'field':table['sortField'],'direction':table['sortDirection']}
        response = save_data(userId, table['columns'], table['tableName'],
                             tableId=table['id'], isDefaultOnDashboard=isDefault,
                             sortBy=sortBy, dashboard=dashboard,
                             clone=clone, row=table['row'], grid_col=table['col'],
                             sizex=table['sizex'], sizey=table['sizey'])
        if not response['success']:
            return httpResponse(response)
    return httpResponse({"success":True,
                         "clone":clone,
                         "dashId": str(dashboard.id),
                         "message":"Dashboard saved successfully!"})
Exemplo n.º 18
0
def create_dashboard(drop=False):
    from cripts.dashboards.dashboard import SavedSearch, Dashboard
    if drop:
        Dashboard.drop_collection()
        SavedSearch.drop_collection()
    defaultDashboard = Dashboard.objects(name="Default", analystId__not__exists=1 , isPublic=True).first()
    if not defaultDashboard:
        defaultDashboard = Dashboard()
        defaultDashboard.name = "Default"
        defaultDashboard.isPublic = True
        defaultDashboard.save()
        for title in ["Counts", ]:
            savedSearch = SavedSearch()
            savedSearch.name = title
            savedSearch.dashboard = defaultDashboard.id
            savedSearch.isDefaultOnDashboard = True
            savedSearch.tableColumns = getColumnsForTable(title)
            if title == "Counts":
                savedSearch.sizex = 10
                
            savedSearch.save()
        print "Default Dashboard Created."
    else:
        print "Default Dashboard already exists."
Exemplo n.º 19
0
def get_saved_searches_list(user):
    """
    Returns all user dashboards and their affiliated saved searches.
    """
    dashboards = []
    for dash in Dashboard.objects(analystId=user.id):
        tables = []
        for table in SavedSearch.objects(dashboard=dash.id):
            if table.isDefaultOnDashboard:
                table.searchTerm = ""
                table.objType = ""
            tables.append(table)
        tempDash = {
                    "name":dash.name,
                   "id": dash.id,
                   "theme":dash.theme,
                   'isPublic':dash.isPublic,
                   "tables": tables
                }
        if dash.parent:
            tempDash['isModified'] = True
        dashboards.append(tempDash)
            
    return {"dashboards": dashboards}
Exemplo n.º 20
0
def setPublic(id, makePublic):
    """
    Sets the dashboards visibility to public or private
    """
    try:
        dashboard = Dashboard.objects(id=id).first()
        if makePublic and Dashboard.objects(name=dashboard.name, isPublic=True):
            return "There already exists a public dashboard with that name. "\
                "You must rename your dashboard before making it public."
        Dashboard.objects(id=id).update(set__isPublic=makePublic)
        #if making a dashboard private, clear all parent-child relationships
        if not makePublic:
            updateChildren(id, deletingParent=True)
        else:#if making public, remove parent
            Dashboard.objects(id=id).update(unset__parent=1)
    except Exception as e:
        print e
        return "An error occured while updating table. Please try again later."
    return True
Exemplo n.º 21
0
def save_search(request):
    """
    Ajax call to save the table. Only called from the saved_search.html
    """
    dashId = request.GET.get('dashId', None)
    newDashName = request.GET.get('newDashName', None)
    tableId = request.GET.get("tableId", None)
    errorMessage = None
    clone = False
    try:
        if newDashName:
            newDash = createNewDashboard(request.user.id, newDashName)
            if not newDash:
                raise (Exception, "Dashboard already exists")
            dashboard = newDash
        elif dashId:
            dashboard = Dashboard.objects(id=dashId).first()
            if dashboard.isPublic and dashboard.analystId != request.user.id:
                newDash = cloneDashboard(request.user.id,
                                         dashboard,
                                         cloneSearches=True,
                                         skip=tableId)
                dashboard = newDash
                clone = True
                newDashName = newDash.name
            elif dashboard.isPublic:
                updateChildren(dashboard.id)
        else:
            errorMessage = "Error finding dashboard. Please refresh and try again."
    except Exception as e:
        print e
        errorMessage = "You already have a dashboard with that name."
    if errorMessage:
        return respondWithError(errorMessage, True)
    userId = request.GET.get('userId', None)
    tableName = request.GET.get('tableName', None)
    searchTerm = request.GET.get('query', None)
    objType = request.GET.get('object_type', None)
    columns = json.loads(request.GET.get("columns", ""))
    sortBy = request.GET.get("sortBy", None)
    isDefault = request.GET.get("isDefaultOnDashboard", "False")
    sizex = request.GET.get("sizex", None)
    maxRows = request.GET.get("maxRows", None)
    if isDefault.lower() == "true":
        isDefault = True
    else:
        isDefault = False
    if sortBy:
        sortBy = json.loads(sortBy)
    response = save_data(userId,
                         columns,
                         tableName,
                         searchTerm,
                         objType,
                         sortBy,
                         tableId,
                         sizex=sizex,
                         isDefaultOnDashboard=isDefault,
                         maxRows=maxRows,
                         dashboard=dashboard,
                         clone=clone)
    if newDashName:
        response["newDashId"] = str(newDash.id)
        response["newDashName"] = newDash.name
        response["isClone"] = clone
        response["newDashUrl"] = reverse("cripts.dashboards.views.dashboard",
                                         kwargs={"dashId": newDash.id})
    return httpResponse(response)
Exemplo n.º 22
0
def deleteDashboardIfEmpty(dashId):
    """
    Checks if a dashboard has saved searches. Deletes it if it doesn't.
    """
    if not SavedSearch.objects(dashboard=dashId):
        Dashboard.objects(id=dashId).delete()