Example #1
0
    def visitLogin_statement(self, ctx: Ah210Parser.Login_statementContext):
        from apitax.ah.Connector import Connector

        parameters = self.visit(ctx.optional_parameters_block())

        driver = self.appOptions.driver
        extra = {}

        if ('driver' in parameters):
            driver = parameters['driver']

        if ('extra' in parameters):
            extra = parameters['extra']

        if ('username' in parameters and 'password' in parameters):
            if (self.appOptions.debug):
                self.log.log("> Logging into API with username and password.")
                self.log.log("")
            connector = Connector(options=Options(debug=self.appOptions.debug,
                                                  sensitive=True,
                                                  driver=driver),
                                  credentials=Credentials(
                                      username=parameters['username'],
                                      password=parameters['password'],
                                      extra=extra))
            return connector.getCredentials()
        elif ('token' in parameters):
            return Credentials(token=parameters['token'])
        else:
            self.error(
                'Must pass a `username` and `password` or a `token` for authentication'
            )
            return None
Example #2
0
    def getCatalog(self, auth):
        from apitax.ah.Connector import Connector
        import json

        connector = Connector(
            credentials=Credentials(token=auth.token),
            command="custom --get --driver OpenstackDriver --url " +
            self.getCatalogEndpoint(),
            options=Options(debug=False,
                            sensitive=True,
                            driver='OpenstackDriver'),
            parameters=None)

        commandHandler = connector.execute()

        services = json.loads(commandHandler.getRequest().getResponseBody())

        catalog = {}
        catalog['endpoints'] = {}

        for service in services['catalog']:
            endpoints = service['endpoints']
            if (len(endpoints) > 0):
                for endpoint in endpoints:
                    if (endpoint['interface'] == 'public'):
                        name = service['name']
                        catalog['endpoints'].update(
                            {name: {
                                "label": name,
                                "value": endpoint['url']
                            }})

        catalog['selected'] = "http://172.25.190.14:5000"

        return catalog
Example #3
0
def mapUserAuthToCredentials(userAuth: UserAuth, credentials=Credentials()):
    if (userAuth.api_token):
        credentials.token = userAuth.api_token
    else:
        credentials.username = userAuth.username
        credentials.password = userAuth.password

    if (userAuth.extra):
        credentials.extra = userAuth.extra

    return credentials
Example #4
0
    def executeCommand(self, resolvedCommand, logPrefix=''):
        from apitax.ah.Connector import Connector
        if (self.appOptions.debug):
            self.log.log(
                '> Executing Commandtax: \'' + resolvedCommand['command'] +
                '\' ' + 'with parameters: ' +
                str(resolvedCommand['parameters']), logPrefix)
            self.log.log('')

        auth = None
        if (resolvedCommand['auth']):
            auth = resolvedCommand['auth']
        else:
            auth = self.data.getAuth()

        connector = Connector(options=Options(
            debug=self.appOptions.debug,
            sensitive=self.appOptions.sensitive,
            driver=resolvedCommand['driver']),
                              credentials=Credentials(username=auth.username,
                                                      password=auth.password,
                                                      token=auth.token),
                              command=resolvedCommand['command'],
                              parameters=resolvedCommand['parameters'],
                              json=True)
        commandHandler = connector.execute()

        if (hasattr(commandHandler.getRequest(), 'parser')):
            if (commandHandler.getRequest().parser.isError()):
                self.error(
                    'Subscript contains error: ' +
                    commandHandler.getRequest().parser.isError()['message'],
                    logPrefix)

        if (resolvedCommand['strict'] and
                commandHandler.getRequest().getResponseStatusCode() >= 300):
            self.error(
                'Request returned non-success status code while in strict mode. Request returned: Status '
                + str(commandHandler.getRequest().getResponseStatusCode()) +
                ' ' + commandHandler.getRequest().getResponseBody(), logPrefix)

        returnResult = commandHandler.getReturnedData()
        if ('callback' in resolvedCommand):
            returnResult = self.executeIsolatedCallback(
                resolvedCommand['callback'], returnResult, logPrefix)

        return dict({
            "command": resolvedCommand['command'],
            "commandHandler": commandHandler,
            "result": returnResult
        })
Example #5
0
def execute_api_command():
    try:
        connector = None

        parameters = []

        if (request.json['parameters']):
            parameters = request.json['parameters']

        credentials = Credentials()
        options = Options(debug=request.json['debug'],
                          sensitive=request.json['sensitive'])

        if ('token' in request.json):
            credentials.token = request.json['token']
        else:
            credentials.username = request.json['user']
            credentials.password = request.json['pass']
            options.sensitive = True

        if ('extra' in request.json):
            credentials.extra = request.json['extra']

        connector = Connector(options=options,
                              credentials=credentials,
                              command=request.json['command'],
                              parameters=parameters)

        commandHandler = connector.execute()

        returner = {
            "status": commandHandler.getRequest().getResponseStatusCode(),
            "body": json.loads(commandHandler.getRequest().getResponseBody())
        }

        if (request.json['debug']):
            returner.update({"log": connector.logBuffer})

        return json.dumps(returner)
    except:
        bottleServer.log.error(traceback.format_exc())
        if ('debug' in request.json and request.json['debug']):
            return json.dumps({
                "status": 500,
                "body": {
                    "error": {
                        "state":
                        "Uncaught exception occured during processing. To get a larger stack trace, visit the logs.",
                        "message": traceback.format_exc(3)
                    }
                }
            })
        else:
            return json.dumps({"status": 500, "body": {}})
