示例#1
0
 async def test_calables_is_allowed(self, callable_loader):
     try:
         web.Application(middlewares=[
             aiohttp_tokenauth.token_auth_middleware(callable_loader),
         ])
     except TypeError:
         pytest.fail("Unexpected TypeError")
示例#2
0
async def init() -> web.Application:
    """
    Инициализация aiohttp-приложения.

    :return: экземпляр aiohttp-приложения
    """
    async def user_loader(token: str) -> Optional[User]:
        """
        Проверить валидность переданного токена.

        :param token: Токен из HTTP заголовка "Authorization"
        :return: если токен найден в БД - вернет экземпляр класса `User`,
                 в противном случае - None
        """
        async with app['db'].acquire() as conn:
            user_dao = SqlAlchemyUserDAO(conn)
            try:
                user = await user_dao.get_by_token(token)
            except DAOException:
                user = None
            return user

    app = web.Application(middlewares=[
        transaction_middleware,
        token_auth_middleware(user_loader=user_loader,
                              exclude_routes=('/login', ))
    ])
    app['config'] = config

    app.on_startup.append(init_pg)
    app.on_cleanup.append(close_pg)

    setup_routes(app)
    return app
示例#3
0
def init_app(argv=None):
    app = web.Application(middlewares=[
        token_auth_middleware(movie.admin_loader, exclude_methods=('GET', ))
    ])
    app.add_routes(routes)
    app.cleanup_ctx.append(init_db)
    web.run_app(app, port=os.environ['PORT'])
    return app
示例#4
0
def cli(loop, aiohttp_client):
    app = web.Application(middlewares=[
        aiohttp_tokenauth.token_auth_middleware(
            user_loader=user_loader,
            exclude_routes=('/exclude', r'/exclude/\w+/info'),
            exclude_methods=('POST', ),
        ),
    ])
    app.router.add_route('*', '/', example_resource)
    app.router.add_get('/exclude', example_resource)
    app.router.add_get('/exclude/{user}/info', example_resource)
    return loop.run_until_complete(aiohttp_client(app))
示例#5
0
async def init():

    async def user_loader(token: str):
        """Checks that token is valid

        It's the callback that will get the token from "Authorization" header.
        It can check that token is exist in a database or some another place.

        Args:
            token (str): A token from "Authorization" http header.

        Returns:
            Dict or something else. If the callback returns None then
            the aiohttp.web.HTTPForbidden will be raised.
        """
        user = None
        if token == 'fake-token':
            user = {'uuid': 'fake-uuid'}
        return user

    app = web.Application(middlewares=[token_auth_middleware(user_loader)])
    app.router.add_get('/', example_resource)
    return app
