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)
def drop_model(appname, modelname): """ offline api to offline data Request URL: /predata/offline Http Method: POST Parameters:{ "items":["123", "124"], "server":"local"} Return :{ "status":0 "data":{}} """ try: req_dict = ArmoryJson.decode(request.data) except: return json_response_error(PARAM_ERROR, msg="json format error") id_list = [] item_ids = req_dict.get("items") server = req_dict.get("server") try: id_list.extend(map(int, item_ids)) except: return json_response_error(PARAM_ERROR, msg="item ids format error") # view logic return offline(appname, modelname, id_list, server)
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)
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({})
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()
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()
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")
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)
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})
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)
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")
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")
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)
def savelog(appname): # check args if appname not in MONGO_CONFIG: _LOGGER.error('cant find appname') return json_response_error(PARAM_ERROR, msg="appname error, check url") try: data_obj = simplejson.loads(request.data) status = save_loginfo(data_obj) return json_response_ok(data={'status': status}, msg='response status') except ValueError as expt: _LOGGER.error("save log para except:%s", expt) return json_response_error( PARAM_ERROR, msg="json loads error,check parameters format")
def getlog(appname): # check args if appname not in MONGO_CONFIG: _LOGGER.error('cant find appname') return json_response_error(PARAM_ERROR, msg="appname error, check url") sort_dict = {} sort_strs = request.args.get('sort') if sort_strs: try: sort_dict = simplejson.loads(sort_strs) except ValueError, e: _LOGGER.error(e) return json_response_error(PARAM_ERROR, msg='sort string error')
def navigate_list(appname, uid): try: uid = int(uid) except ValueError as expt: _LOGGER.error("get navigate para except:%s", expt) return json_response_error( PARAM_ERROR, msg="uid error,check parameters format") cond = {"_id": uid} user_info = User.find_one_user(appname, cond, None) if not user_info: return json_response_error(PARAM_ERROR, msg="the user not exist") nav = init_navigate_list(appname, uid) data = {} data.setdefault("navigate", nav) return json_response_ok(data)
def user_login(appname, user_name, password, session): user_cond = {"user_name": user_name, "password": password} user_check = User.find_one_user(appname, user_cond, None) if not user_check: return json_response_error(AUTH_ERROR, {}, msg="username or password err") elif not user_check["is_active"]: return json_response_error(AUTH_ERROR, {}, msg="user is not active") else: session["uid"] = int(user_check["_id"]) uid = user_check["_id"] upt_dict = {"last_login": now_timestamp(), "total_login": user_check.get("total_login") + 1} User.update_user(appname, {"_id": uid}, upt_dict) # 业务相关拆分 # permissions = Permission.init_menu(uid) return json_response_ok({"uid": uid})
def check_required_params(request, params): if request.method == "GET": data = request.args elif request.method == "POST": try: data = ArmoryJson.decode(request.data) except ValueError as expt: _LOGGER.error("para except:%s", expt) return json_response_error( PARAM_ERROR, msg="json loads error,check parameters format") for key in params: if key not in data: return json_response_error(PARAM_REQUIRED, msg="no param:%s" % key) new_data = get_params(params, data) return new_data
def user_right_mod(appname, projectname, uid, data): """ this api is used to modify one group Request URL: /auth/user/{gid} HTTP Method:POST Parameters: { "perm_list":[1,2,3,4] "disable_list":[1,2,3,4] } Return : { "status":0 "data":{} } """ # check if user id in db cond = {"_id": uid} fields = {"_id": 0} user_info = User.find_one_user(appname, cond, fields) if not user_info: return json_response_error(PARAM_ERROR, msg="the user not exist") # check if right id in db right_list = [int(rid) for rid in data["perm_list"]] right_list = list(set(right_list)) 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) group_perm_ids = [] gids = user_info.get("group_id") for gid in gids: group_info = Group.find_one_group(appname, {"_id": gid}, None) if group_info: perm_ids = group_info.get("permission_list") group_perm_ids += perm_ids.get(projectname, []) if group_perm_ids: group_perm_ids = list(set(group_perm_ids)) # update user right info user_right_list = [] for rid in right_list: if rid not in group_perm_ids: user_right_list.append(rid) user_info["permission_list"][projectname] = user_right_list User.update_user(appname, cond, user_info) return json_response_ok({}, msg="update user right success")
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)
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)
def edit_icon_info(appname): if appname not in MONGO_CONFIG: return json_response_error(PARAM_ERROR, msg="appname error") args = check_id_params(request) if isinstance(args, Response): return args return icon_get(appname, args)
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")
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")
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)
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")
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)
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)
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)
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)