Exemple #1
0
def request_token_check(req, func, jwt_required, *args, **kwargs):
    """校验token,获取user信息并添加到request中"""
    res = None
    # 本地环境无需验证登陆
    jwt_required *= env != 'loc'
    try:
        assert jwt_required
        # 获取jwt中的user
        token = req.headers._store.get('x-token', (None, None))[1]
        user = Ouser.query_user_from_token(token)
        # 获取session中的user
        from django.contrib.auth import get_user
        _user = get_user(req)
        # 校验user
        assert user.pk == _user.pk, 'session和token不匹配'
        # res = func(req, *args, **kwargs)
        # res.content = json.dumps(
        #     dict(json.loads(res.content)))
    except AssertionError as e:
        msg = six.text_type(e)
        if msg:
            raise InvalidUser('token和session用户不一致')
    except IndexError or TypeError:
        message = 'headers need token'
        log.warn(message)
        raise InvalidJwtToken(detail=message)
Exemple #2
0
def _token_get_user_id(token):
    """
    The TokenUser class assumes tokens will have a recognizable user
    identifier claim.
    """
    try:
        Token = SlidingToken(token)
        assert api_settings.USER_ID_CLAIM in Token
        return TokenUser(Token).id
    except:
        raise InvalidJwtToken(detail='Token 失效')
Exemple #3
0
def token_obtain_sliding_logout_handler(**params):
    """
    用户登出,更新用户信息,注销request信息等
    """
    try:
        current_request = params.get('request')
        assert params.get('request')
        session_logout(current_request)
    except Exception as e:
        log.warn(e)
        raise InvalidJwtToken(msg=six.text_type(e))
    return '登出成功'
Exemple #4
0
def token_refresh_sliding_handler(token):
    """
    采用滑动式JSON网络TOKEN,并在TOKEN的刷新期限尚未到期时返回新的刷新版本。
    """
    ser = TokenRefreshSlidingSerializer(data={'token': token})
    try:
        ser.is_valid(raise_exception=True)
    except AssertionError as e:
        log.info('token校验出错')
        raise InvalidJwtToken(detail='token校验出错')
    res = dict(token=ser.validated_data.get('token'))
    return res
Exemple #5
0
        def inner(request, *args, **kwargs):
            # methods校验
            try:
                assert request.method in methods
            except AssertionError:
                dataformat = get_dataformat(request)
                message = 'Method Not Allowed ({method}): {path}'.format(
                    method=request.method, path=request.path)
                r = dict(status_code=HTTP_405_METHOD_NOT_ALLOWED,
                         detail=message)
                response = HttpResponseNotAllowed(
                    methods, json.dumps(r), content_type=dataformat.content_type)
                log.warn(message)
                return response

            # request.user校验
            try:
                assert login_required
                check_user(request.user, perm)
            except AssertionError:
                pass
            except InsufficientPermissionsError:
                message = 'user get no permission (perm:{perm})'.format(
                    perm=perm)
                log.warn(message)
                raise InsufficientPermissionsError(detail=message)

            # NOTE:推荐
            # request.jwt校验
            try:
                assert jwt_required
                jwt_token_verify_handler(request.jwt)
            except AssertionError:
                pass
            except:
                message = 'user not authentication'
                log.warn(message)
                raise InvalidJwtToken(detail=message)

            return func(request, *args, **kwargs)
Exemple #6
0
def request_token_check(req, func, jwt_required, *args, **kwargs):
    """校验token,获取user信息并添加到request中"""
    res = None
    # 本地环境无需验证登陆
    _is_loc = env == 'loc'
    jwt_required &= not _is_loc
    if _is_loc and req.user.is_anonymous:
        """
        本地环境测试接口时 自动登陆admin账号
        """
        # from apps.accounts.handler import token_obtain_sliding_login_handler
        # token_obtain_sliding_login_handler(req, 'admin', 'test123456')
        # logging.info('本地环境自动登录,登陆的用户为%s' % 'admin')
        pass
    else:
        try:
            assert jwt_required
            # 获取jwt中的user
            token = req.headers._store.get('x-token', (None, None))[1]
            user = Ouser.query_user_from_token(token)
            # 获取session中的user
            from django.contrib.auth import get_user
            _user = get_user(req)
            # 校验user
            assert user.pk == _user.pk, 'session和token不匹配'
            # res = func(req, *args, **kwargs)
            # res.content = json.dumps(
            #     dict(json.loads(res.content)))
        except AssertionError as e:
            msg = six.text_type(e)
            if msg:
                raise InvalidUser('token和session用户不一致')
        except IndexError or TypeError:
            message = 'headers need token'
            log.warn(message)
            raise InvalidJwtToken(detail=message)