本文整理匯總了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
示例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"'})
示例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
示例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
示例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")
示例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
示例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
示例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
示例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
示例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
示例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"'}
)
示例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
示例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
示例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)
示例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"'})