Beispiel #1
0
def rolesList(context,
              main=None,
              add=None,
              filterinfo=None,
              session=None,
              params=None,
              curvalue="",
              startswith=False,
              firstrecord=0,
              recordcount=None):
    u'''Функция list селектора типа элемента. '''
    # raise Exception(curvalue)
    recordList = ArrayList()
    roles = RolesCursor(context)
    roles.setFilter(
        'description',
        "@%s'%s'%%" % ("%" * (not startswith), curvalue.replace("'", "''")))
    roles.orderBy('id')
    roles.limit(firstrecord, recordcount)
    if roles.tryFindSet():
        while True:
            rec = DataRecord()
            rec.setId(roles.id)
            rec.setName(
                '%s - %s' %
                (roles.id, roles.description if roles.description else ''))
            recordList.add(rec)
            if not roles.nextInSet():
                break
    return ResultSelectorData(recordList, 0)
Beispiel #2
0
def rolesList(context,
              main=None,
              add=None,
              filterinfo=None,
              session=None,
              params=None,
              curvalue=None,
              startswith=None,
              firstrecord=None,
              recordcount=None):
    u'''Функция list для селектора выбора ролей. '''

    roles = RolesCursor(context)
    roles.setFilter(
        'id', """!'editor'&!'reader'&@%s'%s'%%""" %
        ("%" * (not startswith), curvalue.replace("'", "''")))
    roles.orderBy('id')
    roles.limit(firstrecord, recordcount)

    recordList = ArrayList()
    if roles.tryFindSet():
        while True:
            rec = DataRecord()
            rec.setId(unicode(roles.id))
            rec.setName(roles.id)
            recordList.add(rec)
            if not roles.nextInSet():
                break

    return ResultSelectorData(recordList, 0)
Beispiel #3
0
def gridMeta(context, main=None, add=None, filterinfo=None, session=None, elementId=None):
    u'''Функция получения настроек грида. '''

    # Курсор таблицы directories
    roles = RolesCursor(context)
    # Вычисляем количества записей в таблице
    specialRoles = ["!'editor'", "!'reader'"]
    roles.setFilter("id", '&'.join(specialRoles))
    totalcount = roles.count()
    # Заголовок таблицы
    header = "Роли"
    _header = {"id": [u"Роль"],
               "description": [u"Описание"],
               }

    # Определяем список полей таблицы для отображения
    settings = {}
    settings["gridsettings"] = {"columns": {"col": []},
                                "properties": {"@pagesize":"50",
                                               "@gridWidth": "100%",
                                               "@gridHeight": getGridHeight(session, numberOfGrids=1.6, delta=35),
                                               "@totalCount": totalcount,
                                               "@profile": "default.properties"},
                                "labels": {"header": header}
                                }
    # Добавляем поля для отображения в gridsettings
    settings["gridsettings"]["columns"]["col"].append({"@id": _header["id"][0],
                                                       "@width": "80px"})
    settings["gridsettings"]["columns"]["col"].append({"@id": _header["description"][0],
                                                       "@width": "400px"})

    res = XMLJSONConverter.jsonToXml(json.dumps(settings))
    return JythonDTO(None, res)
Beispiel #4
0
def gridData(context, main=None, add=None, filterinfo=None,
             session=None, elementId=None, sortColumnList=None, firstrecord=None, pagesize=None):
    u'''Функция получения данных для грида. '''

    # Создание экземпляра курсора разрешения
    roles = RolesCursor(context)
    # Определяем переменную для JSON данных
    data = {"records":{"rec":[]}}
    # Проходим по таблице и заполняем data
    specialRoles = ["!'editor'", "!'reader'"]

    roles.setFilter("id", '&'.join(specialRoles))
    if sortColumnList:
        sortName = toHexForXml(sortColumnList[0].id)
        sortType = unicode(sortColumnList[0].sorting).lower()
    else:
        sortName = None

    _header = {"roleId": ["~~id"],
               "id": [u"Роль"],
               "description": [u"Описание"],

               "properties": [u"properties"]
               }
    for column in _header:
        _header[column].append(toHexForXml(_header[column][0]))
        if sortName == _header[column][1]:
            roles.orderBy("%s %s" % (column, sortType))

    roles.limit(firstrecord - 1, pagesize)
    if roles.tryFindSet():
        while True:
            rolesDict = {}
            rolesDict[_header["roleId"][1]] = roles.id
            for column in [x for x in _header.keys() if x not in ("roleId", "properties")]:
                rolesDict[_header[column][1]] = getattr(roles, column) or ''

            rolesDict['properties'] = {"event": {"@name":"row_single_click",
                                                 "action": {"#sorted": [{"main_context": 'current'},
                                                                        {"datapanel":{'@type':"current",
                                                                                      '@tab':"current",
                                                                                      "element":{"@id":"id_perm_roles_grid"}
                                                                                      }
                                                                         }]
                                                            }
                                                 }
                                       }
            data["records"]["rec"].append(rolesDict)
            if not roles.nextInSet():
                break

    res = XMLJSONConverter.jsonToXml(json.dumps(data))
    return JythonDTO(res, None)
