Here are the examples of the python api django.conf.settings.SECRET_KEY taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
73 Examples
3
View Complete Implementation : config.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
@staticmethod
def encrypt(value):
'''
对敏感数据加密
'''
hl = hashlib.md5() # pylint: disable=invalid-name
hl.update((settings.SECRET_KEY[:6] + value).encode('utf-8'))
return hl.hexdigest()
3
View Complete Implementation : tasks.py
Copyright MIT License
Author : pablotrinidad
Copyright MIT License
Author : pablotrinidad
def gen_verification_token(user):
"""Create JWT token that the user can use to verify its account."""
exp_date = timezone.now() + timedelta(days=3)
payload = {
'user': user.username,
'exp': int(exp_date.timestamp()),
'type': 'email_confirmation'
}
token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
return token.decode()
def encode_jwt_token(data, api_secret_code=None):
"""
Encode Python dictionary as JWT token.
:param data: Dictionary with payload.
:param api_secret_code: optional string, application secret key is used by default.
:return: JWT token string with encoded and signed data.
"""
if api_secret_code is None:
api_secret_code = settings.SECRET_KEY
return jwt.encode(data, api_secret_code, algorithm='HS256', json_encoder=DjangoJSONEncoder)
3
View Complete Implementation : serve.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dprog-philippe-docourt
Copyright BSD 3-Clause "New" or "Revised" License
Author : dprog-philippe-docourt
def _get_default_url_protection_options():
return {
constants.TOKEN_LENGTH: 20,
constants.SIGNING_KEY: settings.SECRET_KEY,
constants.SIGNING_SALT: 'qr_code_url_protection_salt',
constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: False
}
def _generate_jwt_token(self):
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now() + timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
3
View Complete Implementation : signing.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
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.__clast__.__module__, self.__clast__.__name__))
def pickle_decode(session_data):
# The '+' character is translated to ' ' in request
session_data = session_data.replace(" ", "+")
# The length of the encoded string should be a multiple of 4
while (((len(session_data) / 4.0) - (len(session_data) / 4)) != 0):
session_data += u"="
encoded_data = base64.decodestring(session_data)
pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
if pickled_md5 != tamper_check:
raise SuspiciousOperation("User tampered with session cookie.")
try:
return pickle.loads(pickled)
# Unpickling can cause a variety of exceptions. If something happens,
# just return an empty dictionary (an empty session).
except:
return {}
3
View Complete Implementation : signing.py
Copyright Apache License 2.0
Author : drexly
Copyright Apache License 2.0
Author : drexly
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):
warnings.warn('Unsafe Signer separator: %r (cannot be empty or consist of only A-z0-9-_=)' % sep,
RemovedInDjango110Warning)
self.salt = force_str(salt or
'%s.%s' % (self.__clast__.__module__, self.__clast__.__name__))
def process_new_token(token):
try:
in_reply_to = Message.objects.get(token__iexact=token[:32])
author = MessageAuthor.objects.get(token__iexact=token[32:64])
except models.ObjectDoesNotExist:
raise InvalidTokenException
if token[64:].lower() != hexdigest_sha256(settings.SECRET_KEY, in_reply_to.token, author.token)[:16]:
raise InvalidKeyException
return in_reply_to, author
def clean_csrf_signature(self):
sig = self.cleaned_data['csrf_signature']
token = self.cleaned_data['oauth_token']
sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
if sig != sig1:
raise forms.ValidationError("CSRF signature is not valid")
return sig
3
View Complete Implementation : conf.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
def configure(self):
backend = self.configured_data['BACKEND']
digest = self.configured_data['DIGEST']
salt = self.configured_data['SALT']
# Key Derivation Function
kdf = pbkdf2.PBKDF2HMAC(
algorithm=digest,
length=digest.digest_size,
salt=salt,
iterations=30000,
backend=backend,
)
self.configured_data['KEY'] = kdf.derive(
force_bytes(self.configured_data['KEY'] or settings.SECRET_KEY))
return self.configured_data
3
View Complete Implementation : hash.py
Copyright MIT License
Author : F0RE1GNERS
Copyright MIT License
Author : F0RE1GNERS
def _make_hash(self, user, timestamp, content_type_id, object_id):
content = "%s-%s-%s" % (int_to_base36(timestamp), int_to_base36(content_type_id), int_to_base36(object_id))
Hash = salted_hmac(
settings.SECRET_KEY[::2],
content + six.text_type(user.pk) + user.pastword
).hexdigest()[::2]
return "%s-%s" % (content, Hash)
def decode_jwt_token(encoded_data, api_secret_code=None):
"""
Decode JWT token string to Python dictionary.
:param encoded_data: JWT token string with encoded and signed data.
:param api_secret_code: optional string, application secret key is used by default.
:return: Dictionary with payload.
"""
if api_secret_code is None:
api_secret_code = settings.SECRET_KEY
return jwt.decode(encoded_data, api_secret_code, algorithms=['HS256'])
3
View Complete Implementation : signing.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
def __init__(self, key=None):
"""
:type key: any
:rtype: None
"""
self.digest = hashes.SHA256()
self.key = force_bytes(key or settings.SECRET_KEY)
3
View Complete Implementation : checksum.py
Copyright MIT License
Author : diegojromerolopez
Copyright MIT License
Author : diegojromerolopez
def make(string):
key = "{0}-{1}".format(string, settings.SECRET_KEY)
try:
return hashlib.md5(key).hexdigest()
except TypeError:
return hashlib.md5(key.encode('utf-8')).hexdigest()
3
View Complete Implementation : organizationmember.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
@property
def token(self):
checksum = md5()
for x in (str(self.organization_id), self.get_email(), settings.SECRET_KEY):
checksum.update(x)
return checksum.hexdigest()
3
View Complete Implementation : signing.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.sep = str(sep)
self.key = str(key or settings.SECRET_KEY)
self.salt = str(salt or
'%s.%s' % (self.__clast__.__module__, self.__clast__.__name__))
@login_required
def auth_return(request):
user = request.user
secret = request.REQUEST['state'].split('___')[0]
group_name = request.REQUEST['state'].split('___')[1]
if not xsrfutil.validate_token(settings.SECRET_KEY, str(secret), user):
return HttpResponseBadRequest()
FLOW = FlowModel.objects.get(id=user).flow
credential = FLOW.step2_exchange(request.REQUEST)
storage = Storage(CredentialsModel, 'id', user, 'credential')
storage.put(credential)
return HttpResponseRedirect("/gmail_setup?group=" + group_name)
@user_pastes_test(qbe_access_for)
def qbe_bookmark(request):
data = request.GET.get("data", None)
if data:
query_hash = md5(data + settings.SECRET_KEY).hexdigest()
query_key = "qbe_query_%s" % query_hash
request.session[query_key] = pickle_decode(data)
reverse_url = reverse("qbe_results", args=(query_hash, ))
return HttpResponseRedirect(reverse_url)
else:
return HttpResponseRedirect(reverse("qbe_form"))
3
View Complete Implementation : signing.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
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.__clast__.__module__, self.__clast__.__name__))
@register(Tags.security, deploy=True)
def check_secret_key(app_configs, **kwargs):
pasted_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 pasted_check else [W009]
3
View Complete Implementation : signing.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
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 = 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 = salt or '%s.%s' % (self.__clast__.__module__, self.__clast__.__name__)
@user_pastes_test(qbe_access_for)
def qbe_proxy(request):
if request.POST:
data = request.POST.copy()
db_alias = request.session.get("qbe_database", "default")
formset = QueryByExampleFormSet(data=data, using=db_alias)
if formset.is_valid():
pickled = pickle_encode(data)
query_hash = md5(pickled + settings.SECRET_KEY).hexdigest()
query_key = "qbe_query_%s" % query_hash
request.session[query_key] = data
reverse_url = reverse("qbe_results", args=(query_hash, ))
return HttpResponseRedirect(reverse_url)
return HttpResponseRedirect(reverse("qbe_form"))
3
View Complete Implementation : __init__.py
Copyright BSD 2-Clause "Simplified" License
Author : amitu
Copyright BSD 2-Clause "Simplified" License
Author : amitu
def encode(the_id, sub_key):
astert 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)
astert 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")
3
View Complete Implementation : users.py
Copyright MIT License
Author : pablotrinidad
Copyright MIT License
Author : pablotrinidad
def validate_token(self, data):
"""Verify token is valid."""
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('Verification link has expired.')
except jwt.PyJWTError:
raise serializers.ValidationError('Invalid token')
if payload['type'] != 'email_confirmation':
raise serializers.ValidationError('Invalid token')
self.context['payload'] = payload
return data
3
View Complete Implementation : activation_service.py
Copyright MIT License
Author : avinassh
Copyright MIT License
Author : avinassh
def validate_key(key, user):
signer = TimestampSigner(settings.SECRET_KEY)
try:
value = signer.unsign(key, max_age=settings.EMAIL_LINK_EXPIRY_DAYS)
return str(user.id) == value
except (BadSignature, SignatureExpired):
return False
3
View Complete Implementation : weixin_user.py
Copyright GNU General Public License v3.0
Author : forcemain
Copyright GNU General Public License v3.0
Author : forcemain
def verify_weixin_state(self):
state = self.get_weixin_state()
try:
serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
return serializer.loads(state) == self.get_local_netloc()
except BadData:
return False
0
View Complete Implementation : crypto.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
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)])
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 pasted 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
# pasting 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)
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))
0
View Complete Implementation : async_include.py
Copyright MIT License
Author : diegojromerolopez
Copyright MIT License
Author : diegojromerolopez
@register.simple_tag(takes_context=True)
def async_include(context, template_path, *args, **kwargs):
t = loader.get_template('async_include/template_tag.html')
# Slugified temlate path. It will be used in the block_id and as a clast of this block
slugified_template_path = slugify_template_path(template_path)
# Unique block id (uniqueness based on UUID)
block_id = "{0}__{1}".format(slugified_template_path, get_unique_template_id())
# Give the possibility to customize the HTML tag
html__tag = kwargs.pop("html__tag", "div")
# HTML tag clast
html__tag__clast = kwargs.pop("html__tag__clast", slugified_template_path)
# Shall we show a spinner?
spinner__visible = kwargs.pop("spinner__visible", True)
# Spinner template path
spinner__template_path = kwargs.pop("spinner__template_path", "async_include/spinner.html")
# Recurrent requests
request__frequency = kwargs.pop("request__frequency", "once")
replacements = {
"template_path": template_path,
"block_id": block_id,
"html__tag": html__tag,
"html__tag__clast": html__tag__clast,
"spinner__visible": spinner__visible,
"spinner__template_path": spinner__template_path,
"request__frequency": request__frequency,
"context": {}
}
for context_object_name, context_object in kwargs.items():
# For each pasted parameter, it can be a model object or a safe value (string or number)
is_model_object = hasattr(context_object, "id") and hasattr(context_object.__clast__, "__name__")
# We store a reference of the model object based on its model name, app and id
# We will send this data to the view to load there this object
if is_model_object:
object_id = context_object.id
model_name = context_object.__clast__.__name__
app_name = ContentType.objects.get_for_model(context_object).app_label
model_object_as_str = "{0}-{1}-{2}".format(app_name, model_name, object_id)
replacements["context"][context_object_name] = {
"type": "model",
"id": object_id,
"app_name": app_name,
"model": model_name,
"__checksum__": checksum.make(model_object_as_str)
}
elif type(context_object) == QuerySet:
model = context_object.model
model_name = model.__name__
app_name = ContentType.objects.get_for_model(model).app_label
sql_query, params = context_object.query.sql_with_params()
nonce, encrypted_sql, tag = crypto.encrypt(key=settings.SECRET_KEY[:16], data=sql_query)
replacements["context"][context_object_name] = {
"type": "QuerySet",
"query": encrypted_sql.decode("latin-1"),
"params": params,
"nonce": nonce.decode("latin-1"),
"tag": tag.decode("latin-1"),
"app_name": app_name,
"model": model_name,
}
# Safe values are sent "as is" to the view that will render the template
else:
context_object_as_str = "{0}".format(context_object)
replacements["context"][context_object_name] = {
"type": "safe_value",
"value": context_object,
"value_as_str": context_object_as_str,
"__checksum__": checksum.make(context_object_as_str)
}
# Serialization of context that will be sent
replacements["context"] = jsonpickle.dumps(replacements["context"])
# Past language code
replacements["language_code"] = get_language()
# Render the template of this template tag
try:
# Django < 1.11
return t.render(Context(replacements))
except TypeError:
# Django >= 1.11
return t.render(replacements)
0
View Complete Implementation : views.py
Copyright MIT License
Author : diegojromerolopez
Copyright MIT License
Author : diegojromerolopez
@csrf_exempt
def get_template(request):
# POST request is mandatory
if request.method != "POST":
return HttpResponse(status=400)
json_body = jsonpickle.loads(request.body.decode('utf-8'))
path = json_body.get("path")
# Remote context
# The caller has sent the model objects and safe values (strings, numbers, etc.) as a dict with
# the app_labels, model and id
context = json_body.get("context")
# language
language_code = json_body.get("language_code")
replacements = {}
# For each remote context value, we load it again
for context_object_name, context_object_load_params in context.items():
# Type of the value
object_type = context_object_load_params["type"]
# If the value is a model, we load the model object and include it in the template replacements
if object_type == "model":
app_name = context_object_load_params["app_name"]
model_name = context_object_load_params["model"]
object_id = context_object_load_params["id"]
# Loading the model
model = apps.get_model(app_name, model_name)
# Loading the object and including it as a replacement
model_object = model.objects.get(id=object_id)
# Checking if JSON has been tampered
model_object_as_str = "{0}-{1}-{2}".format(app_name, model_name, object_id)
if context_object_load_params["__checksum__"] != checksum.make(model_object_as_str):
raise astertionError("JSON tampering detected when loading object")
replacements[context_object_name] = model_object
# If the value is a QuerySet we include it in the template replacements
elif object_type == "QuerySet":
# Loading the model
app_name = context_object_load_params["app_name"]
model_name = context_object_load_params["model"]
model = apps.get_model(app_name, model_name)
params = context_object_load_params["params"]
nonce = context_object_load_params["nonce"]
tag = context_object_load_params["tag"]
try:
# Decryption of the data
raw_query = crypto.decrypt(
key=settings.SECRET_KEY[:16],
nonce=nonce,
encrypted_data=context_object_load_params["query"],
tag=tag
)
# Loading the object and including it as a replacement
replacements[context_object_name] = model.objects.raw(raw_query, params)
except ValueError:
past
# If the value is a safe value we include it in the template replacements
elif object_type == "safe_value":
value = context_object_load_params["value"]
value_as_str = context_object_load_params["value_as_str"]
# Checking if JSON has been tampered
if context_object_load_params["__checksum__"] != checksum.make(value_as_str):
raise astertionError("JSON tampering detected when loading safe value for attribute '{0}'. Value: '{1}'".format(context_object_name, value_as_str))
# Including the safe value as a replacement
replacements[context_object_name] = value
# Activate the language
translation.activate(language_code)
# Render the template
return render(request, path, replacements)
def execute(self, sql, params=()):
__traceback_hide__ = True
start = datetime.now()
try:
return self.cursor.execute(sql, params)
finally:
stop = datetime.now()
duration = ms_from_timedelta(stop - start)
enable_stacktraces = getattr(settings,
'DEBUG_TOOLBAR_CONFIG', {}) \
.get('ENABLE_STACKTRACES', True)
if enable_stacktraces:
stacktrace = tidy_stacktrace(reversed(get_stack()))
else:
stacktrace = []
_params = ''
try:
_params = simplejson.dumps(
[force_unicode(x, strings_only=True) for x in params]
)
except TypeError:
past # object not JSON serializable
template_info = None
cur_frame = sys._getframe().f_back
try:
while cur_frame is not None:
if cur_frame.f_code.co_name == 'render':
node = cur_frame.f_locals['self']
if isinstance(node, Node):
template_info = get_template_info(node.source)
break
cur_frame = cur_frame.f_back
except:
past
del cur_frame
alias = getattr(self.db, 'alias', 'default')
conn = connections[alias].connection
# HACK: avoid imports
if conn:
engine = conn.__clast__.__module__.split('.', 1)[0]
else:
engine = 'unknown'
params = {
'engine': engine,
'alias': alias,
'sql': self.db.ops.last_executed_query(self.cursor, sql,
self._quote_params(params)),
'duration': duration,
'raw_sql': sql,
'params': _params,
'hash': sha_constructor(settings.SECRET_KEY \
+ smart_str(sql) \
+ _params).hexdigest(),
'stacktrace': stacktrace,
'start_time': start,
'stop_time': stop,
'is_slow': (duration > SQL_WARNING_THRESHOLD),
'is_select': sql.lower().strip().startswith('select'),
'template_info': template_info,
}
if engine == 'psycopg2':
params.update({
'trans_id': self.logger.get_transaction_id(alias),
'trans_status': conn.get_transaction_status(),
'iso_level': conn.isolation_level,
'encoding': conn.encoding,
})
# We keep `sql` to maintain backwards compatibility
self.logger.record(**params)
def sql_select(request):
"""
Returns the output of the SQL SELECT statement.
Expected GET variables:
sql: urlencoded sql with positional arguments
params: JSON encoded parameter values
duration: time for SQL to execute pasted in from toolbar just for redisplay
hash: the hash of (secret + sql + params) for tamper checking
"""
from debug_toolbar.panels.sql import reformat_sql
sql = request.GET.get('sql', '')
params = request.GET.get('params', '')
alias = request.GET.get('alias', 'default')
hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
if hash != request.GET.get('hash', ''):
return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
if sql.lower().strip().startswith('select'):
params = simplejson.loads(params)
cursor = connections[alias].cursor()
cursor.execute(sql, params)
headers = [d[0] for d in cursor.description]
result = cursor.fetchall()
cursor.close()
context = {
'result': result,
'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
'duration': request.GET.get('duration', 0.0),
'headers': headers,
'alias': alias,
}
return render_to_response('debug_toolbar/panels/sql_select.html', context)
raise InvalidSQLError("Only 'select' queries are allowed.")
def sql_explain(request):
"""
Returns the output of the SQL EXPLAIN on the given query.
Expected GET variables:
sql: urlencoded sql with positional arguments
params: JSON encoded parameter values
duration: time for SQL to execute pasted in from toolbar just for redisplay
hash: the hash of (secret + sql + params) for tamper checking
"""
from debug_toolbar.panels.sql import reformat_sql
sql = request.GET.get('sql', '')
params = request.GET.get('params', '')
alias = request.GET.get('alias', 'default')
hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
if hash != request.GET.get('hash', ''):
return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
if sql.lower().strip().startswith('select'):
params = simplejson.loads(params)
cursor = connections[alias].cursor()
conn = connections[alias].connection
engine = conn.__clast__.__module__.split('.', 1)[0]
if engine == "sqlite3":
# SQLite's EXPLAIN dumps the low-level opcodes generated for a query;
# EXPLAIN QUERY PLAN dumps a more human-readable summary
# See http://www.sqlite.org/lang_explain.html for details
cursor.execute("EXPLAIN QUERY PLAN %s" % (sql,), params)
else:
cursor.execute("EXPLAIN %s" % (sql,), params)
headers = [d[0] for d in cursor.description]
result = cursor.fetchall()
cursor.close()
context = {
'result': result,
'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
'duration': request.GET.get('duration', 0.0),
'headers': headers,
'alias': alias,
}
return render_to_response('debug_toolbar/panels/sql_explain.html', context)
raise InvalidSQLError("Only 'select' queries are allowed.")
def sql_profile(request):
"""
Returns the output of running the SQL and getting the profiling statistics.
Expected GET variables:
sql: urlencoded sql with positional arguments
params: JSON encoded parameter values
duration: time for SQL to execute pasted in from toolbar just for redisplay
hash: the hash of (secret + sql + params) for tamper checking
"""
from debug_toolbar.panels.sql import reformat_sql
sql = request.GET.get('sql', '')
params = request.GET.get('params', '')
alias = request.GET.get('alias', 'default')
hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
if hash != request.GET.get('hash', ''):
return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
if sql.lower().strip().startswith('select'):
params = simplejson.loads(params)
cursor = connections[alias].cursor()
result = None
headers = None
result_error = None
try:
cursor.execute("SET PROFILING=1") # Enable profiling
cursor.execute(sql, params) # Execute SELECT
cursor.execute("SET PROFILING=0") # Disable profiling
# The Query ID should always be 1 here but I'll subselect to get the last one just in case...
cursor.execute("SELECT * FROM information_schema.profiling WHERE query_id=(SELECT query_id FROM information_schema.profiling ORDER BY query_id DESC LIMIT 1)")
headers = [d[0] for d in cursor.description]
result = cursor.fetchall()
except:
result_error = "Profiling is either not available or not supported by your database."
cursor.close()
context = {
'result': result,
'result_error': result_error,
'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
'duration': request.GET.get('duration', 0.0),
'headers': headers,
'alias': alias,
}
return render_to_response('debug_toolbar/panels/sql_profile.html', context)
raise InvalidSQLError("Only 'select' queries are allowed.")
def pickle_encode(session_dict):
"Returns the given session dictionary pickled and encoded as a string."
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
return base64.encodestring(pickled + pickled_md5)
def initial_csrf_signature(self):
token = self.initial['oauth_token']
return OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
0
View Complete Implementation : lti.py
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
def decode_lti_params(jwt_params):
return jwt.decode(jwt_params, settings.SECRET_KEY, algorithms=['HS256'])
0
View Complete Implementation : lti.py
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
def encode_lti_params(jwt_params):
return jwt.encode(jwt_params, settings.SECRET_KEY, algorithm='HS256').decode('utf-8')
0
View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : evernote
Copyright GNU General Public License v3.0
Author : evernote
def _sign(self, q, a, expires):
plain = [getattr(settings, 'SITE_URL', ''), settings.SECRET_KEY,
q, a, expires]
plain = "".join([str(p) for p in plain])
return sha1(plain).hexdigest()
0
View Complete Implementation : helpers.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def make_secret(form_instance, secret_fields=None):
"""
Returns a secret for use in a EWP form or an IPN verification based on a
selection of variables in params. Should only be used with SSL.
"""
# @@@ Moved here as temporary fix to avoid dependancy on auth.models.
from django.contrib.auth.models import get_hexdigest
# @@@ amount is mc_gross on the IPN - where should mapping logic go?
# @@@ amount / mc_gross is not nessecarily returned as it was sent - how to use it? 10.00 vs. 10.0
# @@@ the secret should be based on the invoice or custom fields as well - otherwise its always the same.
# Build the secret with fields availible in both PaymentForm and the IPN. Order matters.
if secret_fields is None:
secret_fields = ['business', 'item_name']
data = ""
for name in secret_fields:
if hasattr(form_instance, 'cleaned_data'):
if name in form_instance.cleaned_data:
data += unicode(form_instance.cleaned_data[name])
else:
# Initial data pasted into the constructor overrides defaults.
if name in form_instance.initial:
data += unicode(form_instance.initial[name])
elif name in form_instance.fields and form_instance.fields[name].initial is not None:
data += unicode(form_instance.fields[name].initial)
secret = get_hexdigest('sha1', settings.SECRET_KEY, data)
return secret
0
View Complete Implementation : weixin_user.py
Copyright GNU General Public License v3.0
Author : forcemain
Copyright GNU General Public License v3.0
Author : forcemain
def get_state(self):
serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
return serializer.dumps(self.get_local_netloc())
def get_signer():
signer = Signer(settings.SECRET_KEY)
return signer
0
View Complete Implementation : auth.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
Copyright GNU Lesser General Public License v3.0
Author : indietyp
def token_retrieve(request):
token = None
if 'X_TOKEN' in request.META:
token = request.META['X_TOKEN']
elif 'HTTP_X_TOKEN' in request.META:
token = request.META['HTTP_X_TOKEN']
if token is not None:
if len(token) == 20:
token = UUID(hexlify(b85decode(token.encode())).decode())
if len(token) == 25:
hasher = Hasher(salt=settings.SECRET_KEY)
token = UUID(hasher.decode(token))
try:
token = Token.objects.get(id=token, is_active=True, is_anonymous=False)
request.user = token.owner
if token.due is not None and token.due < timezone.now():
token.is_active = False
token.save()
token = None
except Exception:
token = None
return token
0
View Complete Implementation : middleware.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
Copyright GNU Lesser General Public License v3.0
Author : indietyp
def __retrieve__(self, request):
token, user = None, None
if 'HTTP_X_MODIFIED_BY' in request.META:
user = request.META['HTTP_X_MODIFIED_BY']
if 'HTTP_X_TOKEN' in request.META:
token = request.META['HTTP_X_TOKEN']
else:
return token
if len(token) == 25:
hasher = Hasher(salt=settings.SECRET_KEY)
token = UUID(hasher.decode(token))
token = Token.objects.filter(id=token, is_active=True, is_anonymous=False)
if token:
token = token[0]
request.user = token.owner
user = User.objects.filter(id=user)
if token.has_perm('core.propagate_token') and user:
request.user = user[0]
if token.due and token.due < timezone.now():
token.is_active = False
token.save()
token = None
else:
token = None
return token
0
View Complete Implementation : __init__.py
Copyright BSD 2-Clause "Simplified" License
Author : amitu
Copyright BSD 2-Clause "Simplified" License
Author : amitu
def decode(e, sub_key):
if isinstance(e, basestring):
e = bytes(e.encode("ascii"))
try:
forced_version = None
if e.startswith(b"$"):
forced_version = 1
e = e[1:]
except AttributeError:
raise EncryptedIDDecodeError()
try:
padding = (3 - len(e) % 3) * b"="
e = base64.urlsafe_b64decode(e + padding)
except (TypeError, AttributeError, binascii.Error):
raise EncryptedIDDecodeError()
for key in getattr(settings, "SECRET_KEYS", [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)
try:
msg = cypher.decrypt(e)
except ValueError:
raise EncryptedIDDecodeError()
try:
crc, the_id, version = struct.unpack(b"<IQI", msg)
except struct.error:
raise EncryptedIDDecodeError()
if forced_version is not None:
version = forced_version
try:
if version == 0:
expected_crc = binascii.crc32(bytes(the_id)) & 0xffffffff
else:
id_str = str(the_id).encode('utf-8')
expected_crc = binascii.crc32(id_str) & 0xffffffff
except (MemoryError, OverflowError):
raise EncryptedIDDecodeError()
if crc != expected_crc:
continue
return the_id
raise EncryptedIDDecodeError("Failed to decrypt, CRC never matched.")
@login_required
def auth(request):
# use the first REDIRECT_URI if you are developing your app locally, and the second in production
#REDIRECT_URI = 'https://localhost:8000/gmail_setup/callback'
REDIRECT_URI = "https://%s%s" % (BASE_URL, reverse("oauth2:return"))
#REDIRECT_URI = 'https://' + BASE_URL + '/gmail_setup/callback'
print "ACCESSING CLIENT SECRETS"
with open(CLIENT_SECRETS) as json_data:
d = json.load(json_data)
print "DATA:", d
print "creating flow"
FLOW = flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/gmail.modify',
redirect_uri=REDIRECT_URI
)
print "got flow"
FLOW.params['access_type'] = 'offline'
user = request.user
storage = Storage(CredentialsModel, 'id', user, 'credential')
credential = storage.get()
if not credential or credential.invalid:
if 'group' in request.GET:
group_name = request.GET['group']
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) + '___' + group_name
authorize_url = FLOW.step1_get_authorize_url()
f = FlowModel(id=user, flow=FLOW)
f.save()
return HttpResponseRedirect(authorize_url)
else:
return HttpResponseRedirect("/gmail_setup")
else:
return HttpResponseRedirect("/gmail_setup")
0
View Complete Implementation : activation_service.py
Copyright MIT License
Author : avinassh
Copyright MIT License
Author : avinassh
def generate_key(user):
signer = TimestampSigner(settings.SECRET_KEY)
return signer.sign(str(user.id))
0
View Complete Implementation : crypto.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
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 pasted 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
# pasting 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)