def addSystem():
    g = request.args.get("groupName")
    t = request.args.get("team")
    n = request.args.get("notes")
    s = request.args.get("systems").split(";")
    components = []
    verifyAccess("system_group", "write", t, True)
    if len(request.args.get("components")) != 0:
        for x in request.args.get("components").split(","):
            components.append(Component(x.split("|")[1]))
    try:
        if vmdb.addSystemGroup(
            SystemGroup(groupID=None, groupName=g, team=t, notes=n, systems=s, components=components)
        ):
            status = ["system_added", "success"]
            error = ""
        else:
            status = ["action_failed", "error"]
            error = "Could not save the system to the database"
    except AlreadyExistsException:
        status = ["action_failed", "error"]
        error = "A group with this name already exists"
    except TeamRequiredException:
        status = ["action_failed", "error"]
        error = "There is no team selected to add this system group to."
    except InvalidVariableTypes:
        status = ["action_failed", "error"]
        error = "Some of the input is invalid"
    return jsonify({"status": status, "error": error, "groups": vmdb.getGroupVulns(t)})
def getTicketInfo():
    i = request.form.get('id', type=str).split("|")
    verifyAccess("ticket", "read", i[0])
    return render_template('ticket.html',
                           ticket=vmdb.getTicket(i[2].strip("vuln:"), i[3],
                                                 i[1], i[0]),
                           statusses=vmdb.getStatusses())
def editSystem():
    team = request.form.get("team", type=str)
    group = request.form.get("group", type=str)
    verifyAccess("system_group", "write", team)
    return render_template(
        "addSystem.html", team=team, components=vmdb.getComponentNames(), group=vmdb.getGroups(team, group)[0]
    )
def editSystem():
    team = request.form.get('team', type=str)
    group = request.form.get('group', type=str)
    verifyAccess("system_group", "write", team)
    return render_template("addSystem.html",
                           team=team,
                           components=vmdb.getComponentNames(),
                           group=vmdb.getGroups(team, group)[0])
def setTicketNotes():
    i = request.args.get('id', type=str).split("|")
    notes = request.args.get('notes', type=str)
    verifyAccess("ticket", "write", i[0], True)
    ticket = vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0])
    return jsonify({
        "status":
        vmdb.setDBTicketStatus(ticket, current_user.id, notes=notes)
    })
def setTicketStatus():
    i = request.args.get('id', type=str).split("|")
    status = request.args.get('status', type=str)
    verifyAccess("ticket", "write", i[0], True)
    ticket = vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0])
    curStatus = vmdb.setDBTicketStatus(ticket, current_user.id, status=status)
    updated = None
    if status == "closed-implemented":
        updated = vmdb.updateCPE(ticket)
    #print(updated)
    return jsonify({"status": curStatus, "statusses": vmdb.getStatusses()})
def setTicketStatus():
    i = request.args.get("id", type=str).split("|")
    status = request.args.get("status", type=str)
    verifyAccess("ticket", "write", i[0], True)
    ticket = vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0])
    curStatus = vmdb.setDBTicketStatus(ticket, current_user.id, status=status)
    updated = None
    if status == "closed-implemented":
        updated = vmdb.updateCPE(ticket)
    # print(updated)
    return jsonify({"status": curStatus, "statusses": vmdb.getStatusses()})
def setUpdate():
    i = request.args.get("id", type=str).split("|")
    newCPE = request.args.get("newCPE", type=str)
    updateType = request.args.get("updateType", type=str)
    verifyAccess("ticket", "write", i[0], True)
    ticket = vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0])
    return jsonify(
        {
            "status": vmdb.setDBTicketStatus(ticket, current_user.id, updateType=updateType, update=newCPE),
            "statusses": vmdb.getStatusses(),
        }
    )
def setUpdate():
    i = request.args.get('id', type=str).split("|")
    newCPE = request.args.get('newCPE', type=str)
    updateType = request.args.get('updateType', type=str)
    verifyAccess("ticket", "write", i[0], True)
    ticket = vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0])
    return jsonify({
        "status":
        vmdb.setDBTicketStatus(ticket,
                               current_user.id,
                               updateType=updateType,
                               update=newCPE),
        "statusses":
        vmdb.getStatusses()
    })
