本文整理匯總了Python中flask.current_app.secret_key方法的典型用法代碼示例。如果您正苦於以下問題:Python current_app.secret_key方法的具體用法?Python current_app.secret_key怎麽用?Python current_app.secret_key使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.current_app
的用法示例。
在下文中一共展示了current_app.secret_key方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: reset_session
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def reset_session():
global session, processes
current_app.config["JSON_SORT_KEYS"] = False
current_app.secret_key = "xxxrrr"
session.clear()
session["projects"] = projects
session["options"] = ["archieml"]
session["contribute"] = {}
sbx_content = current_app.config.get("SANDBOX_CONTENT")
if sbx_content is not None:
session["sbx_content"] = sbx_content
session["jupyter_url"] = current_app.config.get("JUPYTER_URL")
if not current_app.config.get("START_JUPYTER") and "NotebookProcess" in processes:
processes.pop("NotebookProcess")
if not current_app.config.get("START_MONGODB") and "MongodProcess" in processes:
processes.pop("MongodProcess")
stop_processes()
start_processes()
for suffix in ["_in.txt", "_out.txt"]:
filepath = default_mpfile_path.replace(".txt", suffix)
if os.path.exists(filepath):
os.remove(filepath)
示例2: auth_required
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def auth_required(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated:
token = request.headers.get('token', None)
if token:
try:
user = Users.verify_auth_token(current_app.secret_key, token)
request.api_user = user
except SignatureExpired:
abort(401, 'Signature Expired')
except BadSignature:
abort(401, 'Token did not match')
except Exception:
abort(401, 'Unknown error')
else:
abort(400, 'Missing token')
return func(*args, **kwargs)
return decorated_view
示例3: secret_key
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def secret_key(self) -> str:
return current_app.secret_key
# - request payload -
示例4: generate_csrf
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def generate_csrf(secret_key=None, time_limit=None):
"""Generate csrf token code.
:param secret_key: A secret key for mixing in the token,
default is Flask.secret_key.
:param time_limit: Token valid in the time limit,
default is 3600s.
"""
if not secret_key:
secret_key = current_app.config.get(
'WTF_CSRF_SECRET_KEY', current_app.secret_key
)
if not secret_key:
raise Exception('Must provide secret_key to use csrf.')
if time_limit is None:
time_limit = current_app.config.get('WTF_CSRF_TIME_LIMIT', 3600)
if 'csrf_token' not in session:
session['csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
if time_limit:
expires = int(time.time() + time_limit)
csrf_build = '%s%s' % (session['csrf_token'], expires)
else:
expires = ''
csrf_build = session['csrf_token']
hmac_csrf = hmac.new(
to_bytes(secret_key),
to_bytes(csrf_build),
digestmod=hashlib.sha1
).hexdigest()
return '%s##%s' % (expires, hmac_csrf)
示例5: api_key_required
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def api_key_required(request=None, action=None):
"""
This is a decorator for check_user_pass and check_serial_pass.
It checks, if a policy scope=auth, action=apikeyrequired is set.
If so, the validate request will only performed, if a JWT token is passed
with role=validate.
"""
user_object = request.User
# Get the policies
action = Match.user(g, scope=SCOPE.AUTHZ, action=ACTION.APIKEY, user_object=user_object).policies()
# Do we have a policy?
if action:
# check if we were passed a correct JWT
# Get the Authorization token from the header
auth_token = request.headers.get('PI-Authorization')
if not auth_token:
auth_token = request.headers.get('Authorization')
try:
r = jwt.decode(auth_token, current_app.secret_key, algorithms=['HS256'])
g.logged_in_user = {"username": r.get("username", ""),
"realm": r.get("realm", ""),
"role": r.get("role", "")}
except (AttributeError, jwt.DecodeError):
# PyJWT 1.3.0 raises AttributeError, PyJWT 1.6.4 raises DecodeError.
raise PolicyError("No valid API key was passed.")
role = g.logged_in_user.get("role")
if role != ROLE.VALIDATE:
raise PolicyError("A correct JWT was passed, but it was no API "
"key.")
# If everything went fine, we call the original function
return True
示例6: csrf_secret
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def csrf_secret(self):
return current_app.config.get(
'WTF_CSRF_SECRET_KEY', current_app.secret_key
)
示例7: generate_csrf
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def generate_csrf(secret_key=None, token_key=None):
"""Generate a CSRF token. The token is cached for a request, so multiple
calls to this function will generate the same token.
During testing, it might be useful to access the signed token in
``g.csrf_token`` and the raw token in ``session['csrf_token']``.
:param secret_key: Used to securely sign the token. Default is
``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
:param token_key: Key where token is stored in session for comparision.
Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
"""
secret_key = _get_config(
secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
message='A secret key is required to use CSRF.'
)
field_name = _get_config(
token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
message='A field name is required to use CSRF.'
)
if field_name not in g:
if field_name not in session:
session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()
s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')
setattr(g, field_name, s.dumps(session[field_name]))
return g.get(field_name)
示例8: generate_csrf_token
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def generate_csrf_token(self, csrf_token_field):
return generate_csrf(
secret_key=self.meta.csrf_secret,
token_key=self.meta.csrf_field_name
)
示例9: generate_token
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def generate_token(tenant: Tenant) -> bytes:
s = JSONWebSignatureSerializer(current_app.secret_key, salt="auth")
payload: Dict[str, Any] = {
"access": {str(k): int(v) if v else None for k, v in tenant.access.items()}
}
if getattr(tenant, "user_id", None):
payload["uid"] = str(tenant.user_id)
return s.dumps(payload)
示例10: parse_token
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def parse_token(token: str) -> Optional[Any]:
s = JSONWebSignatureSerializer(current_app.secret_key, salt="auth")
try:
return s.loads(token)
except BadSignature:
return None
示例11: decode_token
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def decode_token(self, token):
"""Decode Authorization token, return None if token invalid"""
key = current_app.secret_key
if key is None:
if current_app.debug:
current_app.logger.debug("app.secret_key not set")
return None
try:
return jwt.decode(
token, key,
algorithms=[self.config["algorithm"]],
options={'require_exp': True}
)
except jwt.InvalidTokenError:
return None
示例12: encode_token
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def encode_token(self, token):
"""Encode Authorization token, return bytes token"""
key = current_app.secret_key
if key is None:
raise RuntimeError(
"please set app.secret_key before generate token")
return jwt.encode(token, key, algorithm=self.config["algorithm"])
示例13: auth_token
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def auth_token():
username = request.json['username']
password = request.json['password']
user = Users.get_user_by_username(username=username)
if user is None:
abort(401, 'User does not exist')
elif not user.verify_password(password):
abort(401, 'Incorrect password')
else:
token = user.generate_auth_token(current_app.secret_key, expiration=3600)
return jsonify(token.decode())
示例14: validate_csrf
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def validate_csrf(data, secret_key=None, time_limit=None):
"""Check if the given data is a valid csrf token.
:param data: The csrf token value to be checked.
:param secret_key: A secret key for mixing in the token,
default is Flask.secret_key.
:param time_limit: Check if the csrf token is expired.
default is True.
"""
if not data or '##' not in data:
return False
try:
expires, hmac_csrf = data.split('##', 1)
except ValueError:
return False # unpack error
if time_limit is None:
time_limit = current_app.config.get('WTF_CSRF_TIME_LIMIT', 3600)
if time_limit:
try:
expires = int(expires)
except ValueError:
return False
now = int(time.time())
if now > expires:
return False
if not secret_key:
secret_key = current_app.config.get(
'WTF_CSRF_SECRET_KEY', current_app.secret_key
)
if 'csrf_token' not in session:
return False
csrf_build = '%s%s' % (session['csrf_token'], expires)
hmac_compare = hmac.new(
to_bytes(secret_key),
to_bytes(csrf_build),
digestmod=hashlib.sha1
).hexdigest()
return safe_str_cmp(hmac_compare, hmac_csrf)
示例15: validate_csrf
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import secret_key [as 別名]
def validate_csrf(data, secret_key=None, time_limit=None, token_key=None):
"""Check if the given data is a valid CSRF token. This compares the given
signed token to the one stored in the session.
:param data: The signed CSRF token to be checked.
:param secret_key: Used to securely sign the token. Default is
``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
:param time_limit: Number of seconds that the token is valid. Default is
``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes).
:param token_key: Key where token is stored in session for comparision.
Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
:raises ValidationError: Contains the reason that validation failed.
.. versionchanged:: 0.14
Raises ``ValidationError`` with a specific error message rather than
returning ``True`` or ``False``.
"""
secret_key = _get_config(
secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
message='A secret key is required to use CSRF.'
)
field_name = _get_config(
token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
message='A field name is required to use CSRF.'
)
time_limit = _get_config(
time_limit, 'WTF_CSRF_TIME_LIMIT', 3600, required=False
)
if not data:
raise ValidationError('The CSRF token is missing.')
if field_name not in session:
raise ValidationError('The CSRF session token is missing.')
s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')
try:
token = s.loads(data, max_age=time_limit)
except SignatureExpired:
raise ValidationError('The CSRF token has expired.')
except BadData:
raise ValidationError('The CSRF token is invalid.')
if not safe_str_cmp(session[field_name], token):
raise ValidationError('The CSRF tokens do not match.')