当前位置: 首页>>代码示例>>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;未经允许,请勿转载。