Exemplo n.º 1
0
def check_session(appname, module, opname, action, lc, uid):
    '''
    check user right
    '''
    rightids = []
    perm_names = ['%s-%s-%s' % (opname, module, action), ]
    for perm_name in perm_names:
        perm = Right.find_one_right(appname, {'perm_name': perm_name})
        if perm:
            if perm['_id'] not in rightids:
                rightids.append(perm['_id'])
    usr = User.find_one_user({'_id': uid})
    usrights = usr['permission_list']
    if not usr:
        return json_response_error(AUTH_ERROR)
    if usr['is_superuser']:
        return json_response_ok()
    usrgroup = usr['group_id']
    for group in usrgroup:
        group_info = Group.find_one_group({'_id': group})
        usrights.extend(group_info['permission_list'])
    for rightid in rightids:
        if rightid in usrights:
            return json_response_ok()
    return json_response_error(AUTH_ERROR)
Exemplo n.º 2
0
def right_mod(appname, rid, data):
    '''
        this api is used to modify one right
        Request URL: /auth/user/{uid}
        HTTP Method:POST
        Parameters:
            {
            "group_name":"xxx",
            "perm_list":[1,2,3,4]
            }
        Return :
        {
        "status":0
        "data":{}
        "msg":"modify successfully"
        }
        '''
    cond = {"_id": rid}
    if not App.find_one_app(appname, {"name": data["app_label"]}):
        return json_response_error(PARAM_ERROR, msg="the app label not exist")
    if not Module.find_one_module(appname, {"module_name": data["module"]}):
        return json_response_error(PARAM_ERROR, msg="the app module not exist")
    perm_name = '%s-%s-%s' % (
        data["app_label"], data["module"], data["action"])
    data["perm_name"] = perm_name
    Right.update_right(appname, cond, data)
    return json_response_ok()
Exemplo n.º 3
0
def right_create(
        appname, projectname, perm_module, perm_opname, perm_action='list',
        perm_type="module", perm_lc='all'):
    '''
    create api to add right.
    Parameters:
    {
    'perm_type': 'module',
    'perm_name': 'aospreset-aosrecommendshare-list',
    'perm_container': 'aospreset',
    'perm_lc': 'zh-cn'
    }
    '''
    perm_name = '%s-%s-%s' % (perm_opname, perm_module, perm_action)
    right_cond = {
        'perm_name': perm_name, 'app_name': projectname, "lc": perm_lc}
    if Right.find_one_right(appname, right_cond):
        return json_response_error(PARAM_ERROR, msg="the right exist")
    if not App.find_one_app(appname, {"name": perm_opname}):
        return json_response_error(PARAM_ERROR, msg="the app label not exist")
    if not Module.find_one_module(appname, {"module_name": perm_module}):
        return json_response_error(
            PARAM_ERROR, msg="the app module not exist")
    right_instance = Right.new(
        appname, projectname, perm_module, perm_opname, perm_action,
        perm_type, perm_lc)
    Right.save(appname, right_instance)
    return json_response_ok()
Exemplo n.º 4
0
def common_create(appname, modelname, temp_dict):
    Model_Name = classing_model(modelname)
    try:
        temp_dict = CommonBase.clean_data(modelname, temp_dict)
    except ParamError as e:
        return json_response_error(PARAM_ERROR, msg=e.msg)
    # when save data, filter some useless data
    pop_list = [
        'id', 'last_release_ec2', 'last_release_local', 'release',
        'is_upload_local', 'is_upload_ec2']
    for key in pop_list:
        temp_dict.pop(key, None)
    if hasattr(Model_Name, "fields_check"):
        try:
            temp_dict = get_valid_params(temp_dict, Model_Name.fields_check)
        except ParamError as e:
            return json_response_error(PARAM_ERROR, msg=e.msg)
    temp_dict['first_created'] = temp_dict['last_modified'] = now_timestamp()

    #this is a factory function, to check some save data before insert if need
    (check_success, msg) = check_save_dict(appname, modelname, temp_dict)
    if not check_success:
        return json_response_error(PARAM_ERROR, msg=msg)
    insert_id = Model_Name.insert(appname, temp_dict)

    temp_dict['id'] = insert_id
    # if the model has ref icon and rule, increase the reference
    inc_icon(appname, modelname, temp_dict)
    inc_rule(appname, modelname, temp_dict)
    return json_response_ok(temp_dict)
