class TestConfigPumpkinProxy(unittest.TestCase): def test_config_key_set(self): self.config = SettingsINI(C.CONFIG_PP_INI) self.result = "http://example.com/foo.js" self.value = self.config.get("set_js_inject", "url") self.assertEqual(self.result, self.value) def test_get_all_configkey_list(self): self.config = SettingsINI(C.CONFIG_PP_INI) self.result = ["url"] self.value = self.config.get_all_childname("set_js_inject") self.assertEqual(self.result, self.value)
def __init__(self, parse_args=None): self.parse_args = parse_args Cmd.__init__(self) self.conf = SettingsINI.getInstance() self.set_prompt() self.initialize_core() self.setOptions()
def __init__(self, parse_args=None, root=None): self.parse_args = parse_args self.root = root Cmd.__init__(self) self.conf = SettingsINI(C.CONFIG_INI) self.setOptions() self.set_prompt_modules()
def __init__(self, parent, **kwargs): super(WirelessModeController, self).__init__() self.parent = parent # self.setHidden(True) # hide widget on home self.conf = SettingsINI.getInstance() # append controller in DefaultWidget self.parent.getDefault.addController(self)
class CoreSettings(Linux): Name = "General" ID = "General" ConfigRoot = "General" Category = "General" Icon = None __subitem = False conf = {} def __init__(self, parent=0, FSettings=None): super(CoreSettings, self).__init__() self.parent = parent self.conf = SettingsINI(C.CONFIG_INI) def deleteObject(self, obj): """ reclaim memory """ del obj @property def getIptablesPath(self): return self.conf.get("iptables", "path_binary") @property def isSubitem(self): return self.__subitem def osWalkCallback(self, arg, directory, files): pass
class SettingsDHCPResource(Resource): config = SettingsINI.getInstance() key_name = "dhcp" @token_required def get(self, attribute=None): if attribute: if not attribute in self.config.get_all_childname(self.key_name): return exception( "Cannot found that attribute {} on {}!".format( key, self.key_name), code=400, ) return jsonify( {attribute: self.config.get(self.key_name, attribute)}) data = {} for key in self.config.get_all_childname(self.key_name): data[key] = self.config.get(self.key_name, key) return jsonify(data) @token_required def post(self): data = request.get_json(force=True) for key, value in data.items(): if not key in self.config.get_all_childname(self.key_name): return jsonify({ "message": "Cannot found that attribute {} on {}!".format( key, self.key_name) }) self.config.set(self.key_name, key, value) return jsonify(data)
class getFileLogResource(Resource): config = SettingsINI.getInstance() args = "page" limit_view = 10 def chunk(self, it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) @token_required def get(self, filename=None): if not os.path.isfile("{}/{}.log".format(C.LOG_BASE, filename)): return exception("Cannot found that file log {}".format(filename), code=400) for args in request.args: if not args in self.args: return exception( "Cannot found parameters {} on request ".format(args), code=400) table = [] page = int(request.args.get("page")) with open("{}/{}.log".format(C.LOG_BASE, filename), "r") as f: for line in f: table.append(json.loads(line)) data_splited = list(self.chunk(table, self.limit_view)) if page <= (len(data_splited) - 1): return jsonify({ "data": { "items": data_splited[page], "limit_view": self.limit_view, "total_pages": (len(table) // self.limit_view) + 1, "current_page": page, "total_count": len(table), } }) return jsonify({ "data": { "items": [], "limt_view": self.limit_view, "total_pages": (len(table) // self.limit_view) + 1, "current_page": page, "total_count": len(table), } }) @token_required def post(self): data = request.get_json(force=True) for key, value in data.items(): if not key in self.config.get_all_childname(self.key_name): return exception( "Cannot found that attribute {} on {}!".format( key, self.key_name), code=400, ) self.config.set(self.key_name, key, value) return jsonify(data)
def __init__(self, parse_args=None, root=None): self.__class__._instance = weakref.proxy(self) self.parse_args = parse_args self.root = root Cmd.__init__(self) self.conf = SettingsINI(C.CONFIG_INI) self.setOptions() self.set_prompt_modules()
def do_list(self, args): """ show all avaliable templates from github """ if not path.isfile(self.save_path): print( display_messages( "can't find downloaded file: {}".format(self.save_path), error=True ) ) return config = SettingsINI(self.config_file_ini) plugins_installed = self.config_default.get_all_childname("plugins") self.plugins_remote = {} for plugin in config.get_all_childname("plugins"): self.plugins_remote[plugin] = {} for info in config.get_all_childname("info_{}".format(plugin)): self.plugins_remote[plugin][info] = config.get( "info_{}".format(plugin), info ) self.plugins_remote[plugin]["installed"] = ( setcolor("True", color="green") if plugin in plugins_installed else setcolor("False", color="red") ) self.table_output = [] for plugin in self.plugins_remote: self.table_output.append( [ self.plugins_remote[plugin]["name"], self.plugins_remote[plugin]["author"], self.plugins_remote[plugin]["installed"], self.plugins_remote[plugin]["preview"], ] ) if len(self.table_output) > 0: print( display_messages( "Available Customs CaptiveFlask:", info=True, sublime=True ) ) display_tabulate(self.table_headers, self.table_output)
def installPluginByName(self, plugin_name): print( display_messages( "Install plugin:: {}".format( setcolor(plugin_name, color="yellow")), info=True, sublime=True, )) source = "{}/plugins/{}.py".format(self.extracted_filepath, plugin_name) destination = "{}/{}.py".format(self.captiveflask_path, plugin_name) dest = copyfile(source, destination) print( display_messages("copy content file to {}".format(dest), info=True)) folder_plugin = "{}/templates/{}".format(self.extracted_filepath, plugin_name) copy_tree(folder_plugin, "config/templates/{}".format(plugin_name)) print( display_messages( "copy content directory to {}".format( "config/templates/{}".format(plugin_name)), info=True, )) self.config_default.set("plugins", plugin_name, False) config = SettingsINI(self.config_file_ini) if config.get_all_childname("set_{}".format(plugin_name)) != []: for language in config.get_all_childname( "set_{}".format(plugin_name)): self.config_default.set("set_{}".format(plugin_name), language, False) self.config_default.set("set_{}".format(plugin_name), "Default", True) print( display_messages( "plugin install {}".format(setcolor("sucessful", color="green")), info=True, ))
class BasePumpkin(object): _name = 'plugin base PumpkinProxy ' _version = '1.0' _config = SettingsINI(C.CONFIG_TP_INI) @staticmethod def getName(): return BasePumpkin._name def handleHeader(self, request, key, value): raise NotImplementedError def handleResponse(self, request, data): raise NotImplementedError
class MitmPluginsResource(Resource): config = SettingsINI.getInstance() key_name = "mitm_modules" def __init__(self): self.root = PumpkinShell.getInstance() super(MitmPluginsResource, self).__init__() @token_required def get(self): mitm_plugins = self.root.mitm_controller.getInfo(excluded=("Config")) for item in mitm_plugins: mitm_plugins[item]["Activate"] = self.config.get( self.key_name, mitm_plugins[item]["ID"], format=bool) return jsonify({"plugins": mitm_plugins})
def test_read_config_SettingsINI(self): config_file_ini = (tempfile.gettempdir() + "/extra-captiveflask-master/config.ini") config = SettingsINI(config_file_ini) result = { "example": { "author": "mh4x0f", "description": "Example is a simple portal default page", "preview": "https://i.imgur.com/G0wtAme.png", "name": "example", "version": "1.0", } } plugins = {} for plugin in config.get_all_childname("plugins"): plugins[plugin] = {} for info in config.get_all_childname("info_{}".format(plugin)): plugins[plugin][info] = config.get("info_{}".format(plugin), info) for plugin in plugins: print(plugin) self.assertEqual(result["example"], plugins["example"])
class ProxiesAllInfoResource(Resource): config = SettingsINI.getInstance() key_name = "proxy_plugins" def __init__(self): self.root = PumpkinShell.getInstance() super(ProxiesAllInfoResource, self).__init__() @token_required def get(self): proxy_plugins = self.root.proxy_controller.getInfo(excluded=("Config")) for item in proxy_plugins: proxy_plugins[item]["Activate"] = self.config.get( self.key_name, proxy_plugins[item]["ID"], format=bool) return jsonify({"proxies": proxy_plugins})
class PSniffer(object): """ plugins data sniffers""" name = "plugin sniffkin3 master" version = "1.0" config = SettingsINI(C.CONFIG_SK_INI) loggers = {} output = pyqtSignal(object) session = None def filterPackets(self, pkt): """ intercept packetes data """ raise NotImplementedError def get_http_headers(self, http_payload): """ get header dict http request""" try: headers_raw = http_payload[:http_payload.index("\r\n\r\n") + 2] headers = dict( findall(r"(?P<name>.*?):(?P<value>.*?)\r\n", headers_raw)) except: return None if "Content-Type" not in headers: return None return headers def setup_logger(self, logger_name, log_file, key=str(), level=logging.INFO): if self.loggers.get(logger_name): return self.loggers.get(logger_name) else: logger = logging.getLogger(logger_name) formatter = logging.Formatter( "SessionID[{}] %(asctime)s : %(message)s".format(key)) fileHandler = logging.FileHandler(log_file, mode="a") fileHandler.setFormatter(formatter) logger.setLevel(logging.INFO) logger.addHandler(fileHandler) return logger def hexdumpPackets(self, pkt): """ show packets hexdump """ return hexdump(pkt)
class LoginResource(Resource): conf = SettingsINI.getInstance() def get(self): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response( "Could not verify", 401, {"WWW-Authenticate": 'Basic realm="Login required!"'}, ) admin_password = generate_password_hash(self.conf.get( "rest_api_settings", "PASSWORD"), method="sha256") admin_name = self.conf.get("rest_api_settings", "USERNAME") admin_SECRET_KEY = self.conf.get("rest_api_settings", "SECRET_KEY") if auth.username != admin_name: return make_response( "Could not verify", 401, {"WWW-Authenticate": 'Basic realm="Login required!"'}, ) admin_public_id = self.conf.get("rest_api_settings", "public_id") if check_password_hash(admin_password, auth.password): token = jwt.encode( { "public_id": admin_public_id, "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30), }, admin_SECRET_KEY, ) return jsonify({"token": token.decode("UTF-8")}) return make_response( "Could not verify", 401, {"WWW-Authenticate": 'Basic realm="Login required!"'}, )
class CaptiveTemplatePlugin(object): Name = "plugin template captive-portal" version = "1.0" config = SettingsINI(C.CONFIG_CP_INI) loggers = {} def init_language(self, lang): pass def getSellectedLanguage(self): selected_lang, key = None, "set_{}".format(self.Name) for lang in self.config.get_all_childname(key): if self.config.get(key, lang, format=bool): selected_lang = lang return selected_lang def initialize(self): self.init_language(self.getSellectedLanguage())
class BasePumpkin(object): _name = "plugin base PumpkinProxy " _version = "1.0" _config = SettingsINI(C.CONFIG_PP_INI) @staticmethod def getName(): return BasePumpkin._name @property def config(self): return self._config def handleHeader(self, request, key, value): raise NotImplementedError def handleResponse(self, request, data): raise NotImplementedError
class ProxysPluginsResource(Resource): config = SettingsINI.getInstance() key_name = "proxy_plugins" def __init__(self): self.root = PumpkinShell.getInstance() super(ProxysPluginsResource, self).__init__() @token_required def get(self): proxy_plugins = self.root.proxy_controller.getInfo() list_plugins = [] for item in proxy_plugins: proxy_plugins[item]["Activate"] = self.config.get( self.key_name, proxy_plugins[item]["ID"], format=bool) if proxy_plugins[item].get("Config"): del proxy_plugins[item]["Config"] list_plugins.append(proxy_plugins[item]) return jsonify({"proxys": list_plugins})
def decorated(*args, **kwargs): token = None if "x-access-token" in request.headers: token = request.headers["x-access-token"] if not token: return jsonify({"message": "Token is missing!"}) conf = SettingsINI.getInstance() try: app_secret_key = conf.get("rest_api_settings", "SECRET_KEY") data = jwt.decode(token, app_secret_key) app_public_id = conf.get("rest_api_settings", "public_id") if app_public_id != data["public_id"]: return jsonify({"message": "Token is invalid!"}) except: return jsonify({"message": "Token is invalid!"}) return f(*args, **kwargs)
class WidgetBase(urwid.Frame): """ common class for widgets """ _conf = SettingsINI(C.CONFIG_INI) def __init__(self, *args, **kwargs): pass def setup_view(self): raise NotImplementedError def main(self): raise NotImplementedError def handleWindow(self, key): raise NotImplementedError def render_view(self): return self
class PluginsInfoResource(Resource): config = SettingsINI.getInstance() key_name = "mitm_modules" def __init__(self): self.root = PumpkinShell.getInstance() super(PluginsInfoResource, self).__init__() @token_required def get(self, plugin_name=None): if plugin_name: if not plugin_name in self.config.get_all_childname(self.key_name): return exception( "Cannot found that attribute {} on {}!".format( plugin_name, self.key_name), code=400, ) proxy_plugins = self.root.mitm_controller.getInfo(excluded=("Config")) for item in proxy_plugins: proxy_plugins[item]["Activate"] = self.config.get( self.key_name, proxy_plugins[item]["ID"], format=bool) return jsonify(proxy_plugins.get(plugin_name))
def __init__(self, parent=0, FSettings=None): super(CoreSettings, self).__init__() self.parent = parent self.conf = SettingsINI(C.CONFIG_INI)
def __init__(self, interface, session): QtCore.QThread.__init__(self) self.interface = interface self.session = session self.stopped = False self.config = SettingsINI(C.CONFIG_SK_INI)
def init_app(app): conf = SettingsINI.getInstance() conf.set("rest_api_settings", "public_id", str(uuid.uuid4()))
def main(): app = QtCore.QCoreApplication(sys.argv) conf = SettingsINI.getInstance() # settings default values that change on conf.set("accesspoint", "status_ap", False) parser = argparse.ArgumentParser( description="WiFi-Pumpkin - pure line-oriented command" ) parser.add_argument( "-i", dest="interface", help="set interface for create AP", default="" ) parser.add_argument( "-s", dest="session", help="set session for continue attack", default=None ) parser.add_argument( "-p", "--pulp", dest="pulp", help="interactive sessions can be scripted with .pulp file", default="", ) parser.add_argument( "-x", "--xpulp", dest="xpulp", help='interactive sessions can be string with ";" as the separator', default="", ) parser.add_argument( "-m", "--wireless-mode", dest="wireless_mode", help="set wireless mode settings", default=None, ) parser.add_argument( "--no-colors", dest="nocolors", help="disable terminal colors and effects.", action="store_true", default=False, ) parser.add_argument( "-v", "--version", action="version", dest="version", version="%(prog)s v{}".format(__version__), ) parse_args = parser.parse_args() parser_args_func(parse_args) # check is rootuser if not getuid() == 0: sys.exit("[!] Wp3 must be run as root.") _author = "{}".format(setcolor(__author__, color="yellow")) _version = setcolor(__version__, color="yellow") _codename = setcolor(__codename__, color="ciano") banner(_codename) print("by: {} - P0cL4bs Team | version: {} ".format(_author, _version)) prompt = PumpkinShell(parse_args) prompt.cmdloop("Starting prompt...") sys.exit(app.exec_())
class Sniffkin3Core(QtCore.QThread): _ProcssOutput = QtCore.pyqtSignal(object) def __init__(self, interface, session): QtCore.QThread.__init__(self) self.interface = interface self.session = session self.stopped = False self.config = SettingsINI(C.CONFIG_SK_INI) def run(self): self.main() def sniffer(self, q): while not self.stopped: try: sniff( iface=self.interface, filter="tcp and ( port 80 or port 8080)", prn=lambda x: q.put(x), store=0, ) except Exception: pass if self.stopped: break def main(self): self.plugins = {} self.plugin_classes = default.PSniffer.__subclasses__() for p in self.plugin_classes: plugin_load = p() self.plugins[plugin_load.Name] = plugin_load self.plugins[plugin_load.Name].output = self._ProcssOutput self.plugins[plugin_load.Name].session = self.session print("\n[*] {} running on port 80/8080:\n".format(self.getID())) for name in self.plugins.keys(): if self.config.get("plugins", name, format=bool): self.plugins[name].getInstance()._activated = True print("TCPProxy::{0:17} status:On".format(name)) print("\n") q = queue.Queue() sniff = Thread(target=self.sniffer, args=(q, )) sniff.start() while not self.stopped: try: pkt = q.get(timeout=0) for Active in self.plugins.keys(): if self.plugins[Active].getInstance()._activated: try: self.plugins[Active].filterPackets(pkt) except Exception: pass except queue.Empty: pass def snifferParser(self, pkt): try: if (pkt.haslayer(Ether) and pkt.haslayer(Raw) and not pkt.haslayer(IP) and not pkt.haslayer(IPv6)): return self.dport = pkt[TCP].dport self.sport = pkt[TCP].sport if pkt.haslayer(TCP) and pkt.haslayer(Raw) and pkt.haslayer(IP): self.src_ip_port = str(pkt[IP].src) + ":" + str(self.sport) self.dst_ip_port = str(pkt[IP].dst) + ":" + str(self.dport) if pkt.haslayer(Raw): self.load = pkt[Raw].load if self.load.startswith("GET"): self.get_http_GET(self.src_ip_port, self.dst_ip_port, self.load) self.searchBingGET( self.load.split("\n", 1)[0].split("&")[0]) elif self.load.startswith("POST"): header, url = self.get_http_POST(self.load) self.getCredentials_POST( pkt.getlayer(Raw).load, url, header, self.dport, self.sport) except: pass def searchBingGET(self, search): if "search?q" in search: searched = search.split("search?q=", 1)[1] searched = searched.replace("+", " ") print("Search::BING { %s }" % (searched)) def getCredentials_POST(self, payload, url, header, dport, sport): user_regex = ("([Ee]mail|%5B[Ee]mail%5D|[Uu]ser|[Uu]sername|" "[Nn]ame|[Ll]ogin|[Ll]og|[Ll]ogin[Ii][Dd])=([^&|;]*)") pw_regex = ("([Pp]assword|[Pp]ass|[Pp]asswd|[Pp]wd|[Pp][Ss][Ww]|" "[Pp]asswrd|[Pp]assw|%5B[Pp]assword%5D)=([^&|;]*)") username = re.findall(user_regex, payload) password = re.findall(pw_regex, payload) if not username == [] and not password == []: self._ProcssOutput.emit({ "POSTCreds": { "User": username[0][1], "Pass": password[0][1], "Url": url, "destination": "{}/{}".format(sport, dport), } }) def get_http_POST(self, load): dict_head = {} try: headers, body = load.split("\r\n\r\n", 1) header_lines = headers.split("\r\n") for item in header_lines: try: dict_head[item.split()[0]] = item.split()[1] except Exception: pass if "Referer:" in dict_head.keys(): return dict_head, dict_head["Referer:"] except ValueError: return None, None return dict_head, None def getpid(self): """ return the pid of current process in background""" return "thread" def getID(self): """ return the name of process in background""" return self.objectName() def stop(self): self.stopped = True print("Thread::[{}] successfully stopped.".format(self.objectName()))
class ModPump(ModuleUI): """ Extra customs captiveflask templates """ name = "extra_captiveflask" save_path = tempfile.gettempdir() + "/master.zip" extracted_filepath = tempfile.gettempdir() + "/extra-captiveflask-master" config_file_ini = tempfile.gettempdir() + "/extra-captiveflask-master/config.ini" captiveflask_path = "wifipumpkin3/plugins/captiveflask" config_default = SettingsINI(C.CONFIG_CP_INI_ROOT) def __init__(self, parse_args=None, root=None): self.parse_args = parse_args self.root = root self.name_module = self.name self.plugins_remote = {} self.table_headers = ["Name", "Author", "Installed", "Preview"] super(ModPump, self).__init__(parse_args=self.parse_args, root=self.root) def do_list(self, args): """ show all avaliable templates from github """ if not path.isfile(self.save_path): print( display_messages( "can't find downloaded file: {}".format(self.save_path), error=True ) ) return config = SettingsINI(self.config_file_ini) plugins_installed = self.config_default.get_all_childname("plugins") self.plugins_remote = {} for plugin in config.get_all_childname("plugins"): self.plugins_remote[plugin] = {} for info in config.get_all_childname("info_{}".format(plugin)): self.plugins_remote[plugin][info] = config.get( "info_{}".format(plugin), info ) self.plugins_remote[plugin]["installed"] = ( setcolor("True", color="green") if plugin in plugins_installed else setcolor("False", color="red") ) self.table_output = [] for plugin in self.plugins_remote: self.table_output.append( [ self.plugins_remote[plugin]["name"], self.plugins_remote[plugin]["author"], self.plugins_remote[plugin]["installed"], self.plugins_remote[plugin]["preview"], ] ) if len(self.table_output) > 0: print( display_messages( "Available Customs CaptiveFlask:", info=True, sublime=True ) ) display_tabulate(self.table_headers, self.table_output) def do_download(self, args): """ download all avaliable templates""" url = C.URL_EXTRA_CAPTIVEFLASK chunk_size = 128 print( display_messages( "downloading templates on {} ".format(self.save_path), info=True ) ) try: r = requests.get(url, stream=True) except Exception as e: print(display_messages(e, error=True)) return with open(self.save_path, "wb") as fd: for chunk in r.iter_content(chunk_size=chunk_size): fd.write(chunk) if not path.isfile(self.save_path): print(display_messages("error when try download templates", error=True)) return print(display_messages("extra captiveflask download successful.", sucess=True)) print(display_messages("extracting files from zip archive", info=True)) path_to_zip_file = tempfile.gettempdir() + "/master.zip" with ZipFile(path_to_zip_file, "r") as zip_ref: zip_ref.extractall(tempfile.gettempdir()) print( display_messages( "extracted files on : {}".format(self.extracted_filepath), info=True ) ) def installPluginByName(self, plugin_name): print( display_messages( "Install plugin:: {}".format(setcolor(plugin_name, color="yellow")), info=True, sublime=True, ) ) source = "{}/plugins/{}.py".format(self.extracted_filepath, plugin_name) destination = "{}/{}.py".format(self.captiveflask_path, plugin_name) dest = copyfile(source, destination) print(display_messages("copy content file to {}".format(dest), info=True)) folder_plugin = "{}/templates/{}".format(self.extracted_filepath, plugin_name) copy_tree(folder_plugin, "config/templates/{}".format(plugin_name)) print( display_messages( "copy content directory to {}".format( "config/templates/{}".format(plugin_name) ), info=True, ) ) self.config_default.set("plugins", plugin_name, False) config = SettingsINI(self.config_file_ini) if config.get_all_childname("set_{}".format(plugin_name)) != []: for language in config.get_all_childname("set_{}".format(plugin_name)): self.config_default.set("set_{}".format(plugin_name), language, False) self.config_default.set("set_{}".format(plugin_name), "Default", True) print( display_messages( "plugin install {}".format(setcolor("sucessful", color="green")), info=True, ) ) def do_install(self, args): """ install custom captiveflask portals """ if not path.isdir(self.captiveflask_path): print( display_messages( "directory {} not found".format(self.captiveflask_path), error=True ) ) return if args: plugin_name = args.split()[0] if not plugin_name in self.plugins_remote: print( display_messages( "plugin: {} not found ".format(plugin_name), error=True ) ) return self.installPluginByName(plugin_name) return self.show_help_command("help_extra_captiveflask") anwer_question = input("So, do you want to install all plugins ? (Y/N): ") if anwer_question.lower() != "y": return for plugin in self.plugins_remote: self.installPluginByName(plugin) return self.show_help_command("help_extra_captiveflask") def do_info(self, args): """ get info custom captiveflask portals """ if args: plugin_name = args.split()[0] if not plugin_name in self.plugins_remote: print( display_messages( "plugin: {} not found ".format(plugin_name), error=True ) ) return print(display_messages("Information", info=True, sublime=True)) list_keys = [ "Name", "Author", "Version", "Installed", "Preview", "Description", ] for item in list_keys: print( " {} : {}".format( setcolor(item, color="blue"), setcolor( self.plugins_remote[plugin_name][item.lower()], color="yellow", ), ) ) print("\n") def complete_info(self, text, args, start_index, end_index): if text: return [ command for command in list(self.plugins_remote.keys()) if command.startswith(text) ] else: return list(self.plugins_remote.keys()) def complete_install(self, text, args, start_index, end_index): if text: return [ command for command in list(self.plugins_remote.keys()) if command.startswith(text) ] else: return list(self.plugins_remote.keys()) def do_options(self, line): pass def do_set(self, args): pass
class SettingsPluginsResource(Resource): config = None key_name = "plugins" def create_config(self, plugin_id): plugin_settings_ini = C.ALL_CONFIGSINI.get(plugin_id) if plugin_settings_ini is None: return self.config = SettingsINI(plugin_settings_ini) @token_required def get(self, plugin_id=None): self.create_config(plugin_id) if self.config is None: return exception( "Cannot found plugin {} ini file.".format(plugin_id), code=400) data = {} for key in self.config.get_all_childname(self.key_name): data[key] = self.config.get(self.key_name, key) for sub_key in self.config.get_all_childname("set_{}".format(key)): if "set_{}".format(key) in list(data.keys()): data["set_{}".format(key)].append({ sub_key: self.config.get("set_{}".format(key), sub_key) }) else: data["set_{}".format(key)] = [] data["set_{}".format(key)].append({ sub_key: self.config.get("set_{}".format(key), sub_key) }) return jsonify(data) @token_required def post(self, plugin_id=None): data = request.get_json(force=True) self.create_config(plugin_id) if self.config is None: return exception( "Cannot found plugin {} ini file.".format(plugin_id), code=400) for key, value in data.items(): if str(key).startswith("set_"): for item in value: for sub_key, sub_value in item.items(): if not sub_key in self.config.get_all_childname(key): return exception( "Cannot found that attribute {} on {}!".format( sub_key, key), code=400, ) self.config.set(key, sub_key, sub_value) else: if not key in self.config.get_all_childname(self.key_name): return exception( "Cannot found that attribute {} on {}!".format( key, self.key_name), code=400, ) self.config.set(self.key_name, key, value) return jsonify(data)
def create_config(self, plugin_id): plugin_settings_ini = C.ALL_CONFIGSINI.get(plugin_id) if plugin_settings_ini is None: return self.config = SettingsINI(plugin_settings_ini)