Beispiel #5
0
def cardData(context,
             main=None,
             add=None,
             filterinfo=None,
             session=None,
             elementId=None):
    u'''Функция данных для карточки редактирования содержимого таблицы ролей. '''

    roles = RolesCursor(context)

    if add == 'add':
        xformsdata = {"schema": {"role": {"id": "", "description": ""}}}
    elif add == 'edit':
        currId = json.loads(session)['sessioncontext']['related'][
            'gridContext']['currentRecordId']
        #currId = json.loads(base64.b64decode(currIdEncoded))
        roles.get(currId)
        xformsdata = {
            "schema": {
                "role": {
                    "id": roles.id,
                    "description": roles.description,
                    "add": add
                }
            }
        }

    #print xformsdata
    xformssettings = {
        "properties": {
            "event": {
                "@name": "single_click",
                "@linkId": "1",
                "action": {
                    "#sorted": [{
                        "main_context": "current"
                    }, {
                        "datapanel": {
                            "@type": "current",
                            "@tab": "current",
                            "element": {
                                "@id": "id_roles_grid",
                                "add_context": ""
                            }
                        }
                    }]
                }
            }
        }
    }

    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xformsdata)),
                     XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))
Beispiel #6
0
def rolesCount(context,
               main=None,
               add=None,
               filterinfo=None,
               session=None,
               params=None,
               curvalue="",
               startswith=False):
    roles = RolesCursor(context)
    roles.setFilter(
        'description',
        "@%s'%s'%%" % ("%" * (not startswith), curvalue.replace("'", "''")))
    count = roles.count()
    # raise Exception(count)
    return ResultSelectorData(None, count)
def permissionsload(context,
                    main=None,
                    add=None,
                    filterinfo=None,
                    session=None,
                    elementId=None,
                    data=None):
    permissions = PermissionsCursor(context)
    roles = RolesCursor(context)
    rolesCustomPerms = rolesCustomPermsCursor(context)
    customPerms = customPermsCursor(context)
    customPermsTypes = customPermsTypesCursor(context)
    cursors = [
        roles, permissions, customPermsTypes, customPerms, rolesCustomPerms
    ]
    files = [
        'roles', 'permissions', 'customPermsTypes', 'customPerms',
        'rolesCustomPerms'
    ]

    for i in range(len(cursors)):
        filePath = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            files[i] + '.xml')
        # raise Exception(filePath)
        if add == 'upload':
            dataStream = FileOutputStream(filePath)
        elif add == 'download':
            dataStream = FileInputStream(filePath)
        exchange = DataBaseXMLExchange(dataStream, cursors[i])
        if add == 'upload':
            exchange.downloadXML()
        elif add == 'download':
            exchange.uploadXML()
        dataStream.close()
Beispiel #8
0
def rolesCount(context,
               main=None,
               add=None,
               filterinfo=None,
               session=None,
               params=None,
               curvalue=None,
               startswith=None):
    u'''Функция count для селектора выбора ролей. '''

    #specialRoles = ["!'editor'", "!'reader'"]
    roles = RolesCursor(context)
    roles.setFilter(
        'id', """!'editor'&!'reader'&@%s'%s'%%""" %
        ("%" * (not startswith), curvalue.replace("'", "''")))

    count = roles.count()

    return ResultSelectorData(None, count)
Beispiel #9
0
def cardDelete(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None):
    currentRecordId = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId']
    userRoles=UserrolesCursor(context)
    userRoles.setRange("roleid", currentRecordId)
    userRoles.deleteAll()
    rolesCustomPermissions=rolesCustomPermsCursor(context)
    rolesCustomPermissions.setRange("roleid", currentRecordId)
    rolesCustomPermissions.deleteAll()
    permissions=PermissionsCursor(context)
    permissions.setRange("roleid", currentRecordId)
    permissions.deleteAll()
    role = RolesCursor(context)
    role.get(currentRecordId)
    role.delete()