Exemplo n.º 5
0
def group_right_get(appname, projectname, gid):
    '''
        this api is used to get group perm list
        Request URL: /auth/user/{uid}
        HTTP Method:POST
        Parameters:None
        Return :
        {
        "status":0
        "data":{
            "perm_list":[1,2,3,4],
            "id": 1
            }
        "msg":""
        }
        '''
    cond = {"_id": gid}
    group_info = Group.find_one_group(appname, cond, None)
    if not group_info:
        return json_response_error(
            PARAM_ERROR, msg="the group not exist")
    right_ids = group_info.get("permission_list")
    right_ids = right_ids.get(projectname, [])
    rights = {}
    rights.setdefault("perm_list", right_ids)
    rights.setdefault("id", gid)
    return json_response_ok(rights)
Exemplo n.º 6
0
def common_update(appname, modelname, temp_dict, item_id):
    Model_Name = classing_model(modelname)
    temp_dict.pop("id", 0)
    try:
        temp_dict = CommonBase.clean_data(modelname, temp_dict)
    except ParamError as e:
        return json_response_error(PARAM_ERROR, msg=e.msg)
    if hasattr(Model_Name, "fields_check"):
        try:
            temp_dict = get_valid_params(temp_dict, Model_Name.fields_check)
        except ParamError as e:
            return json_response_error(PARAM_ERROR, msg=e.msg)
    cond = {"id": int(item_id)}
    temp_dict['last_modified'] = now_timestamp()
    # if the model has release field
    if check_release(modelname):
        temp_dict['release'] = UploadStatus.UNUPLOAD_LOCAL
    # find the old item before update, aim to track icon and rule
    old_item = Model_Name.find_one(appname, {'id': item_id}, {'_id': 0})

    #this is a factory function, to check some save data before save if need
    (check_success, msg) = check_save_dict(
        appname, modelname, temp_dict, item_id)
    if not check_success:
        return json_response_error(PARAM_ERROR, msg=msg)

    Model_Name.update(appname, cond, temp_dict)
    temp_dict['id'] = item_id
    # if model has refered icon and rule
    mod_icon(appname, modelname, temp_dict, old_item)
    mod_rule(appname, modelname, temp_dict, old_item)
    return json_response_ok(temp_dict)
Exemplo n.º 7
0
def common_check_unique(appname, modelname, temp_dict):
    Model_Name = classing_model(modelname)
    method = temp_dict.pop('method', None)
    temp_dict.pop('original_value', None)
    item_id = temp_dict.pop('id', 0)
    # when pop method and id, only "unique_key": "value" left
    name = temp_dict.keys()[0]
    value = temp_dict.get(name)
    unique_pass = False
    if hasattr(Model_Name, "unique"):
        unique_list = Model_Name.unique
        if name not in unique_list:
            return json_response_error(PARAM_ERROR, msg="%s not exist" % name)
        if method == 'add':
            if not Model_Name.find_one(appname, temp_dict):
                unique_pass = True
        elif method == 'update':
            old_item = Model_Name.find_one(appname, {'id': int(item_id)})
            if not Model_Name.find_one(appname, temp_dict):
                unique_pass = True
            else:
                old_val = old_item.get(name)
                # when update if old title not change
                unique_pass = True if old_val == value else False
        else:
            return json_response_error(PARAM_ERROR, msg="method is not apply")
    else:
        unique_pass = True
    return json_response_ok({"unique": unique_pass})
Exemplo n.º 8
0
def module_delete(appname, mid):
    '''
    this api is used to delete app
    Request URL: /auth/app/delete
    HTTP Method: POST
    Parameters:
        {
            "aids":3
        }
    Return:
     {
     "status":0
     "data":{}
     "msg":"delete successfully"
     }
    '''
    mid = int(mid)
    module_info = Module.find_one_module(appname, {"_id": mid}, None)
    data = {"id": mid}
    if module_info:
        Module.del_module(appname, mid)
        return json_response_ok(data, msg="delete app success")
    else:
        _LOGGER.info("module id %s is not exist" % mid)
        return json_response_error(
            PARAM_ERROR, data, msg="invalid module id,check parameters")
