Exemple #1
0
    async def authenticate(
            self, request: HTTPConnection
    ) -> typing.Optional[typing.Tuple["AuthCredentials", "BaseUser"]]:
        if request.get('method') == 'OPTIONS':
            return
        if "Authorization" not in request.headers:
            raise AuthenticationError('Header not found')
        auth = request.headers['Authorization']
        schema, token = auth.split()
        if schema != 'Bearer':
            raise AuthenticationError('Wrong Schema')

        endpoint = environ.get('AUTH_HOST', 'http://localhost') + '/validate'
        r = requests.post(
            endpoint,
            data={'access_token': token}
        )
        if r.status_code != status.HTTP_200_OK:
            raise AuthenticationError('Unauthorized')

        return
Exemple #2
0
    async def authenticate(self, conn: HTTPConnection):
        global payload

        if conn.url.path == '/users/login' or conn.url.path == '/users/register':
            return
        if conn.url.path.startswith('/records/') and conn.url.path != '/records/' and conn.get('method') == 'GET':
            return

        if 'Authorization' not in conn.headers:
            raise AuthenticationError()

        # 就直接从请求头拿 jwt token ...
        authorization = conn.headers.get('Authorization')
        token = authorization.split(' ')[1]
        try:
            payload = jwt.decode(token, algorithms=['HS256'], key=config.JWT_SECRET)
        except ExpiredSignatureError:
            pass
        username = payload.get('username')
        id = payload.get('id')

        user: Optional[UserModel] = UserModel.get_by_id(id)
        if user:
            return AuthCredentials(['user']), {'username': user.username, 'password': user.password}