# coding:utf-8

from makit.web.context import Context
from makit.web.middleware.base import Middleware


class JWTMiddleware(Middleware):

    async def __call__(self, c: Context):
        token = c.headers.get('token')
        if not token:
            token = c.headers.get('authorization')
        if not token:
            await c.unauthorized('http headers should has TOKEN or AUTHORIZATION')
            return
        try:
            payload = c.app.jwt_decode(token)
            c.scope['payload'] = payload
        except Exception:
            await c.unauthorized('invalid token')

        await c.next()
