Ejemplo n.º 1
0
        def wrapper(request, *args, **kwargs):
            pool = Pool()
            UserApplication = pool.get('res.user.application')

            authorization = wsgi_to_bytes(request.headers['Authorization'])
            try:
                auth_type, auth_info = authorization.split(None, 1)
                auth_type = auth_type.lower()
            except ValueError:
                abort(401)
            if auth_type != b'bearer':
                abort(403)

            application = UserApplication.check(auth_info, name)
            if not application:
                abort(403)
            transaction = Transaction()
            # TODO language
            with transaction.set_user(application.user.id), \
                    transaction.set_context(_check_access=True):
                try:
                    response = func(request, *args, **kwargs)
                except Exception, e:
                    if isinstance(e, HTTPException):
                        raise
                    logger.error('%s', request, exc_info=True)
                    abort(500, e)
Ejemplo n.º 2
0
        def wrapper(request, *args, **kwargs):
            pool = Pool()
            UserApplication = pool.get('res.user.application')

            authorization = wsgi_to_bytes(request.headers['Authorization'])
            try:
                auth_type, auth_info = authorization.split(None, 1)
                auth_type = auth_type.lower()
            except ValueError:
                abort(HTTPStatus.UNAUTHORIZED)
            if auth_type != b'bearer':
                abort(HTTPStatus.FORBIDDEN)

            application = UserApplication.check(bytes_to_wsgi(auth_info), name)
            if not application:
                abort(HTTPStatus.FORBIDDEN)
            transaction = Transaction()
            # TODO language
            with transaction.set_user(application.user.id), \
                    transaction.set_context(_check_access=True):
                try:
                    response = func(request, *args, **kwargs)
                except Exception as e:
                    if isinstance(e, HTTPException):
                        raise
                    logger.error('%s', request, exc_info=True)
                    abort(HTTPStatus.INTERNAL_SERVER_ERROR, e)
            if not isinstance(response, Response) and json:
                response = Response(json_.dumps(response, cls=JSONEncoder),
                                    content_type='application/json')
            return response
Ejemplo n.º 3
0
def parse_authorization_header(header):
    """
    Parses the HTTP Auth Header to a JWT Token
    Args:
        header: Authorization header of the HTTP Request
    Examples:
        request.headers['Authorization'] or something same
    Returns:
        Valid JWT token
    """
    if not header:
        return None
    value = wsgi_to_bytes(header)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        # Fallback for old versions
        auth_type = b"bearer"
        auth_info = value

    if auth_type == b"basic":
        try:
            username, password = base64.b64decode(auth_info).split(b":", 1)

            with current_app.app_context():
                username = to_unicode(username, "utf-8")
                password = to_unicode(password, "utf-8")

                user_manager: UserManager = UserManager(
                    current_app.database_manager)
                auth_module = AuthModule(
                    SystemSettingsReader(current_app.database_manager))

                try:
                    user_instance = auth_module.login(user_manager, username,
                                                      password)
                except Exception as e:
                    return None
                if user_instance:
                    tg = TokenGenerator(current_app.database_manager)
                    return tg.generate_token(payload={
                        'user': {
                            'public_id': user_instance.get_public_id()
                        }
                    })
                else:
                    return None
        except Exception:
            return None

    if auth_type == b"bearer":
        try:
            tv = TokenValidator()
            decoded_token = tv.decode_token(auth_info)
            tv.validate_token(decoded_token)
            return auth_info
        except Exception:
            return None
    return None
Ejemplo n.º 4
0
def parse_authorization_header(value):
    if not value:
        return
    value = wsgi_to_bytes(value)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return
    if auth_type == b'session':
        try:
            username, userid, session = base64.b64decode(auth_info).split(
                b':', 3)
            userid = int(userid)
        except Exception:
            return
        return Authorization(
            'session', {
                'username': bytes_to_wsgi(username),
                'userid': userid,
                'session': bytes_to_wsgi(session),
            })
    # JMO: the initial implementation used 'token',
    # but the IETF specifies 'Bearer'
    # (cf https://datatracker.ietf.org/doc/html/rfc6750#section-2.1 ).
    # So, we allow both to maintain compatibility with previous uses,
    # and be compatible with standard HTTP clients.
    elif auth_type in (b'token', b'bearer'):
        return Authorization('token', {'token': bytes_to_wsgi(auth_info)})
Ejemplo n.º 5
0
def parse_jwt_header(value):
    """Parse an HTTP bearer authorization header transmitted by the web
    browser.  Try to parse this JWT token, return parsed object
    or None if header is invalid.

    :param value: the authorization header to parse.
    :return: parsed JWT token as a dict object or `None`.
    """
    if not value:
        return None
    value = wsgi_to_bytes(value)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return
    if auth_type == b'bearer':
        return jwt.decode(auth_info, algorithms=['RS256'], verify=False)
Ejemplo n.º 6
0
def get_authorization_header():
    """
    Return request's 'Authorization:' header as
    a two-tuple of (type, info).
    """
    header = request.environ.get('HTTP_AUTHORIZATION')

    if not header:
        return None

    header = wsgi_to_bytes(header)

    try:
        auth_type, auth_info = header.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return None

    return auth_type, auth_info
Ejemplo n.º 7
0
def get_authorization_header():
    """
    Return request's 'Authorization:' header as
    a two-tuple of (type, info).
    """
    header = request.environ.get('HTTP_AUTHORIZATION')

    if not header:
        return None

    header = wsgi_to_bytes(header)

    try:
        auth_type, auth_info = header.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return None

    return auth_type, auth_info
Ejemplo n.º 8
0
def parse_authorization_header(value):
    if not value:
        return
    value = wsgi_to_bytes(value)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return
    if auth_type == b'session':
        try:
            username, userid, session = base64.b64decode(auth_info).split(
                b':', 3)
            userid = int(userid)
        except Exception:
            return
        return Authorization('session', {
                'username': bytes_to_wsgi(username),
                'userid': userid,
                'session': bytes_to_wsgi(session),
                })
Ejemplo n.º 9
0
def get_current_session_id_and_token():
    auth_header = request.environ.get('HTTP_AUTHORIZATION')
    auth_token = ""

    if auth_header:
        value = http.wsgi_to_bytes(auth_header)
        try:
            auth_type, auth_token = value.split(None, 1)
            auth_type = auth_type.lower()

            if auth_type != b'bearer':
                return None

        except ValueError:
            logging.warning("Invalid Auth header")
            return None
    elif "rbbtoken" in request.cookies:
        # Session token in cookie needs to be supported for embedded media links
        auth_token = urllib.parse.unquote(request.cookies['rbbtoken']).encode('latin1')
    else:
        return None

    return unpack_token(base64.b64decode(auth_token))