Esempio n. 1
0
    def get_auth(self):
        """ Support basic auth, bearer token """

        auth = request.authorization  # werkzeug parse authorization header
        if auth is None and request.headers.get('Authorization'):
            # bearer token
            try:
                auth_type, token = request.headers['Authorization'].split(
                    None, 1)
                if isinstance(auth_type,
                              str) and auth_type.lower() == 'bearer':
                    auth_type = 'token'
                    auth = Authorization(auth_type, {'token': token})
                else:
                    raise AuthFailed(field='headers')
            except ValueError:
                # The authorization header is either empty or has no token
                auth = None
        if auth is None and request.args.get('token'):
            auth_type = 'token'
            auth = Authorization(auth_type, {'token': request.args['token']})
        if auth is None and request.form.get('token'):
            auth_type = 'token'
            auth = Authorization(auth_type, {'token': request.form['token']})
        if auth is None:
            raise AuthFailed(field='AuthType')
        if not self.schemas.get(auth.type):
            raise AuthFailed(field='AuthType')
        return auth
Esempio n. 2
0
def parse_authorization_header(value):
    """Parse an HTTP basic/digest authorization header transmitted by the web
    browser.  The return value is either `None` if the header was invalid or
    not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
    object.

    :param value: the authorization header to parse.
    :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
    """
    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'basic':
        try:
            username, password = base64.b64decode(auth_info).split(b':', 1)
        except Exception as e:
            return
        return Authorization('basic', {'username':  bytes_to_wsgi(username),
                                       'password': bytes_to_wsgi(password)})
    elif auth_type == b'digest':
        auth_map = parse_dict_header(auth_info)
        for key in 'username', 'realm', 'nonce', 'uri', 'response':
            if not key in auth_map:
                return
        if 'qop' in auth_map:
            if not auth_map.get('nc') or not auth_map.get('cnonce'):
                return
        return Authorization('digest', auth_map)
Esempio n. 3
0
        def decorated(*args, **kwargs):
            auth = request.authorization
            if auth is None and 'Authorization' in request.headers:
                # Flask/Werkzeug do not recognize any authentication types
                # other than Basic or Digest, so here we parse the header by
                # hand
                try:
                    auth_type, token = request.headers['Authorization'].split(
                        None, 1)
                    auth = Authorization(auth_type, {'token': token})
                except ValueError:
                    # The Authorization header is either empty or has no token
                    pass

            # if the auth type does not match, we act as if there is no auth
            # this is better than failing directly, as it allows the callback
            # to handle special cases, like supporting multiple auth types
            if auth is not None and auth.type.lower() != self.scheme.lower():
                auth = None

            # Flask normally handles OPTIONS requests on its own, but in the
            # case it is configured to forward those to the application, we
            # need to ignore authentication headers and let the request through
            # to avoid unwanted interactions with CORS.
            if request.method != 'OPTIONS':  # pragma: no cover
                if auth and auth.username:
                    password = self.get_password_callback(auth.username)
                else:
                    password = None
                if not self.authenticate(auth, password):
                    return self.auth_error_callback()
            return f(*args, **kwargs)
Esempio n. 4
0
def parse_authorization_header(value):
    """Parse an HTTP basic/digest authorization header transmitted by the web
    browser.  The return value is either `None` if the header was invalid or
    not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
    object.

    :param value: the authorization header to parse.
    :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
    """
    if not value:
        return
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return
    if auth_type == 'basic':
        try:
            username, password = auth_info.decode('base64').split(':', 1)
        except Exception, e:
            return
        return Authorization('basic', {
            'username': username,
            'password': password
        })
