<commit_before># -*- coding: utf-8 -*-
#
# Copyright 2017 dpa-infocom GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import uuid
from aiohttp import web

logger = logging.getLogger(__name__)

_tokens = {}


async def auth_middleware(app, handler):
    async def middleware_handler(request):
        try:
            # check auth header
            if not request.path == "/api/v1/session":
                token = request.headers.get("X-Auth-Token")
                if token not in _tokens.values():
                    raise web.HTTPUnauthorized()
            # return response
            response = await handler(request)
            return response
        except web.HTTPException as ex:
            raise
    return middleware_handler


class WebApi(object):

    def __init__(self, *, config, controller, loop):
        self.config = config
        self.loop = loop

        # start server
        self.app = web.Application(loop=loop, middlewares=[auth_middleware])
        self.app["controller"] = controller
        self.app.router.add_get("/", self.index_handler)
        self.app.router.add_get("/api/v1/controlfile", self.control_get)
        self.app.router.add_post("/api/v1/controlfile", self.control_post)
        self.app.router.add_post("/api/v1/session", self.login)
        self.handler = self.app.make_handler()
        f = self.loop.create_server(self.handler, self.config["host"], self.config["port"])
        self.srv = loop.run_until_complete(f)

    async def login(self, request):
        try:
            assert self.config["auth"]["user"]
            assert self.config["auth"]["password"]
        except AssertionError:
            logger.error("HTTP Auth credentials are missing!")
            return web.json_response({"error": "Internal Server Error"}, status=500)

        params = await request.post()
        user = params.get('username', None)
        if (user == self.config["auth"]["user"] and
            params.get('password', None) == self.config["auth"]["password"]):
            # User is in our database, remember their login details
            _tokens[user] = str(uuid.uuid4())
            return web.json_response({"token":_tokens[user]})
        raise web.HTTPUnauthorized()

    async def index_handler(self, request):
        return web.json_response({})

    async def control_get(self, request):
        return web.json_response({"foo": "GET"})

    async def control_post(self, request):
        return web.json_response({"foo": "POST"})

    def shutdown(self):<commit_msg>API: PUT method for saving controldata.<commit_after># -*- coding: utf-8 -*-
#
# Copyright 2017 dpa-infocom GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import uuid
from aiohttp import web

logger = logging.getLogger(__name__)

_tokens = {}


async def auth_middleware(app, handler):
    async def middleware_handler(request):
        try:
            # check auth header
            if not request.path == "/api/v1/session":
                token = request.headers.get("X-Auth-Token")
                if token not in _tokens.values():
                    raise web.HTTPUnauthorized()
            # return response
            response = await handler(request)
            return response
        except web.HTTPException as ex:
            raise
    return middleware_handler


class WebApi(object):

    def __init__(self, *, config, controller, loop):
        self.config = config
        self.loop = loop

        # start server
        self.app = web.Application(loop=loop, middlewares=[auth_middleware])
        self.app["controller"] = controller
        self.app.router.add_get("/", self.index_handler)
        self.app.router.add_get("/api/v1/controldata", self.control_get)
        self.app.router.add_put("/api/v1/controldata", self.control_put)
        self.app.router.add_post("/api/v1/session", self.login)
        self.handler = self.app.make_handler()
        f = self.loop.create_server(self.handler, self.config["host"], self.config["port"])
        self.srv = loop.run_until_complete(f)

    async def login(self, request):
        try:
            assert self.config["auth"]["user"]
            assert self.config["auth"]["password"]
        except AssertionError:
            logger.error("HTTP Auth credentials are missing!")
            return web.json_response({"error": "Internal Server Error"}, status=500)

        params = await request.post()
        user = params.get('username', None)
        if (user == self.config["auth"]["user"] and
            params.get('password', None) == self.config["auth"]["password"]):
            # User is in our database, remember their login details
            _tokens[user] = str(uuid.uuid4())
            return web.json_response({"token":_tokens[user]})
        raise web.HTTPUnauthorized()

    async def index_handler(self, request):
        return web.json_response({})

    async def control_get(self, request):
        return web.json_response({"foo": "GET"})

    async def control_put(self, request):
        return web.json_response({"foo": "PUT"})

    def shutdown(self):
{'fraction_non_alphanumeric': 0.11543492478744277, 'fraction_numerical': 0.005559189012426423, 'mean_word_length': 2.727605118829982, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '184998', 'n_tokens_mistral': 1688, 'n_tokens_neox': 1653, 'n_words': 484}