本文整理匯總了Python中django.conf.settings.SECRET_KEY屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.SECRET_KEY屬性的具體用法?Python settings.SECRET_KEY怎麽用?Python settings.SECRET_KEY使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類django.conf.settings
的用法示例。
在下文中一共展示了settings.SECRET_KEY屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: generate_password
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def generate_password(input_seed):
"""
Generate some hard-to-guess but deterministic password.
(deterministic so we have some hope of password recovery if something gets lost)
Note: settings.SECRET_KEY is different (and actually secret) in production.
"""
# generate seed integer
secret = settings.SECRET_KEY
seed_str = '_'.join([secret, input_seed, PW_SERIES, secret])
h = hashlib.new('sha512')
h.update(seed_str.encode('utf8'))
seed = int(h.hexdigest(), 16)
# use seed to pick characters: one letter, one digit, one punctuation, length 6-10
letter, seed = _choose_from(LETTERS, seed)
digit, seed = _choose_from(DIGITS, seed)
punc, seed = _choose_from(PUNCTUATION, seed)
pw = letter + digit + punc
for i in range(7):
c, seed = _choose_from(ALL_CHARS, seed)
pw += c
return pw
示例2: salted_hmac
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
示例3: get_random_string
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
示例4: _authenticate_credentials
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def _authenticate_credentials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except:
msg = 'Invalid authentication. Could not decode token.'
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get(pk=payload['id'])
except User.DoesNotExist:
msg = 'No user matching this token was found.'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = 'This user has been deactivated.'
raise exceptions.AuthenticationFailed(msg)
return (user, token)
示例5: salted_hmac
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def salted_hmac(key_salt, value, secret=None):
"""
Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1(key_salt + secret).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
示例6: get_random_string
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
).digest()
)
return ''.join(random.choice(allowed_chars) for i in range(length))
示例7: test_generate_api_token
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def test_generate_api_token(self):
token = self.profile.generate_api_token()
self.assertIsInstance(token, str)
self.assertIsInstance(self.profile.api_token, str)
user_id, raw_token = struct.unpack('>I32s', base64.urlsafe_b64decode(token))
self.assertEqual(self.users['normal'].id, user_id)
self.assertEqual(len(raw_token), 32)
self.assertTrue(
hmac.compare_digest(
hmac.new(force_bytes(settings.SECRET_KEY), msg=force_bytes(raw_token), digestmod='sha256').hexdigest(),
self.profile.api_token,
),
)
示例8: adduser
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def adduser(apps, schema_editor):
if os.getenv('CI'):
return
User = apps.get_model(*settings.AUTH_USER_MODEL.split('.'))
if settings.SECRET_KEY != 'notsecret':
return
user, created = User.objects.get_or_create(
username='test',
is_superuser=True,
is_active=True,
)
if created:
user.password = make_password('test')
user.save()
示例9: salted_hmac
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1((key_salt + secret).encode('utf-8')).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
示例10: get_random_string
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join([random.choice(allowed_chars) for i in range(length)])
示例11: _authenticate_credentials
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def _authenticate_credentials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except Exception as e:
msg = 'Invalid authentication. Could not decode token.'
print(e)
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get(pk=payload['id'])
except User.DoesNotExist:
msg = 'No user matching this token was found.'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = 'This user has been deactivated.'
raise exceptions.AuthenticationFailed(msg)
return user, token
示例12: auth_return
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def auth_return(request):
if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']),
request.user.username):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.GET)
credential = TwitchCredentials.from_json(credential.to_json())
http = httplib2.Http()
http = credential.authorize(http)
resp, data = http.request("https://api.twitch.tv/kraken/user")
data = json.loads(data)
print data
ac = TwitchAppCreds(user=request.user, label=data['name'])
ac.save()
return HttpResponseRedirect("/accounts/")
return render(request, "twitchaccount/label.html", data)
示例13: auth_return
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def auth_return(request):
if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']),
request.user.username):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.GET)
http = httplib2.Http()
http = credential.authorize(http)
resp, data = http.request("https://api.patreon.com/oauth2/api/current_user")
data = json.loads(data)
name = data['data']['attributes'].get("full_name") or "(unnamed)"
internal_label = "%s-%s" % (request.user.id, name)
ac = PatreonAppCreds(user=request.user, label=internal_label)
ac.save()
storage = Storage(PatreonCredentialsModel, 'id', ac, 'credential')
storage.put(credential)
pu = PatreonUpdate(credentials=ac, user=request.user, type="patreon")
pu.save()
return HttpResponseRedirect("/patreon/")
示例14: encode
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def encode(the_id, sub_key):
assert 0 <= the_id < 2 ** 64
version = 1
crc = binascii.crc32(str(the_id).encode('utf-8')) & 0xffffffff
message = struct.pack(b"<IQI", crc, the_id, version)
assert len(message) == 16
key = settings.SECRET_KEY
iv = hashlib.sha256((key + sub_key).encode('ascii')).digest()[:16]
cypher = AES.new(key[:32].encode('utf-8'), AES.MODE_CBC, iv)
eid = base64.urlsafe_b64encode(cypher.encrypt(message)).replace(b"=", b"")
return eid.decode("utf-8")
示例15: decode
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import SECRET_KEY [as 別名]
def decode(
token: bytes,
options: Optional[Dict[str, bool]] = None,
check_claims: Optional[Sequence[str]] = None,
algorithms: Optional[List[str]] = None,
) -> dict:
"""Decode JWT payload and check for 'jti', 'sub' claims."""
if not options:
options = DEFAULT_DECODE_OPTIONS
if not check_claims:
check_claims = MANDATORY_CLAIMS
if not algorithms:
# default encode algorithm - see PyJWT.encode
algorithms = ["HS256"]
decoded = jwt_decode(
token, settings.SECRET_KEY, algorithms=algorithms, options=options
)
check_mandatory_claims(decoded, claims=check_claims)
return decoded