Esempio n. 5
0
    def get_auth(self):
        '''使BasicAuth可以自定义scheme
        '''
        auth = None
        if 'Authorization' in request.headers:
            # Flask/Werkzeug do not recognize any authentication types
            # other than Basic or Digest, so here we parse the header by
            # hand
            try:
                auth_type, auth_str = request.headers['Authorization'].split(
                    None, 1)
                # print(auth_type, auth_str)
                username, password = base64.b64decode(auth_str).decode().split(
                    ':', 1)
                auth = Authorization(auth_type, {
                    'username': username,
                    'password': password
                })
            except ValueError:
                # The Authorization header is either empty or has no token
                pass

        # if the auth type does not match, we act as if there is no auth
        # this is better than failing directly, as it allows the callback
        # to handle special cases, like supporting multiple auth types
        if auth is not None and auth.type.lower() != self.scheme.lower():
            auth = None
        return auth
Esempio n. 6
0
def test_auth_object():
    builder = EnvironBuilder(auth=Authorization("digest", {
        "username": "******",
        "password": "******"
    }))
    request = builder.get_request()
    assert request.headers["Authorization"].startswith("Digest ")
Esempio n. 7
0
 def get_auth(self):
     auth = None
     if self.header is None or self.header == 'Authorization':
         auth = request.authorization
         if auth is None and 'Authorization' in request.headers:
             try:
                 auth_type, token = request.headers['Authorization'].split(
                     None, 1)
                 auth = Authorization(auth_type, {'token': token})
             except (ValueError, KeyError):
                 pass
     elif self.header in request.headers:
         auth = Authorization(self.scheme,
                              {'token': request.headers[self.header]})
     if auth is not None and auth.type.lower() != self.scheme.lower():
         auth = None
     return auth
Esempio n. 8
0
def parse_authorization_header(value):
    """Parse an HTTP basic/digest authorization header transmitted by the web
    browser.  The return value is either `None` if the header was invalid or
    not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
    object.

    :param value: the authorization header to parse.
    :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
    """
    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"basic":
        try:
            username, password = base64.b64decode(auth_info).split(b":", 1)
        except Exception:
            return
        return Authorization(
            "basic",
            {
                "username": bytes_to_wsgi(username),
                "password": bytes_to_wsgi(password)
            },
        )
    elif auth_type == b"digest":
        auth_map = parse_dict_header(auth_info)
        for key in "username", "realm", "nonce", "uri", "response":
            if key not in auth_map:
                return
        if "qop" in auth_map:
            if not auth_map.get("nc") or not auth_map.get("cnonce"):
                return
        return Authorization("digest", auth_map)
Esempio n. 9
0
 def get_auth_from_caps(self):
     try:
         body = loads(request.data)
     except ValueError:
         return anonymous
     try:
         caps = body['desiredCapabilities']
     except KeyError:
         return anonymous
     user = caps.get("user", None)
     if user is None:
         return anonymous
     token = caps.get("token", None)
     return Authorization('basic', {"username": user, "password": token})
Esempio n. 10
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),
                })
    elif auth_type == b'token':
        return Authorization('token', {'token': auth_info})
Esempio n. 11
0
 def get_auth(self):
     # this version of the Authorization header parser is more flexible
     # than Werkzeug's, as it also accepts other schemes besides "Basic"
     header = self.header or 'Authorization'
     if header not in request.headers:
         return None
     value = request.headers[header].encode('utf-8')
     try:
         scheme, credentials = value.split(b' ', 1)
         username, password = b64decode(credentials).split(b':', 1)
     except (ValueError, TypeError):
         return None
     return Authorization(
         scheme, {'username': username.decode('utf-8'),
                  'password': password.decode('utf-8')})
Esempio n. 12
0
def parse_authorization_header(value):
    if not value:
        return
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return

    if auth_type == 'basic':
        try:
            username, password = auth_info.decode('base64').split(':', 1)
        except Exception as e:
            return

        return Authorization('basic', {'username': username,
         'password': password})
    if auth_type == 'digest':
        auth_map = parse_dict_header(auth_info)
        for key in ('username', 'realm', 'nonce', 'uri', 'nc', 'cnonce', 'response'):
            if key not in auth_map:
                return

        return Authorization('digest', auth_map)
