Python django.conf.settings.SECRET_KEY Examples

The following are 30 code examples of django.conf.settings.SECRET_KEY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: test_profile.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
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,
            ),
        ) 
Example #2
Source File: crypto.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #3
Source File: crypto.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #4
Source File: 0002_auto_adduser.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #5
Source File: __init__.py    From django-encrypted-id with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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") 
Example #6
Source File: crypto.py    From python with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: crypto.py    From python with Apache License 2.0 6 votes vote down vote up
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)) 
Example #8
Source File: crypto.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: crypto.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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)]) 
Example #10
Source File: photos.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: backends.py    From aws-workshop with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: utils.py    From django-request-token with MIT License 6 votes vote down vote up
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 
Example #13
Source File: crypto.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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) 
Example #14
Source File: backends.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #15
Source File: views.py    From mirandum with Apache License 2.0 6 votes vote down vote up
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/") 
Example #16
Source File: crypto.py    From bioforum with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: crypto.py    From bioforum with MIT License 6 votes vote down vote up
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)) 
Example #18
Source File: crypto.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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)) 
Example #19
Source File: crypto.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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) 
Example #20
Source File: crypto.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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)) 
Example #21
Source File: backends.py    From cruzz with MIT License 6 votes vote down vote up
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 
Example #22
Source File: views.py    From mirandum with Apache License 2.0 6 votes vote down vote up
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) 
Example #23
Source File: crypto.py    From python2017 with MIT License 6 votes vote down vote up
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)) 
Example #24
Source File: crypto.py    From python2017 with MIT License 6 votes vote down vote up
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) 
Example #25
Source File: models.py    From cruzz with MIT License 5 votes vote down vote up
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.timestamp())
        }, settings.SECRET_KEY, algorithm='HS256')

        return token.decode('utf-8') 
Example #26
Source File: test_badge.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super(BadgeTestCase, self).setUp()
        self.check = Check.objects.create(project=self.project, tags="foo bar")

        sig = base64_hmac(str(self.project.badge_key), "foo", settings.SECRET_KEY)
        sig = sig[:8]
        self.svg_url = "/badge/%s/%s/foo.svg" % (self.project.badge_key, sig)
        self.json_url = "/badge/%s/%s/foo.json" % (self.project.badge_key, sig) 
Example #27
Source File: signing.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
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.__class__.__module__, self.__class__.__name__)) 
Example #28
Source File: signing.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
    modpath = settings.SIGNING_BACKEND
    module, attr = modpath.rsplit('.', 1)
    try:
        mod = import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured(
            'Error importing cookie signer %s: "%s"' % (modpath, e))
    try:
        Signer = getattr(mod, attr)
    except AttributeError as e:
        raise ImproperlyConfigured(
            'Error importing cookie signer %s: "%s"' % (modpath, e))
    return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt) 
Example #29
Source File: signing.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #30
Source File: forms.py    From zentral with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.session = kwargs.pop("session")
        self.user_agent = kwargs.pop("user_agent", None)
        token_data = signing.loads(self.session["verification_token"],
                                   salt="zentral_verify_token",
                                   key=django_settings.SECRET_KEY)
        self.redirect_to = token_data["redirect_to"]
        self.user = User.objects.get(pk=token_data["user_id"])
        self.user.backend = token_data["auth_backend"]  # used by contrib.auth.login
        super().__init__(*args, **kwargs)