當前位置: 首頁>>代碼示例>>Python>>正文


Python request.authorization方法代碼示例

本文整理匯總了Python中flask.request.authorization方法的典型用法代碼示例。如果您正苦於以下問題:Python request.authorization方法的具體用法?Python request.authorization怎麽用?Python request.authorization使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask.request的用法示例。


在下文中一共展示了request.authorization方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: check_authentication_response

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def check_authentication_response() -> Union[Response, None]:
    """
    Return the response as per the authentication requirements.
    """
    if get_authentication():
        if get_token():
            token = check_token(request, get_session())
            if not token:
                if request.authorization is None:
                    return failed_authentication(False)
                else:
                    return verify_user()
        elif request.authorization is None:
            return failed_authentication(False)
        else:
            return verify_user()
    else:
        return None 
開發者ID:HTTP-APIs,項目名稱:hydrus,代碼行數:20,代碼來源:auth.py

示例2: exit_maintenance

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def exit_maintenance():
    config = get_config()
    auth = request.authorization
    if auth \
            and auth.username in config.MAINTENANCE_CREDENTIALS \
            and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
        try:
            os.remove(config.MAINTENANCE_FILE)  # remove maintenance file
        except OSError:
            return 'Not in maintenance mode. Ignore command.'
        open(os.path.join(os.getcwd(), 'reload'), "w+").close()  # uwsgi reload
        return 'success'
    else:
        return Response(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials', 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'}) 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:19,代碼來源:views_main.py

示例3: get_permissions

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def get_permissions():
    """
    get the permissions for the current user (if logged in)
    or the default permissions (if not logged in).
    """
    auth = request.authorization
    if auth:
        # http basic auth header present
        permissions = lookup_permissions(auth.password)
    elif 'token' in request.values:
        # token present in query args or post form (can be used by cli clients)
        permissions = lookup_permissions(request.values['token'])
    else:
        # look into session, login might have put something there
        permissions = session.get(PERMISSIONS)
    if permissions is None:
        permissions = current_app.config['DEFAULT_PERMISSIONS']
    permissions = set(permissions.split(','))
    return permissions 
開發者ID:bepasty,項目名稱:bepasty-server,代碼行數:21,代碼來源:permissions.py