def getVulnerabilities():
    i = request.form.get("id", type=str).split("|")
    verifyAccess("system_group", "read", i[0])
    cpe = i[2] if i[2] else None
    t = "Vulnerabilities for %s in %s" % (Component(cpe).product, i[1]) if i[2] else "Vulnerabilities in %s" % i[1]
    vulns = vmdb.getVulnsForSystem(i[1], i[0], cpe)
    return render_template("vulnerabilities.html", cpe=cpe, title=t, vulns=vulns, team=i[0], system=i[1])
def getTeamContent():
    team = request.form.get('team', type=str)
    verifyAccess("team", "read", team)
    return render_template("teamContent.html",
                           vulns=vmdb.getLastTeamVulns(team, 10),
                           team=team,
                           user=getCurrentUser())
def getClosed():
    team = request.form.get("team", type=str)
    system = request.form.get("system", type=str)
    verifyAccess("ticket", "read", team)
    tickets = {}
    for t in vmdb.getTickets(team, system, limit="closed"):
        if t.groupName in tickets.keys():
            tickets[t.groupName].append(t)
        else:
            tickets[t.groupName] = [t]
    return render_template("systemTickets.html", tickets=tickets, team=team, system=system)
def getUserInfo():
    user = current_user
    axx = []
    for x in vmdb.getTeamNames():
        apt = getAccessPerTeam(x)
        if set(apt.values()) - set(["none", False]):
            axx.append({"team": x, "access": getAccessPerTeam(x)})
    for i, x in enumerate(axx):
        if x["team"] == "-":
            axx.pop(i)
    u = {"teams": axx, "first_name": user.first_name, "last_name": user.last_name, "id": user.id}
    return u
def getClosed():
    team = request.form.get('team', type=str)
    system = request.form.get('system', type=str)
    verifyAccess("ticket", "read", team)
    tickets = {}
    for t in vmdb.getTickets(team, system, limit="closed"):
        if t.groupName in tickets.keys(): tickets[t.groupName].append(t)
        else: tickets[t.groupName] = [t]
    return render_template("systemTickets.html",
                           tickets=tickets,
                           team=team,
                           system=system)
def getVulnerabilities():
    i = request.form.get("id", type=str).split("|")
    verifyAccess("system_group", "read", i[0])
    cpe = i[2] if i[2] else None
    t = "Vulnerabilities for %s in %s" % (Component(
        cpe).product, i[1]) if i[2] else "Vulnerabilities in %s" % i[1]
    vulns = vmdb.getVulnsForSystem(i[1], i[0], cpe)
    return render_template("vulnerabilities.html",
                           cpe=cpe,
                           title=t,
                           vulns=vulns,
                           team=i[0],
                           system=i[1])
def addSystem():
    g = request.args.get('groupName')
    t = request.args.get('team')
    n = request.args.get('notes')
    s = request.args.get('systems').split(";")
    components = []
    verifyAccess("system_group", "write", t, True)
    if len(request.args.get('components')) != 0:
        for x in request.args.get('components').split(","):
            components.append(Component(x.split("|")[1]))
    try:
        if vmdb.addSystemGroup(
                SystemGroup(groupID=None,
                            groupName=g,
                            team=t,
                            notes=n,
                            systems=s,
                            components=components)):
            status = ["system_added", "success"]
            error = ""
        else:
            status = ["action_failed", "error"]
            error = "Could not save the system to the database"
    except AlreadyExistsException:
        status = ["action_failed", "error"]
        error = "A group with this name already exists"
    except TeamRequiredException:
        status = ["action_failed", "error"]
        error = "There is no team selected to add this system group to."
    except InvalidVariableTypes:
        status = ["action_failed", "error"]
        error = "Some of the input is invalid"
    return jsonify({
        "status": status,
        "error": error,
        "groups": vmdb.getGroupVulns(t)
    })
def get_Statistics():
    team = request.form.get("team", type=str)
    verifyAccess("statistics", "read", team)
    cat = []
    o = []
    c = []
    oac = []
    for x in vmdb.getStatistics(team):
        cat.append(x["systems"])
        o.append(x["new"])
        c.append(x["closed"])
        oac.append(x["openedAndClosed"])
    return render_template(
        "statistics.html", stats={"categories": cat, "opened": o, "closed": c, "openedAndClosed": oac}
    )