Example #6
0
def execute_api_auth():
    connector = Connector(sensitive=True,
                          credentials=Credentials(
                              username=request.json['user'],
                              password=request.json['pass']))

    if (connector.http.isTokenable()):
        return json.dumps({
            "status": 201,
            "auth": "presumed success",
            "token": connector.token,
            "body": json.loads(connector.auth.getResponseBody())
        })
    else:
        return json.dumps({
            "status":
            400,
            "auth":
            "authentication does not support tokens, please pass username and password with each API request"
        })
Example #7
0
    def __init__(self,
                 header,
                 command,
                 config,
                 options=Options(),
                 parameters={},
                 auth=Credentials()):

        if (type(command) is not list):
            command = shlex.split(command.strip())
        if (len(command) < 1):
            return
        self.request = None

        if ('--debug' in command):
            options.debug = True
        if ('--sensitive' in command):
            options.sensitive = True
        if ('--driver' in command):
            options.driver = command[command.index('--driver') + 1]

        if (command[0] == 'script'):
            self.request = Script(config, header, auth, parameters, options)
        elif (command[0] == 'custom'):
            self.request = Custom(config, header, auth, parameters, options)
        else:
            if (options.driver):
                customCommands = LoadedDrivers.getCommandsDriver(
                    options.driver)
            else:
                customCommands = LoadedDrivers.getDefaultCommandsDriver()
            self.request = customCommands.setup(config, header, auth,
                                                parameters, options)
            self.request = self.request.handle(command)
            return

        self.request.handle(command[1:])
Example #8
0
    def execute(self, command):
        self.command = command

        if (self.usage == 'cli'):
            # Authentication is incorporated into Connector

            if (self.options.debug):
                self.log.log(">>> Starting Processing")
                self.log.log("")
                self.log.log("")

            self.connector = Connector(options=self.options,
                                       command=self.command,
                                       credentials=Credentials(
                                           username=self.username,
                                           password=self.password),
                                       json=True)
            self.result = self.connector.execute()

            # print(str(connector.http.getCatalog()))

            if (self.options.debug):
                self.log.log(">>> Finished Processing")
                self.log.log("")
                self.log.log("")

            if (self.options.debug and self.command.split(' ')[0] == 'script'):
                for t in self.result.getRequest().parser.threads:
                    t.join()
                self.log.log(">> Dumping Current DataStore Status:")
                self.log.log(
                    "    * I recommend this website for looking at the data: http://json.parser.online.fr/"
                )
                self.log.log("")
                self.log.log("")
                self.log.log(
                    json.dumps(
                        self.result.getRequest().parser.data.getStatus(),
                        default=serialize))
                self.log.log("")
                self.log.log("")
            # print(result.getRequest().data.getData('5.3.role_assignments.0.links.assignment'))

            if (self.options.debug):
                self.log.log(">> Apitax finished processing in " +
                             round2str(time() - self.t0) + "s")
                self.log.log("")
                self.log.log("")

        elif (self.usage == 'web'):
            from apitax.ah.api.Server import startDevServer
            if (self.build):
                self.log.log(">> Building Website Assets:")
                self.log.log("")
                path = State.paths['node']
                self.npm = Npm(path)
                self.npm.install()
                self.npm.build()
                if (self.watcher):
                    self.npm.buildWatch(True)
                self.log.log("")
                self.log.log(">> Done Building Website Assets")
            self.log.log(">> Booting Up WebServer:")
            self.log.log("")
            self.server = startDevServer(self.config.get("ip"),
                                         self.config.get("port"))
            #bSrv.start(config.get("ip"), config.get("port"), config=config, options=options, reloader=reloader)

        elif (self.usage == 'grammar-test'):
            GrammarTest(self.script)

        elif (self.usage == 'feature-test'):
            pass

        elif (self.usage == 'build'):
            self.log.log(">> Building:")
            self.log.log("> This can take several minutes")
            self.log.log("")
            path = State.paths['node']
            self.npm = Npm(path)
            self.npm.install()
            self.npm.build()
            self.log.log("")
            self.log.log(">> Building Complete")

        else:
            self.log.log("### Error: Unknown mode")

        self.log.getLoggerDriver().outputLog()