示例#6
0
async def init(loop):
    conn = await connect(host=HOST,
                         port=PORT,
                         user=USER,
                         password=PASSWORD,
                         db=DATABASE_NAME,
                         loop=loop)

    # Require image(bytes), userID(string), domainName(string), thres(float)(Optional default = 0.85)
    @routes.post('/check')
    async def handle_post_check(request):
        # read request data
        reader = await request.multipart()
        filedata = None
        userID = None
        domainName = None
        decisionThres = 1.1
        # read all parts
        while True:
            part = await reader.next()
            if part is None:  # all parts are read
                break
            if part.name == 'image':
                filedata = await part.read()
            elif part.name == 'userID':
                userID = await part.text()
            elif part.name == 'domainName':
                domainName = await part.text()
            elif part.name == 'thres':
                decisionThres = float(await part.text())
        # check requirements
        if filedata is None or not userID or not domainName:
            return web.HTTPBadRequest(
                reason='Require image, userID and domainName.')
        else:
            if userID != request['user']['userID'] or domainName != request[
                    'user']['domainName']:
                return web.HTTPForbidden(text='Invalid Token')
            async with conn.cursor() as cursor:
                stmt = 'SELECT embedding FROM {} WHERE domainName = %s AND userID = %s'.format(
                    TABLE_NAME)
                value = (domainName, userID)
                await cursor.execute(stmt, value)
                result = await cursor.fetchone()
                await cursor.close()
                # check if account already registered
                if result:
                    result = np.array([json.loads(result[0])])
                    async with ClientSession() as session:
                        async with session.post(ENDPOINT_URL,
                                                data={'image':
                                                      filedata}) as resp:
                            # check if API status_code is 200
                            if resp.status == 200:
                                r = await resp.json()
                                # check if API can not progress
                                if r['status'] != 'OK':
                                    return web.HTTPBadRequest(
                                        reason='API Error')
                                # check number of faces
                                elif len(r['faces']) >= 1:
                                    embeddings = np.array([
                                        face['embedding']
                                        for face in r['faces']
                                    ])
                                    dist2Store = cdist(embeddings, result)
                                    minDist = np.min(
                                        dist2Store, axis=0)[0]  # closest match
                                    if minDist <= decisionThres:  # atleast one face
                                        return web.json_response(
                                            {'result': True})
                                    return web.json_response({'result': False})
                                # number of faces are not valid(0)
                                else:
                                    return web.HTTPBadRequest(
                                        reason='{} faces found.'.format(
                                            len(r['faces'])))
                            # API downed
                            else:
                                return web.HTTPBadRequest(
                                    reason='API status : {}'.format(
                                        resp.status))
                # domainName + userID are invalid
                else:
                    return web.HTTPNotFound()

    # Require image(bytes), userID(string), domainName(string)
    @routes.post('/register')
    async def handle_post_register(request):
        # read request data
        reader = await request.multipart()
        filedata = None
        userID = None
        domainName = None
        # read all parts
        while True:
            part = await reader.next()
            if part is None:  # all parts are read
                break
            if part.name == 'image':
                filedata = await part.read()
            elif part.name == 'userID':
                userID = await part.text()
            elif part.name == 'domainName':
                domainName = await part.text()
        # check requirements
        if filedata is None or not userID or not domainName:
            return web.HTTPBadRequest(
                reason='Require image, userID and domainName.')
        else:
            if userID != request['user']['userID'] or domainName != request[
                    'user']['domainName']:
                return web.HTTPForbidden(text='Invalid Token')
            async with conn.cursor() as cursor:
                stmt = 'SELECT * FROM {} WHERE domainName = %s AND userID = %s'.format(
                    TABLE_NAME)
                value = (domainName, userID)
                await cursor.execute(stmt, value)
                result = await cursor.fetchone()
                await cursor.close()
                # check if account is not yet registered
                if not result:
                    async with ClientSession() as session:
                        async with session.post(ENDPOINT_URL,
                                                data={'image':
                                                      filedata}) as resp:
                            # check if API status_code is 200
                            if resp.status == 200:
                                r = await resp.json()
                                # check if API can not progress
                                if r['status'] != 'OK':
                                    return web.HTTPBadRequest(
                                        reason='API Error')
                                # check number of faces(only 1 face can be registered)
                                elif len(r['faces']) == 1:
                                    embedding = r['faces'][0]['embedding']
                                    async with conn.cursor() as cursor:
                                        stmt = 'INSERT INTO {} (domainName, userID, embedding) VALUES (%s, %s, %s)'.format(
                                            TABLE_NAME)
                                        value = (domainName, userID,
                                                 json.dumps(embedding))
                                        await cursor.execute(stmt, value)
                                        await conn.commit()
                                        await cursor.close()
                                        return web.json_response(
                                            {'status': 'OK'})
                                # number of faces are not valid(not equal 1)
                                else:
                                    return web.HTTPBadRequest(
                                        reason='{} faces found.'.format(
                                            len(r['faces'])))
                            # API downed
                            else:
                                return web.HTTPBadRequest(
                                    reason='API status : {}'.format(
                                        resp.status))
                # domainName + userID found
                else:
                    return web.HTTPBadRequest(reason='already registered')

    # Require image(bytes), userID(string), domainName(string)
    @routes.post('/update')
    async def handle_post_update(request):
        # read request data
        reader = await request.multipart()
        filedata = None
        userID = None
        domainName = None
        # read all parts
        while True:
            part = await reader.next()
            if part is None:  # all parts are read
                break
            if part.name == 'image':
                filedata = await part.read()
            elif part.name == 'userID':
                userID = await part.text()
            elif part.name == 'domainName':
                domainName = await part.text()
        # check requirements
        if filedata is None or not userID or not domainName:
            return web.HTTPBadRequest(
                reason='Require image, userID and domainName.')
        else:
            if userID != request['user']['userID'] or domainName != request[
                    'user']['domainName']:
                return web.HTTPForbidden(text='Invalid Token')
            async with conn.cursor() as cursor:
                stmt = 'SELECT * FROM {} WHERE domainName = %s AND userID = %s'.format(
                    TABLE_NAME)
                value = (domainName, userID)
                await cursor.execute(stmt, value)
                result = await cursor.fetchone()
                await cursor.close()
                # check if account already registered
                if result:
                    async with ClientSession() as session:
                        async with session.post(ENDPOINT_URL,
                                                data={'image':
                                                      filedata}) as resp:
                            # check if API status_code is 200
                            if resp.status == 200:
                                r = await resp.json()
                                # check if API can not progress
                                if r['status'] != 'OK':
                                    return web.HTTPBadRequest(
                                        reason='API Error')
                                # check number of faces(only 1 face can be updated)
                                elif len(r['faces']) == 1:
                                    embedding = r['faces'][0]['embedding']
                                    async with conn.cursor() as cursor:
                                        stmt = 'UPDATE {} SET embedding = %s WHERE domainName = %s AND userID = %s'.format(
                                            TABLE_NAME)
                                        value = (json.dumps(embedding),
                                                 domainName, userID)
                                        await cursor.execute(stmt, value)
                                        await conn.commit()
                                        await cursor.close()
                                        return web.json_response(
                                            {'status': 'OK'})
                                # number of faces are not valid(not equal 1)
                                else:
                                    return web.HTTPBadRequest(
                                        reason='{} faces found.'.format(
                                            len(r['faces'])))
                            # API downed
                            else:
                                return web.HTTPBadRequest(
                                    reason='API status : {}'.format(
                                        resp.status))
                # domainName + userID not found
                else:
                    return web.HTTPNotFound()

    # Require json userID(string), domainName(string)
    @routes.delete('/delete')
    async def handle_delete(request):
        try:
            # read request data to json
            js = await request.json()
            userID = js['userID']
            domainName = js['domainName']
            if userID != request['user']['userID'] or domainName != request[
                    'user']['domainName']:
                return web.HTTPForbidden(text='Invalid Token')
            async with conn.cursor() as cursor:
                stmt = 'SELECT * FROM {} WHERE domainName = %s AND userID = %s'.format(
                    TABLE_NAME)
                value = (domainName, userID)
                await cursor.execute(stmt, value)
                result = await cursor.fetchone()
                await cursor.close()
                # check if account already registered
                if result:
                    async with conn.cursor() as cursor:
                        stmt = 'DELETE FROM {} WHERE domainName = %s AND userID = %s'.format(
                            TABLE_NAME)
                        value = (domainName, userID)
                        await cursor.execute(stmt, value)
                        await conn.commit()
                        await cursor.close()
                        return web.json_response({'status': 'OK'})
                # domainName + userID not found
                else:
                    return web.HTTPNotFound()
            # error occure return error message to client
        except Exception as err:
            return web.HTTPBadRequest(reason=str(err))

    async def user_loader(token: str):
        try:
            user = {
                k: v
                for k, v in jwt.decode(token, SECRET, algorithms=['HS256'
                                                                  ]).items()
                if k in ('userID', 'domainName')
            }
            if 'userID' not in user or 'domainName' not in user:
                user = None
        except:
            user = None
        finally:
            return user

    app = web.Application(middlewares=[token_auth_middleware(user_loader)])
    app.add_routes(routes)
    return app
示例#7
0
 async def test_uncalables_is_not_allowed(self):
     with pytest.raises(TypeError):
         web.Application(middlewares=[
             aiohttp_tokenauth.token_auth_middleware(user_loader=111)
         ])
示例#8
0
    print(picture)
    file = open(list_data[1][int(picture)], 'rb')
    print(file)
    return web.Response(body=file, content_type="image/jpeg")


async def user_verify(token: str):
    user = None
    if db.token_check(token):
        user = token
    return user


database = db.bind(True)

# comment line below after creating database
# db.define_all()

# x = db.json_pack()

# db.show()
# app = web.Application()
excluded = ('/add/user', '/login', r'/confirm/.+', r'/send/picture/.+')

app = web.Application(middlewares=[
    token_auth_middleware(
        user_loader=user_verify, auth_scheme='Token', exclude_routes=excluded)
])
app.add_routes(routes)
web.run_app(app)