def createEnterprise(): if request.method == 'POST': api_response = { "code": 0, "msg": "success" } try: currResource = Resource.query.filter(Resource.perms == "modules:enterprise:save").first() if currResource==None: api_response["code"] = 401 api_response["msg"] = "当前操作权限实体不存在" return jsonify(api_response), 401 very = very_permission(currResource.id) if very == False: api_response["code"] = 401 api_response["msg"] = "该账户无操作权限" return jsonify(api_response), 401 else: request_json = request.get_json() # if 'etpCode' not in request_json or request_json['etpCode'] is "": # raise ValidationError("参数不能为空") # etpCode = request_json['etpCode'] if 'etpName' not in request_json or request_json['etpName'] is "": raise ValidationError("参数不能为空") etpName = request_json['etpName'] if 'LDAPCode' not in request_json or request_json['LDAPCode'] is "": raise ValidationError("参数不能为空") LDAPCode = request_json['LDAPCode'] etpCode = LDAPCode + "_" + str(int(time.time() * 10)) if 'serverInfolist' not in request_json or request_json['serverInfolist'] is "": raise ValidationError("参数不能为空") serverInfolist = request_json['serverInfolist'] dhcpServerIP = (request_json['dhcpServerIP'] if ('dhcpServerIP' in request_json) else "") TFTPServerIP = (request_json['TFTPServerIP'] if ('TFTPServerIP' in request_json) else "") FTPServerIP = (request_json['FTPServerIP'] if ('FTPServerIP' in request_json) else "") createAdmin = g.user createTime = (request_json['createTime'] if ('createTime' in request_json) else datetime.now()) newenterprise = Enterprise(etpCode, etpName, LDAPCode, dhcpServerIP, TFTPServerIP, FTPServerIP, createAdmin, createTime) db.session.add(newenterprise) for serverinfo in serverInfolist: if 'serverType' not in serverinfo or serverinfo['serverType'] is "": raise ValidationError("参数不能为空") serverType = serverinfo['serverType'] serverIP = (serverinfo['serverIP'] if ('serverIP' in serverinfo) else "") serverUsername = (serverinfo['serverUsername'] if ('serverUsername' in serverinfo) else "") serverPasswd = (serverinfo['serverPasswd'] if ('serverPasswd' in serverinfo) else "") newServer = Server(etpCode, serverType, serverIP, serverUsername, serverPasswd) db.session.add(newServer) try: db.session.commit() except Exception as ie: Logger('error.log', level='error').logger.error("[事务提交失败]accName:【%s】%s" % (g.user, ie)) db.session.rollback() api_response["result"] = etpCode return jsonify(api_response) except Exception as e: Logger('error.log', level='error').logger.error("[添加企业异常]accName:【%s】%s" % (g.user, e)) api_response["code"] = 500 api_response["msg"] = "服务器未知错误" return jsonify(api_response),500
def login(): if request.method == 'POST': api_response = {"code": 0, "msg": "success"} request_json = request.get_json() if 'accName' not in request_json or request_json['accName'] is "": raise ValidationError("参数不能为空") accName = request_json['accName'] if 'password' not in request_json or request_json['password'] is "": raise ValidationError("参数不能为空") password = request_json['password'] try: user = User.query.filter(User.accName == accName).first() if user == None: api_response["code"] = 401 api_response["msg"] = "用户不存在" return jsonify(api_response), 401 very = user.very_password(password) if very == False: api_response["code"] = 401 api_response["msg"] = "账号或密码不正确" return jsonify(api_response), 401 elif user.status == 0: api_response["code"] = 401 api_response["msg"] = "账号已被封禁,请联系管理员" return jsonify(api_response), 401 else: last_login = Last_Online.query.filter( Last_Online.accName == accName).first() if last_login is None: new_last_login = Last_Online(accName, user.userName, datetime.now(), 1) db.session.add(new_last_login) else: last_login.last_login_time = datetime.now() last_login.login_count = last_login.login_count + 1 try: db.session.commit() except Exception as ie: Logger('error.log', level='error').logger.error( "[事务提交失败]accName:【%s】%s" % (accName, ie)) db.session.rollback() token = bytes.decode(user.generate_auth_token(2592000)) api_response['expire'] = 3600 api_response['token'] = token return jsonify(api_response) except Exception as e: Logger('error.log', level='error').logger.error( "[登录异常]accName:【%s】%s" % (accName, e)) api_response["code"] = 500 api_response["msg"] = "服务器未知错误" return jsonify(api_response), 500
def on_patch(self, req: falcon.Request, resp: falcon.Response, store_id: str, project_id: str, asset_id: str): validate_not_null(req.media, 'action') validate_not_null(req.media, 'data') validate_list(req.media.get('data')) action = req.media.get('action') data = req.media.get('data') if action not in ['add', 'remove']: raise ValidationError( title="Invalid action provided", description="The action should be either add or remove") meta = self._controller.get_asset_meta(store_id=store_id, project_id=project_id, asset_id=asset_id) new_tags = set(meta.tags) if action == 'add': new_tags.update(data) elif action == 'remove': new_tags.difference_update(data) meta.tags = list(new_tags) self._controller.edit_asset_meta(store_id=store_id, project_id=project_id, asset_id=asset_id, meta=meta) resp.media = meta.tags resp.status = falcon.HTTP_200
def on_get(self, req: falcon.Request, resp: falcon.Response, store_id: str, project_id: str, object_id: str): default_object = OBJECT_TEMPLATE.get(object_id, {}) resp.context = { "store_id": store_id, "project_id": project_id, "object_id": object_id, "object": default_object, "create": False } objects = self._controller.check_objects(store_id=store_id, project_id=project_id, object_ids=[object_id], auth_token=auth_token(req)) if len(objects) > 0: resp.context['file_url'] = objects[0]['index_file'] try: resp.context["object"] = self._controller.get_object( store_id=store_id, project_id=project_id, object_id=object_id, auth_token=auth_token(req)) resp.context["create"] = False except: resp.context["create"] = True resp.context["object"] = default_object raise ValidationError( title="Not found", description="This project does not have a '{}.json' object". format(object_id))
def editUserPermission(): if request.method == 'POST': api_response = {"code": 0, "msg": "success"} try: currResource = Resource.query.filter( Resource.perms == "modules:usermanage:update").first() if currResource == None: api_response["code"] = 401 api_response["msg"] = "当前操作权限实体不存在" return jsonify(api_response), 401 very = very_permission(currResource.id) if very == False: api_response["code"] = 401 api_response["msg"] = "该账户无操作权限" return jsonify(api_response), 401 else: request_json = request.get_json() if 'accName' not in request_json or request_json[ 'accName'] is "": raise ValidationError("参数不能为空") accName = request_json['accName'] if 'accType' not in request_json or request_json[ 'accType'] is "": raise ValidationError("参数不能为空") accType = request_json['accType'] user = User.query.filter(User.accName == accName).first() if user == None: api_response["code"] = 400 api_response["msg"] = "所修改账户不存在" return jsonify(api_response), 400 user.role_id = accType try: db.session.commit() except Exception as ie: Logger('error.log', level='error').logger.error( "[事务提交失败]accName:【%s】%s" % (accName, ie)) db.session.rollback() return jsonify(api_response) except Exception as e: Logger('error.log', level='error').logger.error( "[修改角色异常]accName:【%s】%s" % (accName, e)) api_response["code"] = 500 api_response["msg"] = "服务器未知错误" return jsonify(api_response), 500
def create_project(self, project_id: str, store_id: str = None) -> None: client = self._get_connection(store_id) try: client.make_bucket(project_id, location=_DEFAULT_STORE_LOCATION) except ResponseError: logging.error("Error while trying to create project. Error: %s", sys.exc_info()[1]) raise ValidationError( "Unable to create project on remote storage. Please check the project name." )
def on_post(self, req: falcon.Request, resp: falcon.Response): validate_not_null(req.params, 'user') validate_not_null(req.params, 'password') token = self._controller.login(user=req.params.get("user", None), password=req.params.get( "password", None)) if token: resp.set_cookie(FIELD_AUTH_TOKEN, token) raise falcon.HTTPSeeOther("/") else: raise ValidationError(title="Invalid login", description="Invalid username or password")
def to_bool(value): """ Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle. Case is ignored for strings. These string values are handled: True: 'True', "1", "TRue", "yes", "y", "t" False: "", "0", "faLse", "no", "n", "f" Non-string values are passed to bool. """ if isinstance(value, str): if value.lower() in ("yes", "y", "true", "t", "1"): return True if value.lower() in ("no", "n", "false", "f", "0", ""): return False raise ValidationError(description='Invalid value for boolean conversion: ' + value) return bool(value)
def upload_asset(self, project_id: str, asset_id: str, filename: str, upload_filename: str, store_id: str = None) -> None: client = self._get_connection(store_id) try: # filesize=os.stat(upfile.name).st_size filepath = asset_id + S3_SEPARATOR + filename client.fput_object(project_id, filepath, upload_filename) except ResponseError: logging.error("Error while trying to upload. Error: %s", sys.exc_info()[1]) raise ValidationError("Unable to upload asset to remote storage.")
def on_patch(self, req: falcon.Request, resp: falcon.Response): _validate_is_admin(req) validate_not_null(req.media, 'user') data = self._auth.get_user(user=req.media.get("user")) if not data: raise ValidationError(title="Invalid user", description="User not found") for field in UserAccessMeta.EDITABLE_FIELDS: if req.media.get(field, None): setattr(data, field, req.media.get(field)) self._auth.edit_user(access=data) resp.media = {"result": "OK"} resp.status = falcon.HTTP_200
def create_asset(self, project_id: str, meta: OveAssetMeta, store_id: str = None) -> OveAssetMeta: client = self._get_connection(store_id) meta.proxy_url = self._get_proxy_url(store_id) try: # minio interprets the slash as a directory meta_name = meta.id + S3_SEPARATOR + OVE_META data, size = _encode_json(meta.to_json()) client.put_object(project_id, meta_name, data, size) meta.created() self.set_asset_meta(store_id=store_id, project_id=project_id, asset_id=meta.id, meta=meta) return meta except ResponseError: logging.error("Error while trying to create asset. Error: %s", sys.exc_info()[1]) raise ValidationError( "Unable to create asset on remote storage. Please check the asset name." )
def editEnterprise(): if request.method == 'POST': api_response = { "code": 0, "msg": "success" } try: currResource = Resource.query.filter(Resource.perms == "modules:enterprise:update").first() if currResource==None: api_response["code"] = 401 api_response["msg"] = "当前操作权限实体不存在" return jsonify(api_response), 401 very = very_permission(currResource.id) if very == False: api_response["code"] = 401 api_response["msg"] = "该账户无操作权限" return jsonify(api_response), 401 else: request_json = request.get_json() if 'etpCode' not in request_json or request_json['etpCode'] is "": raise ValidationError("参数不能为空") etpCode = request_json['etpCode'] enterprise = Enterprise.query.filter(Enterprise.etpCode == etpCode).first() if enterprise == None: api_response["code"] = 400 api_response["msg"] = "该组织机构不存在" return jsonify(api_response), 400 updateTime = (request_json['updateTime'] if ('updateTime' in request_json) else datetime.now()) enterprise.updateTime = updateTime if ('dhcpServerIP' in request_json): enterprise.dhcpServerIP = request_json['dhcpServerIP'] if ('TFTPServerIP' in request_json): enterprise.TFTPServerIP = request_json['TFTPServerIP'] if ('FTPServerIP' in request_json): enterprise.FTPServerIP = request_json['FTPServerIP'] if ('serverInfolist' in request_json): serverInfoList = request_json['serverInfolist'] for server in serverInfoList: serverType = (server['serverType'] if ('serverType' in server) else "") serverInfo = Server.query.filter(Server.etpCode == etpCode,Server.serverType == serverType).first() if serverInfo==None: api_response["code"] = 400 api_response["msg"] = "该服务器信息不存在" return jsonify(api_response), 400 if ('serverIP' in server): serverInfo.serverIP = server['serverIP'] if ('serverUsername' in server): serverInfo.serverUsername = server['serverUsername'] if ('serverPasswd' in server): serverInfo.serverPasswd = server['serverPasswd'] try: db.session.commit() except Exception as ie: Logger('error.log', level='error').logger.error("[事务提交失败]accName:【%s】%s" % (g.user, ie)) db.session.rollback() api_response["result"] = etpCode return jsonify(api_response) except Exception as e: Logger('error.log', level='error').logger.error("[修改企业信息异常]accName:【%s】%s" % (g.user, e)) api_response["code"] = 500 api_response["msg"] = "服务器未知错误" return jsonify(api_response)
def editUser(): if request.method == 'POST': api_response = {"code": 0, "msg": "success"} try: currResource = Resource.query.filter( Resource.perms == "modules:usermanage:update").first() if currResource == None: api_response["code"] = 401 api_response["msg"] = "当前操作权限实体不存在" return jsonify(api_response), 401 very = very_permission(currResource.id) if very == False: api_response["code"] = 401 api_response["msg"] = "该账户无操作权限" return jsonify(api_response), 401 else: request_json = request.get_json() if 'accName' not in request_json or request_json[ 'accName'] is "": raise ValidationError("参数不能为空") accName = request_json['accName'] # if 'userID' not in request_json or request_json['userID'] is "": # raise ValidationError("参数不能为空") # userID = request_json['userID'] # if 'userName' not in request_json or request_json['userName'] is "": # raise ValidationError("参数不能为空") # userName = request_json['userName'] # if 'accAttr' not in request_json or request_json['accAttr'] is "": # raise ValidationError("参数不能为空") # accAttr = request_json['accAttr'] # if 'etpName' not in request_json or request_json['etpName'] is "": # raise ValidationError("参数不能为空") # etpName = request_json['etpName'] # if 'userDP' not in request_json or request_json['userDP'] is "": # raise ValidationError("参数不能为空") # userDP = request_json['userDP'] if 'userMail' not in request_json or request_json[ 'userMail'] is "": raise ValidationError("参数不能为空") userMail = request_json['userMail'] if 'userPhone' not in request_json or request_json[ 'userPhone'] is "": raise ValidationError("参数不能为空") userPhone = request_json['userPhone'] if 'userTel' not in request_json or request_json[ 'userTel'] is "": raise ValidationError("参数不能为空") userTel = request_json['userTel'] # user = User.query.filter(User.accName == accName,User.userID == userID,User.userName == userName, # User.accAttr == accAttr,User.etpName == etpName,User.userDP == userDP).first() user = User.query.filter(User.accName == accName).first() if user == None: api_response["code"] = 400 api_response["msg"] = "该账户不存在" return jsonify(api_response), 400 if ('accType' in request_json): user.role_id = request_json['accType'] user.userMail = userMail user.userPhone = userPhone user.userTel = userTel if ('password' in request_json): user.hash_pwd(request_json['password']) if ('status' in request_json): user.status = request_json['status'] if ('remarks' in request_json): user.remarks = request_json['remarks'] try: db.session.commit() except Exception as ie: Logger('error.log', level='error').logger.error( "[事务提交失败]accName:【%s】%s" % (accName, ie)) db.session.rollback() return jsonify(api_response) except Exception as e: Logger('error.log', level='error').logger.error( "[修改用户信息异常]accName:【%s】%s" % (accName, e)) api_response["code"] = 500 api_response["msg"] = "服务器未知错误" return jsonify(api_response), 500
def createUser(): if request.method == 'POST': api_response = {"code": 0, "msg": "success"} try: currResource = Resource.query.filter( Resource.perms == "modules:usermanage:save").first() if currResource == None: api_response["code"] = 401 api_response["msg"] = "当前操作权限实体不存在" return jsonify(api_response), 401 very = very_permission(currResource.id) if very == False: api_response["code"] = 401 api_response["msg"] = "该账户无操作权限" return jsonify(api_response), 401 else: request_json = request.get_json() if 'accName' not in request_json or request_json[ 'accName'] is "": raise ValidationError("参数不能为空") accName = request_json['accName'] if 'password' not in request_json or request_json[ 'password'] is "": raise ValidationError("参数不能为空") password = request_json['password'] if 'accType' not in request_json or request_json[ 'accType'] is "": raise ValidationError("参数不能为空") accType = request_json['accType'] if 'userID' not in request_json or request_json['userID'] is "": raise ValidationError("参数不能为空") userID = request_json['userID'] if 'userName' not in request_json or request_json[ 'userName'] is "": raise ValidationError("参数不能为空") userName = request_json['userName'] if 'accAttr' not in request_json or request_json[ 'accAttr'] is "": raise ValidationError("参数不能为空") accAttr = request_json['accAttr'] if 'etpName' not in request_json or request_json[ 'etpName'] is "": raise ValidationError("参数不能为空") etpName = request_json['etpName'] if 'userDP' not in request_json or request_json['userDP'] is "": raise ValidationError("参数不能为空") userDP = request_json['userDP'] if 'userMail' not in request_json or request_json[ 'userMail'] is "": raise ValidationError("参数不能为空") userMail = request_json['userMail'] if 'userPhone' not in request_json or request_json[ 'userPhone'] is "": raise ValidationError("参数不能为空") userPhone = request_json['userPhone'] if 'userTel' not in request_json or request_json[ 'userTel'] is "": raise ValidationError("参数不能为空") userTel = request_json['userTel'] status = (request_json['status'] if ('status' in request_json) else 1) create_user_id = g.user create_date = (request_json['create_date'] if ('create_date' in request_json) else datetime.now()) remarks = (request_json['remarks'] if ('remarks' in request_json) else "") newUser = User(accName, userID, userName, userMail, userPhone, userTel, password, status, accType, accAttr, etpName, userDP, create_date, create_user_id, remarks) newUser.hash_pwd(password) db.session.add(newUser) try: db.session.commit() except Exception as ie: Logger('error.log', level='error').logger.error( "[事务提交失败]accName:【%s】%s" % (accName, ie)) db.session.rollback() return jsonify(api_response) except Exception as e: Logger('error.log', level='error').logger.error( "[添加用户异常]accName:【%s】%s" % (accName, e)) api_response["code"] = 500 api_response["msg"] = "服务器未知错误" return jsonify(api_response), 500