

def loadSaltApi(app, opts=None):
    ' Load endpoints for Salt-API '
    from salt.exceptions import EauthAuthenticationError
    import salt.client.api
    sleep = (gevent.sleep if gevented else time.sleep)

    @app.post('/login')
    def loginPost():
        ' Login and respond with login credentials'
        data = bottle.request.json
        if (not data):
            bottle.abort(400, 'Login data missing.')
        creds = dict(username=data.get('username'), password=data.get('password'), eauth=data.get('eauth'))
        client = salt.client.api.APIClient(opts)
        try:
            creds = client.create_token(creds)
        except EauthAuthenticationError as ex:
            bottle.abort(401, text=repr(ex))
        bottle.response.set_header('X-Auth-Token', creds['token'])
        return {
            'return': [creds],
        }

    @app.post('/logout')
    def logoutPost():
        '\n        Logout\n        {return: "Logout suceeded."}\n        '
        token = bottle.request.get_header('X-Auth-Token')
        if token:
            result = {
                'return': 'Logout suceeded.',
            }
        else:
            result = {
                
            }
        return result

    @app.post(['/signature', '/signature/<token>'])
    def signaturePost(token=None):
        '\n        Fetch module function signature(s) with either credentials in post data\n        or token from url or token from X-Auth-Token header\n        '
        if (not token):
            token = bottle.request.get_header('X-Auth-Token')
        cmds = bottle.request.json
        if (not cmds):
            bottle.abort(code=400, text='Missing command(s).')
        if hasattr(cmds, 'get'):
            cmds = [cmds]
        client = salt.client.api.APIClient(opts)
        try:
            results = [client.signature(tokenify(cmd, token)) for cmd in cmds]
        except EauthAuthenticationError as ex:
            bottle.abort(code=401, text=repr(ex))
        except Exception as ex:
            bottle.abort(code=400, text=repr(ex))
        return {
            'return': results,
        }

    @app.post(['/run', '/run/<token>'])
    def runPost(token=None):
        '\n        Execute salt command with either credentials in post data\n        or token from url or token from X-Auth-Token headertoken\n        '
        if (not token):
            token = bottle.request.get_header('X-Auth-Token')
        cmds = bottle.request.json
        if (not cmds):
            bottle.abort(code=400, text='Missing command(s).')
        if hasattr(cmds, 'get'):
            cmds = [cmds]
        client = salt.client.api.APIClient(opts)
        try:
            results = [client.run(tokenify(cmd, token)) for cmd in cmds]
            if (not results[0]):
                bottle.response.status = 404
                return {
                    'error': 'Failed to run command: {0} on target: {1}'.format(str(cmds[0]['fun']), str(cmds[0]['tgt'])),
                }
        except EauthAuthenticationError as ex:
            bottle.abort(code=401, text=repr(ex))
        except Exception as ex:
            bottle.abort(code=400, text=repr(ex))
        return {
            'return': results,
        }

    @app.get('/event/<token>')
    def eventGet(token):
        '\n        Create server sent event stream from salt\n        and authenticate with the given token\n        Also optional query arg tag allows with\n        filter events based on tag\n        '
        if (not token):
            bottle.abort(401, 'Missing token.')
        client = salt.client.api.APIClient(opts)
        if (not client.verify_token(token)):
            bottle.abort(401, 'Invalid token.')
        tag = bottle.request.query.get('tag', '')
        bottle.response.set_header('Content-Type', 'text/event-stream')
        bottle.response.set_header('Cache-Control', 'no-cache')
        (yield 'retry: 250\n\n')
        while True:
            data = client.get_event(wait=0.025, tag=tag, full=True)
            if data:
                try:
                    (yield 'data: {0}\n\n'.format(json.dumps(data)))
                except UnicodeDecodeError as ex:
                    logger.error('Error: Salt event has non UTF-8 data:\n{0}'.format(data))
            else:
                sleep(0.1)

    @app.post(['/fire', '/fire/<token>'])
    def firePost(token=None):
        "\n        Fire event(s)\n        Each event is a dict of the form\n        {\n          tag: 'tagstring',\n          data: {datadict},\n        }\n        Post body is either list of events or single event\n        "
        if (not token):
            token = bottle.request.get_header('X-Auth-Token')
        if (not token):
            bottle.abort(401, 'Missing token.')
        client = salt.client.api.APIClient(opts)
        if (not client.verify_token(token)):
            bottle.abort(401, 'Invalid token.')
        events = bottle.request.json
        if (not events):
            bottle.abort(code=400, text='Missing event(s).')
        if hasattr(events, 'get'):
            events = [events]
        results = [dict(tag=event['tag'], result=client.fire_event(event['data'], event['tag'])) for event in events]
        bottle.response.set_header('Content-Type', 'application/json')
        return json.dumps(results)
    return app

dataset/ETHPy150Open saltstack/halite/halite/server_bottle.py loadSaltApi/original