Exemplo n.º 9
0
def group_get(appname, gid):
    '''
        this api is used to view one group
        Request URL: /auth/user/{gid}
        HTTP Method:GET
        Return:
            Parameters: None
            {
                "status":0
                "data":{
                "item":[
                    {
                        "id":"2",
                        "role":"admin",
                        "last_login":"******"
                    }
            }
    '''
    group_info = Group.find_one_group(appname, {"_id": gid})
    if not group_info:
        return json_response_error(PARAM_ERROR, msg="the group not exist")
    group_info = user_info(appname, gid)
    data = {}
    data.setdefault("items", group_info)
    return json_response_ok(data)
Exemplo n.º 10
0
def user_delete(appname, uid):
    """
        this api is used to delete user.

        Request URL: /auth/user/delete

        HTTP Method: POST

        Parameters:
            {
                "uids": 3
            }

        Return:
        {
        "status":0
        "data":{}
        "msg":"delete successfully"
        }
    """
    uid = int(uid)
    user = User.find_one_user(appname, {"_id": uid}, None)
    if user:
        User.del_user(appname, uid)
        return json_response_ok({"id": uid}, msg="delete user success")
    else:
        return json_response_error(PARAM_ERROR, msg="id:%s is invalid" % uid)
Exemplo n.º 11
0
def del_from_admin(appname, icon_ids):
    data = {"success": [], "failed": []}
    for icon_id in icon_ids:
        icon_id = int(icon_id) if not isinstance(icon_id, int) else icon_id
        cond = {"_id": icon_id}
        icon = Icon.find_one(appname, cond, None)
        if not icon:
            _LOGGER.info("icon id %s is not exist" % icon_id)
            continue
        if icon["refered_info"]:
            _LOGGER.info("icon id %s is refer" % icon_id)
            refer_info = {"id":  icon_id, "refered_info": []}
            refer_info["refered_info"] = icon["refered_info"]
            data["failed"].append(refer_info)
        else:
            # remove from database
            Icon.remove(appname, cond)
            # remove from filesystem 
            remove_icon_file(appname, icon["icon"])
            data["success"].append({"id": icon_id})
    if data["failed"]:
        return json_response_error(
            DATA_RELETED_BY_OTHER, data, msg="releted by other")
    else:
        return json_response_ok(data)
Exemplo n.º 12
0
def user_get(appname, user_id):
    """
        this api is used to view one group
        Request URL: /auth/user/{gid}
        HTTP Method:GET
        Return:
            Parameters: None
            {
                "status":0
                "data":{
                    "item":[
                    {
                        "id":"2",
                        "role":"admin",
                        "last_login": "******"
                    }
            }
    """
    fields = {"group_id": 1, "_id": 1, "user_name": 1, "mark": 1}
    user_info = User.find_one_user(appname, {"_id": user_id}, fields)
    if user_info:
        user_info["id"] = user_info["_id"]
        _LOGGER.info(user_info)
        return json_response_ok(user_info)
    else:
        return json_response_error(PARAM_ERROR, msg="not user:%s" % user_id)
Exemplo n.º 13
0
def user_mod(appname, uid, data):
    """
        this api is used to modify one user
        Request URL: /auth/user/{uid}
        HTTP Method:POST
        Parameters: None
        Return :
        {
        "status":0
        "data":{
            "perm_list":[1,2,3,4],
            "disable_list":[1,2,3,4],
            "id": 1
            }
        "msg":""
        }
        """
    cond = {"_id": uid}
    user = User.find_one_user(appname, cond, None)
    if not user:
        return json_response_error(PARAM_ERROR, msg="id:%s is invalid" % uid)
    user_name = data["user_name"]
    old_user = Group.find_one_group(appname, {"user_name": user_name})
    if old_user and old_user["_id"] != uid:
        return json_response_error(PARAM_ERROR, msg="the user name exist")
    group_id = [int(gid) for gid in data["group_id"]]
    user_data = {"user_name": user_name, "mark": data["mark"], "group_id": group_id}
    User.update_user(appname, cond, user_data)
    return json_response_ok({})