def getUserInfo():
    user = current_user
    axx = []
    for x in vmdb.getTeamNames():
        apt = getAccessPerTeam(x)
        if set(apt.values()) - set(["none", False]):
            axx.append({"team": x, "access": getAccessPerTeam(x)})
    for i, x in enumerate(axx):
        if x["team"] == "-":
            axx.pop(i)
    u = {
        "teams": axx,
        "first_name": user.first_name,
        "last_name": user.last_name,
        "id": user.id
    }
    return u
def get_Statistics():
    team = request.form.get('team', type=str)
    verifyAccess("statistics", "read", team)
    cat = []
    o = []
    c = []
    oac = []
    for x in vmdb.getStatistics(team):
        cat.append(x["systems"])
        o.append(x["new"])
        c.append(x["closed"])
        oac.append(x["openedAndClosed"])
    return render_template("statistics.html",
                           stats={
                               "categories": cat,
                               "opened": o,
                               "closed": c,
                               "openedAndClosed": oac
                           })
def getSystems():
    team = request.form.get('team', type=str)
    verifyAccess("team", "read", team)
    return render_template("systems.html",
                           team=team,
                           systemGroups=vmdb.getGroupVulns(team, True))
def setTicketNotes():
    i = request.args.get("id", type=str).split("|")
    notes = request.args.get("notes", type=str)
    verifyAccess("ticket", "write", i[0], True)
    ticket = vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0])
    return jsonify({"status": vmdb.setDBTicketStatus(ticket, current_user.id, notes=notes)})
def addSystemView():
    team = request.form.get('team', type=str)
    verifyAccess("system_group", "write", team)
    return render_template("addSystem.html",
                           team=team,
                           components=vmdb.getComponentNames())
def addSystemView():
    team = request.form.get("team", type=str)
    verifyAccess("system_group", "write", team)
    return render_template("addSystem.html", team=team, components=vmdb.getComponentNames())
def getSystems():
    team = request.form.get("team", type=str)
    verifyAccess("team", "read", team)
    return render_template("systems.html", team=team, systemGroups=vmdb.getGroupVulns(team, True))
def getTeamContent():
    team = request.form.get("team", type=str)
    verifyAccess("team", "read", team)
    return render_template("teamContent.html", vulns=vmdb.getLastTeamVulns(team, 10), team=team, user=getCurrentUser())
def getTicketInfo():
    i = request.form.get("id", type=str).split("|")
    verifyAccess("ticket", "read", i[0])
    return render_template(
        "ticket.html", ticket=vmdb.getTicket(i[2].strip("vuln:"), i[3], i[1], i[0]), statusses=vmdb.getStatusses()
    )
def defaultValues(conn):
  import lib.database.VulnManager as vmdb
  for x in def_ticket_statusses:   vmdb.addTicket_Status(x)
  for x in def_ticket_resolutions: vmdb.addTicket_Resolution(x)
  for x in def_access_rights:      vmdb.addAccess_Right(x)
  for x in def_ticket_priorities:  vmdb.addTicket_Priority(x["name"], x["max_implement_time"], x["min_cvss"])
  for x in def_ticket_urgencies:   vmdb.addTicket_Urgency(x["name"], x["score"])
  for x in def_teams:              vmdb.addTeam(x[0], x[1])
  for x in def_roles:              vmdb.addRole(x["name"], x["ticket_access"], x["system_group_access"], 
                                                x["statistics_access"], x["team_access"], x["db_access"])
def defaultValues(conn):
    import lib.database.VulnManager as vmdb
    for x in def_ticket_statusses:
        vmdb.addTicket_Status(x)
    for x in def_ticket_resolutions:
        vmdb.addTicket_Resolution(x)
    for x in def_access_rights:
        vmdb.addAccess_Right(x)
    for x in def_ticket_priorities:
        vmdb.addTicket_Priority(x["name"], x["max_implement_time"],
                                x["min_cvss"])
    for x in def_ticket_urgencies:
        vmdb.addTicket_Urgency(x["name"], x["score"])
    for x in def_teams:
        vmdb.addTeam(x[0], x[1])
    for x in def_roles:
        vmdb.addRole(x["name"], x["ticket_access"], x["system_group_access"],
                     x["statistics_access"], x["team_access"], x["db_access"])