Esempio n. 13
0
def get_auth():
    auth = request.authorization
    if auth is None and 'Authorization' in request.headers:
        # Flask/Werkzeug do not recognize any authentication types
        # other than Basic or Digest, so here we parse the header by
        # hand
        try:
            auth_type, token = request.headers['Authorization'].split(
                None, 1)
            auth = Authorization(auth_type, {'token': token})
        except ValueError:
            # The Authorization header is either empty or has no token
            pass

    return auth
Esempio n. 14
0
 def authorization(self):
     authorization = super(Request, self).authorization
     if authorization is None:
         header = self.environ.get('HTTP_AUTHORIZATION')
         auth = parse_authorization_header(header)
         if auth and auth.type == 'token':
             database_name = self.view_args.get('database_name')
             if not database_name:
                 return None
             user_id, party_id = security.check_token(
                 database_name, auth.get('token'))
             return Authorization('token', {
                     'token': auth.get('token'),
                     'user_id': user_id,
                     'party_id': party_id
                 })
         else:
             return auth
     return authorization
Esempio n. 15
0
    def get_auth(self):
        auth = request.authorization
        if auth is None and 'Authorization' in request.headers:
            # Flask/Werkzeug do not recognize any authentication types
            # other than Basic or Digest, so here we parse the header by
            # hand
            try:
                auth_type, token = request.headers['Authorization'].split(
                    None, 1)
                auth = Authorization(auth_type, {'token': token})
            except ValueError:
                # The Authorization header is either empty or has no token
                pass

        # if the auth type does not match, we act as if there is no auth
        # this is better than failing directly, as it allows the callback
        # to handle special cases, like supporting multiple auth types
        if auth is not None and auth.type.lower() != self.scheme.lower():
            auth = None

        return auth
Esempio n. 16
0
 def decorator(*args, **kwargs):
     auth = request.authorization
     if auth is None and 'Authorization' in request.headers:
         try:
             auth_type, token = request.headers['Authorization'].split(
                 None, 1)
             auth = Authorization(auth_type, {'token': token})
         except ValueError:
             pass
     if auth is None or auth.type.lower() != 'basic':
         return pack_resp('Unauthorized.', 401)
     user = User.isExist(auth.username)
     if user and user.verify_password(auth.password):
         pass
     else:
         print(auth.username)
         user = User.verify_auth_token(auth.username)
         if not user:
             return pack_resp('Unauthorized.', 401)
     g.user = user
     return func(*args, **kwargs)
Esempio n. 17
0
def make_test_headers_path_and_query_string(
    app: "Quart",
    path: str,
    headers: Optional[Union[dict, Headers]] = None,
    query_string: Optional[dict] = None,
    auth: Optional[Union[Authorization, Tuple[str, str]]] = None,
) -> Tuple[Headers, str, bytes]:
    """Make the headers and path with defaults for testing.

    Arguments:
        app: The application to test against.
        path: The path to request. If the query_string argument is not
            defined this argument will be partitioned on a '?' with
            the following part being considered the query_string.
        headers: Initial headers to send.
        query_string: To send as a dictionary, alternatively the
            query_string can be determined from the path.
    """
    if headers is None:
        headers = Headers()
    elif isinstance(headers, Headers):
        headers = headers
    elif headers is not None:
        headers = Headers(headers)

    if auth is not None:
        if isinstance(auth, tuple):
            auth = Authorization("basic", {"username": auth[0], "password": auth[1]})
        headers.setdefault("Authorization", auth.to_header())

    headers.setdefault("User-Agent", "Quart")
    headers.setdefault("host", app.config["SERVER_NAME"] or "localhost")
    if "?" in path and query_string is not None:
        raise ValueError("Query string is defined in the path and as an argument")
    if query_string is None:
        path, _, query_string_raw = path.partition("?")
    else:
        query_string_raw = urlencode(query_string, doseq=True)
    query_string_bytes = query_string_raw.encode("ascii")
    return headers, unquote(path), query_string_bytes