Exemplo n.º 14
0
def group_delete(appname, gid):
    '''
    this api is used to delete group,when one group removed,the user who
    in this group ,the group id will remove too.
    Request URL: /auth/group/delete
    HTTP Method: POST
    Parameters:
        {
            "gids":3
        }
    Return:
     {
     "status":0
     "data":{}
     "msg":"delete successfully"
     }
    '''
    gid = int(gid)
    group = Group.find_one_group(appname, {"_id": gid}, None)
    data = {"id": gid}
    if group:
        users = user_info(appname, int(gid))
        if users:
            _LOGGER.info("group id %s is refer" % gid)
            return json_response_error(DATA_RELETED_BY_OTHER, data)
        else:
            Group.del_group(appname, gid)
            return json_response_ok(data, msg="delete group success")
    else:
        _LOGGER.info("group id %s is not exist" % gid)
        return json_response_error(
            PARAM_ERROR, data, msg="invalid group id,check parameters")
Exemplo n.º 15
0
def app_delete(appname, aid):
    '''
    this api is used to delete app
    Request URL: /auth/app/delete
    HTTP Method: POST
    Parameters:
        {
            "aids":3
        }
    Return:
     {
     "status":0
     "data":{}
     "msg":"delete successfully"
     }
    '''
    aid = int(aid)
    app_info = App.find_one_app(appname, {"_id": aid}, None)
    data = {"id": aid}
    if app_info:
        App.del_app(appname, aid)
        return json_response_ok(data, msg="delete app success")
    else:
        _LOGGER.info("app id %s is not exist" % aid)
        return json_response_error(
            PARAM_ERROR, data, msg="invalid app id,check parameters")
Exemplo n.º 16
0
def offline(appname, modelname, item_ids, server):
    Model_Class = classing_model(modelname)
    items = Model_Class.find(
        appname, {'id': {'$in': item_ids}}, fields={'_id': 0}, toarray=True)
    if not items:
        return json_response_error(PARAM_ERROR, msg="no item find")
    results = offline_data(appname, modelname, server, items)
    status = results[0]
    data = {}
    data["success"] = results[1]
    data["failed"] = results[2]
    data['userlog'] = [common_filter(i) for i in data.get('success')]
    data['memo'] = 'offline from %s' % server
    if status == -1:
        return json_response_error(PARAM_ERROR, msg="UNKNOWN UPLOAD SERVER")
    elif status == 0:
        if server == _ADMIN:
            data['success_list'] = data.get('success')
            data['failed_list'] = data.get('failed')
            suc_ids = fail_ids = []
            if data["failed"]:
                fail_ids = [i.get('id') for i in data.get('failed')]
            if data["success"]:
                suc_ids = [i.get('id') for i in data.get('success')]
            data["success"] = suc_ids
            data["failed"] = fail_ids
            data['memo'] = 'delete it from admin'
        return json_response_ok(data, msg="delete successfully")
    else:
        return json_response_error(status, data, msg="del error")
Exemplo n.º 17
0
def group_right_mod(appname, projectname, gid, data):
    '''
        this api is used to modify one group
        Request URL: /auth/user/{gid}
        HTTP Method:POST
        Parameters:
        {
           "perm_list":[1,2,3,4]
        }
        Return :
        {
            "status":0
            "data":{}
        }
        '''
    # check if group id in db
    cond = {"_id": gid}
    fields = {"_id": 0}
    group_info = Group.find_one_group(appname, cond, fields)
    if not group_info:
        return json_response_error(PARAM_ERROR, msg="the group not exist")

    right_list = [int(rid) for rid in data["perm_list"]]
    right_list = list(set(right_list))

    # check if right id in db
    for rid in right_list:
        if not Right.find_one_right(appname, {"_id": rid}):
            return json_response_error(
                PARAM_ERROR, msg="the right id:%s not exist" % rid)

    # update group right info
    group_info["permission_list"][projectname] = right_list
    Group.update_group(appname, cond, group_info)
    return json_response_ok({}, msg="update group right success")