Beispiel #10
0
def cardData(context,
             main=None,
             add=None,
             filterinfo=None,
             session=None,
             elementId=None):
    u'''Функция данных для карточки редактирования содержимого таблицы ролей. '''

    settings = Settings()

    # ru.curs.showcase.security.SecurityParamsFactory.getAuthServerUrl()
    rolesUsers = UserrolesCursor(context)
    roles = RolesCursor(context)
    logins = loginsCursor(context)

    currId = json.loads(
        session)['sessioncontext']['related']['gridContext']['currentRecordId']
    if settings.isUseAuthServer() and settings.loginIsSubject():
        # В данном режиме в currId передаются имя пользователя и сид.
        # Сделано так, чтобы не лопатить огромный xml, приходящий из меллофона
        currId = json.loads(currId)
        if not logins.tryGet(currId[0]):
            # in "tt" regime we copy record from mellophone(AuthServer) to logins if it doesn't appear in logins.
            subjects = subjectsCursor(context)
            subjects.name = currId[0]
            subjects.sid = currId[1]
            subjects.insert()
            logins.userName = currId[0]
            logins.subjectId = currId[1]
            logins.password = ""
            logins.insert()
        rolesUsers.setRange("userid", logins.subjectId)
    elif settings.loginIsSubject():
        logins.get(currId)
        rolesUsers.setRange(
            "userid", logins.subjectId)  # роли всегда привязываются к сидам
    else:
        rolesUsers.setRange("userid", currId)
    content = []
    if rolesUsers.tryFindSet():
        while True:
            if roles.tryGet(rolesUsers.roleid):
                content.append({
                    "@id":
                    roles.id,
                    "@description":
                    '%s - %s' %
                    (roles.id, roles.description if roles.description else '')
                })
            if not rolesUsers.nextInSet():
                break

    if content == []:
        xformsdata = {"schema": {"roles": ""}}
    else:
        xformsdata = {"schema": {"roles": {"role": content}}}
        # сортировка
        xformsdata["schema"]["roles"]["role"].sort(
            key=lambda x: (x["@id"].lower()))

    # raise Exception(xformsdata)

    # print xformsdata
    xformssettings = {
        "properties": {
            "event": {
                "@name": "single_click",
                "@linkId": "1",
                "action": {
                    "#sorted": [{
                        "main_context": "current"
                    }, {
                        "datapanel": {
                            "@type": "current",
                            "@tab": "current",
                            "element": {
                                "@id": "usersGrid",
                                "add_context": ""
                            }
                        }
                    }]
                }
            }
        }
    }

    return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xformsdata)),
                     XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))
Beispiel #11
0
def rolesUpload(context, main=None, add=None, filterinfo=None, session=None, elementId=None, data=None, fileName=None, file=None):
    roles = RolesCursor(context)
    tableUpload(roles, file)
    return context.message(u"Данные успешно загружены в таблицу")
Beispiel #12
0
def rolesDownload(context, main=None, add=None, filterinfo=None, session=None, elementId=None, data=None):
    roles = RolesCursor(context)
    fileName = 'roles'
    return tableDownload(roles, fileName)
Beispiel #13
0
def gridData(context,
             main=None,
             add=None,
             filterinfo=None,
             session=None,
             elementId=None,
             sortColumnList=None,
             firstrecord=None,
             pagesize=None):
    u'''Функция получения данных для грида. '''

    # Создание экземпляра курсора разрешения
    roles = RolesCursor(context)
    rolesPermissions = rolesCustomPermsCursor(context)
    if 'currentRecordId' in session:
        currId = json.loads(session)['sessioncontext']['related'][
            'gridContext']['currentRecordId']
        rolesPermissions.setRange("permissionId", currId)

    roles.orderBy("id")
    # Определяем переменную для JSON данных

    data = {"records": {"rec": []}}
    _header = {
        "id": ["~~id"],
        "roleId": [u"Роль"],
        "description": [u"Описание"],
        "exists": [u" "],
        "properties": [u"properties"]
    }

    for column in _header:
        _header[column].append(toHexForXml(_header[column][0]))

    # Считываем параметры сортировки
    if sortColumnList:
        sortName = sortColumnList[0].id
        sortType = unicode(sortColumnList[0].sorting).lower()
    else:
        sortName = None
    # Проходим по таблице и заполняем data
    if roles.tryFindSet():
        while True:
            permDict = {}
            permDict[_header["id"][1]] = json.dumps({
                "permission": currId,
                "role": roles.id
            })
            permDict[_header["roleId"][1]] = roles.id
            permDict[_header["description"][1]] = roles.description
            rolesPermissions.setRange("roleid", roles.id)
            permDict[_header["exists"][1]] = rolesPermissions.count(
            ) > 0 if rolesPermissions.count() else ''
            permDict[_header["properties"][1]] = {
                "event": {
                    "@name": "row_single_click",
                    "action": {
                        "#sorted": [{
                            "main_context": 'current'
                        }, {
                            "datapanel": {
                                '@type': "current",
                                '@tab': "current"
                            }
                        }]
                    }
                }
            }

            data["records"]["rec"].append(permDict)
            if not roles.nextInSet():
                break

    for column in _header:
        if sortName == _header[column][0]:
            keyField = column if sortName else 'exists'
            data["records"]["rec"].sort(key=lambda x:
                                        (x[_header["%s" % keyField][1]]),
                                        reverse=(sortType == 'desc'))
            data["records"]["rec"] = data["records"]["rec"][firstrecord -
                                                            1:firstrecord - 1 +
                                                            pagesize]
    res = XMLJSONConverter.jsonToXml(json.dumps(data))
    return JythonDTO(res, None)