Esempio n. 18
0
        def decorated_function(*args, **kwargs):
            auth = request.authorization
            token = None
            auth_type = None
            # link jwt: https://jwt.io/introduction/
            if auth is None and 'Authorization' in request.headers:
                # Flask/Werkzeug không công nhận bất kỳ loại authentication
                # nào khác ngoài Basic or Digest, vì vậy cần chuyển đối tượng
                # bằng tay
                try:
                    auth_type, token = request.headers['Authorization'].split(
                        None, 1)
                    local_auth_type = TYPICALLY.DIGEST if auth_type == TYPICALLY.BEARER else auth_type
                    auth = Authorization(local_auth_type, {'token': token})
                except ValueError:
                    # Authorization header là rỗng hoặc không có mã thông báo
                    pass

            # nếu kiểu auth không khớp, chúng ta hành động như thể không có auth
            # này là tốt hơn so với thất bại trực tiếp, vì nó cho phép callback
            # để xử lý các trường hợp đặc biệt, như hỗ trợ nhiều kiểu auth
            if auth is not None and auth.type.lower() in self.scheme:
                auth = None

            # Flask thường giải quyết các yêu cầu của OPTIONS riêng, nhưng trong
            # trường hợp nó được cấu hình để chuyển tiếp các ứng dụng, chúng tôi
            # cần bỏ qua tiêu đề xác thực và để cho yêu cầu thông qua
            # để tránh những tương tác không mong muốn với CORS.
            if request.method != 'OPTIONS':  # pragma: no cover
                if auth:
                    if not self.authenticate(str(auth_type), token, method):
                        # Xóa bộ đệm TCP nhận được dữ liệu đang chờ xử lý
                        print(
                            'authenticate for token %s api_name  %s error %s' %
                            (token, method, str(request.data)[0]))
                        return self.auth_error_callback()
                else:
                    return self.auth_error_callback()
            return f(*args, **kwargs)
Esempio n. 19
0
def parse_authorization_header(value):
    if not value:
        return
    if not isinstance(value, bytes):
        value = value.encode('latin1')
    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': username.decode("latin1"),
                'userid': userid,
                'session': session.decode("latin1"),
            })
Esempio n. 20
0
 def get_auth(self):
     if 'X-API-Key' in request.headers:
         return Authorization('api_key',
                              {'token': request.headers['X-API-Key']})
     return None
Esempio n. 21
0
            username, password = auth_info.decode('base64').split(':', 1)
        except Exception, e:
            return
        return Authorization('basic', {
            'username': username,
            'password': password
        })
    elif auth_type == 'digest':
        auth_map = parse_dict_header(auth_info)
        for key in 'username', 'realm', 'nonce', 'uri', 'response':
            if not key in auth_map:
                return
        if 'qop' in auth_map:
            if not auth_map.get('nc') or not auth_map.get('cnonce'):
                return
        return Authorization('digest', auth_map)


def parse_www_authenticate_header(value, on_update=None):
    """Parse an HTTP WWW-Authenticate header into a
    :class:`~werkzeug.datastructures.WWWAuthenticate` object.

    :param value: a WWW-Authenticate header to parse.
    :param on_update: an optional callable that is called every time a value
                      on the :class:`~werkzeug.datastructures.WWWAuthenticate`
                      object is changed.
    :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
    """
    if not value:
        return WWWAuthenticate(on_update=on_update)
    try:
Esempio n. 22
0
# coding: utf-8

from flask.ext.httpauth import HTTPBasicAuth
from functools import wraps
from flask import request, make_response, current_app
from json import loads, dumps
from werkzeug.datastructures import Authorization

anonymous = Authorization('basic', {'username': '******', 'password': None})


def user_exists(token):
    return current_app.database.get_user(token=token)


def user_not_found():
    error_msg = {
        "status": 1,
        "value": "User not found in service",
        "message": "Please register in service"
    }
    res = make_response(dumps(error_msg))
    res.status_code = 401
    return res


def authentificate_failed():
    error_msg = {
        "status": 1,
        "value": "Authentification was failed",
        "message": "Please try again"