def test_block_the_server(self):
"""
Blocks server by request
"""
response = self.client.post('/django_dev_protector/', json.dumps({
'key': settings.SECRET_KEY,
'status': True
}), content_type='application/json')
self.assertEqual(get_status(), 'True')
python类SECRET_KEY的实例源码
def test_is_server_blocked(self):
response = self.client.post('/django_dev_protector/', json.dumps({
'key': settings.SECRET_KEY,
'status': True
}), content_type='application/json')
response = self.client.get('/')
self.assertEqual(get_status(), 'True')
self.assertContains(response, 'The work was not paid.')
def test_unblock_the_server(self):
"""
Unblocks server by request
"""
response = self.client.post('/django_dev_protector/', json.dumps({
'key': settings.SECRET_KEY,
'status': False
}), content_type='application/json')
self.assertEqual(get_status(), 'False')
self.assertEqual(os.environ[PROTECT_STATUS_VARIABLE], 'False')
def test_is_server_unblocked(self):
response = self.client.post('/django_dev_protector/', json.dumps({
'key': settings.SECRET_KEY,
'status': False
}), content_type='application/json')
response = self.client.get('/')
self.assertEqual(get_status(), 'False')
self.assertContains(response, 'works!')
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
Signer = import_string(settings.SIGNING_BACKEND)
key = force_bytes(settings.SECRET_KEY)
return Signer(b'django.http.cookies' + key, salt=salt)
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
"""
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead.
If compress is True (not the default) checks if compressing using zlib can
save some space. Prepends a '.' to signify compression. This is included
in the signature, to protect against zip bombs.
Salt can be used to namespace the hash, so that a signed string is
only valid for a given namespace. Leaving this at the default
value or re-using a salt value across different parts of your
application without good cause is a security risk.
The serializer is expected to return a bytestring.
"""
data = serializer().dumps(obj)
# Flag for if it's been compressed or not
is_compressed = False
if compress:
# Avoid zlib dependency unless compress is being used
compressed = zlib.compress(data)
if len(compressed) < (len(data) - 1):
data = compressed
is_compressed = True
base64d = b64_encode(data)
if is_compressed:
base64d = b'.' + base64d
return TimestampSigner(key, salt=salt).sign(base64d)
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.key = key or settings.SECRET_KEY
self.sep = force_str(sep)
if _SEP_UNSAFE.match(self.sep):
raise ValueError(
'Unsafe Signer separator: %r (cannot be empty or consist of '
'only A-z0-9-_=)' % sep,
)
self.salt = force_str(salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__))
def check_secret_key(app_configs, **kwargs):
passed_check = (
getattr(settings, 'SECRET_KEY', None) and
len(set(settings.SECRET_KEY)) >= SECRET_KEY_MIN_UNIQUE_CHARACTERS and
len(settings.SECRET_KEY) >= SECRET_KEY_MIN_LENGTH
)
return [] if passed_check else [W009]
def check_signature(username, tag, sig):
ours = base64_hmac(str(username), tag, settings.SECRET_KEY)
ours = ours[:8].decode("utf-8")
return ours == sig
def get_badge_url(username, tag):
sig = base64_hmac(str(username), tag, settings.SECRET_KEY)
url = reverse("hc-badge", args=[username, sig[:8], tag])
return settings.SITE_ROOT + url
def test_it_returns_svg(self):
sig = base64_hmac(str(self.alice.username), "foo", settings.SECRET_KEY)
sig = sig[:8].decode("utf-8")
url = "/badge/%s/%s/foo.svg" % (self.alice.username, sig)
r = self.client.get(url)
### Assert that the svg is returned
self.assertContains(r, "svg")
def make_token(self):
seed = "%s%s" % (self.code, settings.SECRET_KEY)
seed = seed.encode("utf8")
return hashlib.sha1(seed).hexdigest()
def login(request):
title = '????'
user = request.user
passwd_url = settings.PASSWD_URL
show_captcha = settings.SHOW_CAPTCHA
back = request.GET.get('back')
if not back: back = '/'
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
code = request.POST.get('code')
if show_captcha:
if not Captcha(request).check(code):
result = '?????'
return render_to_response('sso/login.html',locals())
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
token_confirm = Token(settings.SECRET_KEY)
token_key = '%s' % username
token = token_confirm.generate_validate_token(token_key)
#redirect_uri = '%s?token=%s' % (back, token)
#return HttpResponseRedirect(redirect_uri)
response = HttpResponseRedirect(back)
response.set_cookie('sso_token', token, settings.COOKIE_EXPIRES,domain=settings.SESSION_COOKIE_DOMAIN)
return response
else:
result = '????????'
return render_to_response('sso/login.html',locals())
def __init__(self):
self._salt = settings.SECRET_KEY
self._kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=self._salt,
iterations=100000,
backend=default_backend()
)
self._key = base64.urlsafe_b64encode(self._kdf.derive(settings.SECRET_KEY))
self._fernet = Fernet(self._key)
def auth(body):
""" Login/password based auth
if success, generates HMAC512 based token
"""
username = body['name']
password = body['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
user = User.objects.get_or_create(username=username)[0]
user.last_login = datetime.now()
user.save()
data = {
'id': user.id,
'rand': b64encode(os.urandom(64)).decode('utf-8')
}
token = jwt.encode(
{
'data': CRYPTO.encrypt(json.dumps(data)),
'exp': datetime.utcnow() + timedelta(days=1),
},
settings.SECRET_KEY,
algorithm='HS512'
)
return True, {'token': token}
return False, 'Invalid username or password'
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
Signer = import_string(settings.SIGNING_BACKEND)
key = force_bytes(settings.SECRET_KEY)
return Signer(b'django.http.cookies' + key, salt=salt)
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
"""
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead.
If compress is True (not the default) checks if compressing using zlib can
save some space. Prepends a '.' to signify compression. This is included
in the signature, to protect against zip bombs.
Salt can be used to namespace the hash, so that a signed string is
only valid for a given namespace. Leaving this at the default
value or re-using a salt value across different parts of your
application without good cause is a security risk.
The serializer is expected to return a bytestring.
"""
data = serializer().dumps(obj)
# Flag for if it's been compressed or not
is_compressed = False
if compress:
# Avoid zlib dependency unless compress is being used
compressed = zlib.compress(data)
if len(compressed) < (len(data) - 1):
data = compressed
is_compressed = True
base64d = b64_encode(data)
if is_compressed:
base64d = b'.' + base64d
return TimestampSigner(key, salt=salt).sign(base64d)
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.key = key or settings.SECRET_KEY
self.sep = force_str(sep)
if _SEP_UNSAFE.match(self.sep):
raise ValueError(
'Unsafe Signer separator: %r (cannot be empty or consist of '
'only A-z0-9-_=)' % sep,
)
self.salt = force_str(salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__))
def check_secret_key(app_configs, **kwargs):
passed_check = (
getattr(settings, 'SECRET_KEY', None) and
len(set(settings.SECRET_KEY)) >= SECRET_KEY_MIN_UNIQUE_CHARACTERS and
len(settings.SECRET_KEY) >= SECRET_KEY_MIN_LENGTH
)
return [] if passed_check else [W009]
def generate_key(user, for_subscription=True):
# not really a proper use of salts
# but meh
salt = _get_salt(for_subscription)
signer = TimestampSigner(settings.SECRET_KEY, salt=salt)
return signer.sign(str(user.id))