Exemplo n.º 18
0
def group_name_mod(appname, gid, data):
    '''
        this api is used to modify one group
        Request URL: /auth/user/{gid}
        HTTP Method:POST
        Parameters:
        {
           "group_name":"xxx",
        }
        Return :
        {
            "status":0
            "data":{}
        }
        '''
    group_name = data["group_name"]
    old_group = Group.find_one_group(appname, {"group_name": group_name})
    if old_group and old_group["_id"] != gid:
        return json_response_error(
            PARAM_ERROR, msg="the groupname exist")
    cond = {"_id": gid}
    Group.update_group(appname, cond, data)
    group_info = Group.find_one_group(
        appname, cond, {"_id": 1, "group_name": 1})
    group_info["id"] = group_info["_id"]
    return json_response_ok(group_info)
Exemplo n.º 19
0
def group_create(appname, group_name, perm_list={}):
    '''
    create api to add group.
    Request URL:  /auth/group/add
    Http Method:  POST
    Parameters:
        {
           "group_name":"xxx",
           "perm_list":{}
        }
    Return :
    {
     "status":0
     "data":{}
    }
    '''
    if Group.find_one_group(appname, {"group_name": group_name}):
        return json_response_error(
            PARAM_ERROR, msg="the groupname exist")
    group_instance = Group.new(group_name, perm_list)
    Group.save(appname, group_instance)
    cond = {"group_name": group_name}
    group_info = Group.find_one_group(
        appname, cond, {"_id": 1, "group_name": 1})
    group_info["id"] = group_info["_id"]
    return json_response_ok(group_info)
Exemplo n.º 20
0
def delete_rule_info(appname, rule_ids):
    data = {"success": [], "failed": []}
    for rule_id in rule_ids:
        try:
            rule_id = int(rule_id) if not isinstance(rule_id, int) else rule_id
        except:
            _LOGGER.error("id:%s type error", rule_id)
            continue

        cond = {"_id": rule_id}
        rule = Rule.find_one(appname, cond, None)
        if not rule:
            _LOGGER.error("rule id %s is not exist", rule_id)
            continue
        refer_cond = {"target_id": int(rule_id), "target_field": "rule"}
        refer_rule = ReferInfo.find_one_refered_info(
            appname, refer_cond, None)
        if refer_rule:
            _LOGGER.info("rule id %s is refer", rule_id)
            refer_info = {"id": rule_id}
            refer_info["refered_info"] = refer_rule["refered_info"]
            data["failed"].append(refer_info)
        else:
            Rule.remove(appname, cond)
            data["success"].append({"id": rule_id})

    if data["failed"]:
        return json_response_error(DATA_RELETED_BY_OTHER, data)
    else:
        return json_response_ok(data, msg="delete successfully")
Exemplo n.º 21
0
def info_del(appname, modelName, ids):
    MODELNAME = get_model_cls(modelName)
    data = {"success": [], "failed": []}
    for id in ids:
        try:
            id = int(id) if not isinstance(id, int) else id
        except:
            _LOGGER.info("id:%s type error", id)
            continue
        cond = {"_id": id}
        info = MODELNAME.find_one(appname, cond, None)
        if not info:
            _LOGGER.info("id %s is not exist", id)
            continue
        refer_cond = {}
        refer_cond[modelName] = id
        refer_rule = Rule.find(appname, refer_cond, toarray=True)
        if refer_rule:
                _LOGGER.info("id %s is refered", id)
                refer_info = {"id": id, "refered_info": []}
                for item in refer_rule:
                    temp_dict = {"modelName": "rule"}
                    temp_dict["id"] = item.get("_id")
                    refer_info["refered_info"].append(temp_dict)
                data["failed"].append(refer_info)
        else:
            MODELNAME.remove(appname, cond)
            data["success"].append({"id": id})

    if data["failed"]:
        return json_response_error(DATA_RELETED_BY_OTHER, data)
    else:
        return json_response_ok(data, msg="delete successfully")
Exemplo n.º 22
0
def info_get(appname, modelName, cond):
    MODELNAME = get_model_cls(modelName)
    info = MODELNAME.find_one(appname, cond, MODELNAME.fields)
    if not info:
        return json_response_error(PARAM_ERROR, msg="invalid param id")
    info["id"] = info.pop("_id")
    return json_response_ok(info)