Beispiel #14
0
def gridMeta(context,
             main=None,
             add=None,
             filterinfo=None,
             session=None,
             elementId=None):
    u'''Функция получения настроек грида. '''

    roles = RolesCursor(context)
    # Вычисляем количества записей в таблице
    totalcount = roles.count()
    # Заголовок таблицы
    header = "Роли"

    _header = {
        "id": ["~~id"],
        "roleId": [u"Роль"],
        "description": [u"Описание"],
        "exists": [u" "],
        "properties": [u"properties"]
    }
    # Определяем список полей таблицы для отображения
    settings = {}
    currentDatapanelHeight = int(
        json.loads(session)["sessioncontext"]["currentDatapanelHeight"])
    # Вычисляем numberOfGrids, где 2.1 - numberOfGrids для первого грида customPermissions.py из датапанели
    # 60 - gridHeaderHeight для обоих гридов, 134 - суммарная дельта
    numberOfGrids = ((currentDatapanelHeight - 60) * 2.1) / (
        2.1 * currentDatapanelHeight - 2.1 * 134 - currentDatapanelHeight + 60)
    settings["gridsettings"] = {
        "columns": {
            "col": []
        },
        "properties": {
            "@pagesize": "50",
            "@gridWidth": "100%",
            "@gridHeight": getGridHeight(session, numberOfGrids, 60, 67),
            "@totalCount": totalcount,
            "@profile": "editableGrid.properties"
        },
        "labels": {
            "header": header
        }
    }
    # Добавляем поля для отображения в gridsettings
    settings["gridsettings"]["columns"]["col"].append({
        "@id":
        _header["exists"][0],
        "@width":
        "33px",
        "@readonly":
        "false",
        "@editor":
        "{editor: 'checkbox'}"
    })
    settings["gridsettings"]["columns"]["col"].append({
        "@id":
        _header["roleId"][0],
        "@width":
        "80px",
        "@readonly":
        "true"
    })
    settings["gridsettings"]["columns"]["col"].append({
        "@id":
        _header["description"][0],
        "@width":
        "400px",
        "@readonly":
        "true"
    })
    res = XMLJSONConverter.jsonToXml(json.dumps(settings))
    return JythonDTO(None, res)
Beispiel #15
0
def cardDataSave(context,
                 main=None,
                 add=None,
                 filterinfo=None,
                 session=None,
                 elementId=None,
                 xformsdata=None):
    u'''Функция сохранения карточки редактирования содержимого справочника ролей. '''
    roles = RolesCursor(context)

    #raise Exception(xformsdata)

    content = json.loads(xformsdata)["schema"]["role"]
    roles.id = content["id"]
    if content["description"] == '':
        roles.description = content["id"]
    else:
        roles.description = content["description"]

    if add == 'add' and roles.canInsert() and roles.canModify():
        if not roles.tryInsert():
            rolesOld = RolesCursor(context)
            rolesOld.get(content["id"])
            roles.recversion = rolesOld.recversion
            roles.update()
        rolesReadPermission(roles)
    elif add == 'add' and roles.canInsert():
        roles.insert()
        rolesReadPermission(roles)
    elif add == 'edit' and roles.canModify():
        rolesOld = RolesCursor(context)
        currId = json.loads(session)['sessioncontext']['related'][
            'gridContext']['currentRecordId']
        rolesOld.get(currId)
        if rolesOld.id == roles.id:
            roles.recversion = rolesOld.recversion
            roles.update()
            rolesReadPermission(roles)
        else:
            raise CelestaException(u"Недостаточно прав для данной операции!")
    else:
        raise CelestaException(u"Недостаточно прав для данной операции!")