示例4: ldap_protected

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def ldap_protected(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    # this can be configured and taken from elsewhere
    # path, method, groups_allowed (users in Allowed Users group will be allowed to access / with a GET method)
    authorization_config = {
      "/": {
         "GET": ["Allowed Users"]
      }
    }

    auth_endpoint_rule = authorization_config.get(request.url_rule.rule)
    if auth_endpoint_rule is not None:
      groups_allowed = auth_endpoint_rule.get(request.method) or True
    else:
      groups_allowed = True
    
    auth = request.authorization
    if not ('username' in session):
      if not auth or not ldap_authenticate(request,auth.username, auth.password, groups_allowed):
        return auth_401()
    else:
      auth_logger.debug("%s calling %s endpoint"%(session['username'],f.__name__))
    return f(*args, **kwargs)
  return decorated 
開發者ID:bbotte,項目名稱:bbotte.github.io,代碼行數:27,代碼來源:auth_ldap3.py

示例5: requires_auth

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

#@app.route('/regex', methods = ["POST"])
#def submit_name_regex():
#
    #request.getdata()
#    request_json = json.loads(request.data.decode('utf-8'))
#    regex = request_json["regex"]
#    print(request_json)
#    subprocess.Popen("/usr/bin/nohup find /home/ubuntu/all_unzipped -type f -exec /bin/grep " + regex + " {} + > /var/www/html/results/" + b58encode(regex).decode('utf-8'), shell=True)
#    return "h'ok"

#@app.route("/status") 
開發者ID:acaceres2176,項目名稱:scylla,代碼行數:22,代碼來源:scylla.py

示例6: requires_auth

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # Favicon is the little icon associated with a domain in a web browser. Browsers issue a request for the
        # resource /favicon.ico alongside any other HTTP request which pollutes the logs with lots of 404 Not Found logs
        # because usually the favicon cannot be resolved. This tells the browser to go away; there is no favicon here.
        if request.path == "/favicon.ico":
            return Response(status=403)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return unauthorized()

        return f(*args, **kwargs)

    return decorated 
開發者ID:datawire,項目名稱:ambassador-auth-httpbasic,代碼行數:18,代碼來源:app.py

示例7: sensor_auth

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def sensor_auth(view):
    """
    Authenticates the view, allowing access if user
    is authenticated or if requesting from a sensor.
    """
    @wraps(view)
    def wrapped_view(*args, **kwargs):
        if current_user and current_user.is_authenticated:
            return view(*args, **kwargs)
        elif request.authorization:
            auth = request.authorization
            if auth and auth.get('username') == auth.get('password') and\
               Sensor.query.filter_by(uuid=auth.get('username')).count() == 1:
                return view(*args, **kwargs)
        return error_response(errors.API_NOT_AUTHORIZED, 401)
    return wrapped_view 
開發者ID:CommunityHoneyNetwork,項目名稱:CHN-Server,代碼行數:18,代碼來源:decorators.py

示例8: extract_params

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def extract_params():
    """Extract request params."""

    uri = _get_uri_from_request(request)
    http_method = request.method
    headers = dict(request.headers)
    if 'wsgi.input' in headers:
        del headers['wsgi.input']
    if 'wsgi.errors' in headers:
        del headers['wsgi.errors']
    # Werkzeug, and subsequently Flask provide a safe Authorization header
    # parsing, so we just replace the Authorization header with the extraced
    # info if it was successfully parsed.
    if request.authorization:
        headers['Authorization'] = request.authorization

    body = request.form.to_dict()
    return uri, http_method, body, headers 
開發者ID:gita,項目名稱:BhagavadGita,代碼行數:20,代碼來源:utils.py

示例9: _get_kms_auth_data

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def _get_kms_auth_data():
    data = {}
    auth = request.authorization
    headers = request.headers
    if auth and auth.get('username'):
        if not auth.get('password'):
            raise AuthenticationError('No password provided via basic auth.')
        data['username'] = auth['username']
        data['token'] = auth['password']
    elif 'X-Auth-Token' in headers and 'X-Auth-From' in headers:
        if not headers.get('X-Auth-Token'):
            raise AuthenticationError(
                'No X-Auth-Token provided via auth headers.'
            )
        data['username'] = headers['X-Auth-From']
        data['token'] = headers['X-Auth-Token']
    return data 
開發者ID:lyft,項目名稱:confidant,代碼行數:19,代碼來源:__init__.py

示例10: _authenticate_user

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def _authenticate_user(self):
        """Authenticate a user using Storehouse."""
        username = request.authorization["username"]
        password = request.authorization["password"].encode()
        try:
            user = self._find_user(username)[0].get("data")
            if user.get("password") != hashlib.sha512(password).hexdigest():
                raise KeyError
            time_exp = datetime.datetime.utcnow() + datetime.timedelta(
                minutes=TOKEN_EXPIRATION_MINUTES
            )
            token = self._generate_token(username, time_exp)
            return {"token": token.decode()}, HTTPStatus.OK.value
        except (AttributeError, KeyError) as exc:
            result = f"Incorrect username or password: {exc}"
            return result, HTTPStatus.UNAUTHORIZED.value 
開發者ID:kytos,項目名稱:kytos,代碼行數:18,代碼來源:auth.py

示例11: check_access

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def check_access():
    if not current_node:
        return 'Unknown psdash node specified', 404

    allowed_remote_addrs = current_app.config.get('PSDASH_ALLOWED_REMOTE_ADDRESSES')
    if allowed_remote_addrs:
        if request.remote_addr not in allowed_remote_addrs:
            current_app.logger.info(
                'Returning 401 for client %s as address is not in allowed addresses.',
                request.remote_addr
            )
            current_app.logger.debug('Allowed addresses: %s', allowed_remote_addrs)
            return 'Access denied', 401

    username = current_app.config.get('PSDASH_AUTH_USERNAME')
    password = current_app.config.get('PSDASH_AUTH_PASSWORD')
    if username and password:
        auth = request.authorization
        if not auth or auth.username != username or auth.password != password:
            return Response(
                'Access deined',
                401,
                {'WWW-Authenticate': 'Basic realm="psDash login required"'}
            ) 
開發者ID:Jahaja,項目名稱:psdash,代碼行數:26,代碼來源:web.py

示例12: expect_basic_auth

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def expect_basic_auth():
    auth = request.authorization

    if auth is None:
        return jsonify({"status": "No authorisation"}), 403

    if auth.type == "basic":
        if auth.username == "fakeuser" and auth.password == "fakepass":
            return (
                jsonify(
                    {
                        "auth_type": auth.type,
                        "auth_user": auth.username,
                        "auth_pass": auth.password,
                    }
                ),
                200,
            )
        else:
            return jsonify({"error": "Wrong username/password"}), 401
    else:
        return jsonify({"error": "unrecognised auth type"}), 403 
開發者ID:taverntesting,項目名稱:tavern,代碼行數:24,代碼來源:server.py

示例13: before_request

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def before_request(self) -> Optional[Response]:
        """Determine if a user is allowed to view this route."""
        auth = request.authorization
        if (
            not auth
            or auth.username is None
            or auth.password is None
            or not self._check_auth(auth.username, auth.password)
        ):
            return Response(
                'Could not verify your access level for that URL.\n'
                'You have to login with proper credentials',
                401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'},
            )
        session['logged_in'] = auth.username
        return None  # pylint wants this return statement 
開發者ID:jwkvam,項目名稱:bowtie,代碼行數:19,代碼來源:auth.py

示例14: get

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def get(self):
        if (not self.auth_source.verify_connect()):
            return make_response(jsonify({'message': 'Unauthorized access'}), 403)

        # First check how many tokens the user has
        username = request.authorization["username"]
        for user in self.data_source.users:
            if username == user.username:
                count = len(user.tokens)
                if count >= self.data_source.max_tokens:
                    return make_response(jsonify({'token': '', 'message': 'maximum amount of tokens generated'}), 200)
                lst = [random.choice(string.ascii_letters + string.digits)
                       for n in range(128)]
                str_ = "".join(lst)
                user.tokens[uuid.uuid1()] = [str_, time.time()]
                return make_response(jsonify({'message': 'success', 'token': str_}), 200)
        # We should now find and modify the file

        return make_response(jsonify({'token': '', 'message': 'token gen failed'}), 200) 
開發者ID:FSecureLABS,項目名稱:captcha22,代碼行數:21,代碼來源:server.py

示例15: enter_maintenance

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import authorization [as 別名]
def enter_maintenance():
    config = get_config()
    auth = request.authorization
    if auth \
            and auth.username in config.MAINTENANCE_CREDENTIALS \
            and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
        open(config.MAINTENANCE_FILE, "w+").close()  # maintenance file
        open(os.path.join(os.getcwd(), 'reload'), "w+").close()  # uwsgi reload
        return 'success'
    else:
        return Response(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials', 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'}) 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:16,代碼來源:views_main.py


注:本文中的flask.request.authorization方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。