Exemplo n.º 23
0
def create_icon(appname, data):
    for key in Icon.params:
        if not data.get(key):
            return json_response_error(PARAM_REQUIRED, msg="no param:%s" % key)

    # if not check_ospn_params(appname, data):
    #     return json_response_error(
    #         PARAM_ERROR, msg="param:platform or package error")

    data["title"] = "%s_%s" % (data["title"], now_timestamp())
    icon_info = Icon.find_one(appname, {"title": data["title"]})
    if icon_info:
        return json_response_error(
            DUPLICATE_FIELD, msg="the icon title exist")

    # save icon file to local file system
    data["icon"], data["height"], data["width"] = save_icon_file(
        data["icon"], appname)
    data["icon"] = _ICON_BASE_DIR + appname + '/' + data["icon"]

    # upload icon to file server
    file_path = os.path.join(MEDIA_ROOT, data["icon"])
    file_transfer = FileTransfer(file_path)
    data["guid"], data["download_url"] = file_transfer.start()

    # insert icon dict to database 
    icon_instance = Icon.new(data)
    Icon.save(appname, icon_instance)
    _LOGGER.info("add a new icon:%s", data["title"])

    icon_info = Icon.find_one(appname, {"title": data["title"]}, None)
    icon_info["id"] = icon_info.pop("_id")
    return json_response_ok(icon_info)
Exemplo n.º 24
0
def app_mod(appname, aid, data):
    name = data["name"]
    old_app = App.find_one_app(appname, {"name": name, "app_name": appname})
    if old_app and old_app["_id"] != aid:
        return json_response_error(PARAM_ERROR, msg="the appname exist")
    cond = {"_id": aid}
    App.update_app(appname, cond, data)
    return json_response_ok()
Exemplo n.º 25
0
def icon_get(appname, iconid):
    cond = {"_id": iconid}
    icon = Icon.find_one(appname, cond, Icon.fields)
    if not icon:
        return json_response_error(PARAM_ERROR, msg='%s not in db' % (iconid))
    icon["id"] = icon.pop("_id")
    icon["last_modified"] = unixto_string(icon.get("last_modified"))
    return json_response_ok(icon)
Exemplo n.º 26
0
def right_delete(appname, pids):
    '''
    delete right
    '''
    pidlist = pids.split(',')
    ids = Right.del_right(appname, pidlist)
    if not ids:
        return json_response_ok()
    else:
        return json_response_error(PARAM_ERROR, msg="ids:%s is invalid" % ids)
Exemplo n.º 27
0
def module_mod(appname, mid, data):
    module_name = data["module_name"]
    app_name = data["app_name"]
    old_module = Module.find_one_module(
        appname, {"module_name": module_name, "app_name": app_name})
    if old_module and old_module["_id"] != mid:
        return json_response_error(PARAM_ERROR, msg="the appname exist")
    cond = {"_id": mid}
    Module.update_module(appname, cond, data)
    return json_response_ok()
Exemplo n.º 28
0
def user_chpasswd(appname, uid, old_pwd, new_pwd):
    usr = User.find_one_user(appname, {"_id": int(uid)}, None)
    if usr:
        if usr.get("password") == old_pwd:
            User.update_user(appname, {"_id": int(uid)}, {"password": new_pwd})
            return json_response_ok()
        else:
            _LOGGER.error("old_pwd err")
            return json_response_error(AUTH_ERROR)
    else:
        return json_response_error(AUTH_ERROR)
Exemplo n.º 29
0
def get_package_display_data(appname):
    display_data = {}
    sort = [("last_modified", -1)]
    display_cursor = ArmoryMongo[appname]["platform"].find({}).sort(sort)
    display_list = []
    for item in display_cursor:
        item_dict = {}
        item_dict["display_value"] = item.get("title")
        item_dict["value"] = item.get("_id")
        display_list.append(item_dict)
    display_data["platform"] = display_list
    return json_response_ok(display_data, msg="")
Exemplo n.º 30
0
def module_list(appname):
    sort = [("order", 1), ("_id", 1)]
    module_cursor = Module.find_module(appname, {}, fields=None).sort(sort)
    total = Module.find_module(appname, {}).count()
    modules = []
    for item in module_cursor:
        item["id"] = item.pop("_id")
        modules.append(item)
    data = {}
    data.setdefault("items", modules)
    data.setdefault("total", total)
    return json_response_ok(data)