コード例 #1
0
ファイル: forms.py プロジェクト: confederacion-pirata/bandera
	def clean_email(self):
		token = salted_hmac(settings.SECRET_SALT, self.cleaned_data['email'], settings.SECRET_KEY).hexdigest()
		if not MemberToken.objects.filter(token__iexact=token):
			raise forms.ValidationError('Dirección no registrada. Por favor, introduce el correo con el que estás afiliado a tu partido o contacta con el mismo para revisar el problema.')
		if Supporter.objects.filter(email__iexact=self.cleaned_data['email']):
			raise forms.ValidationError('Correo ya registrado.')
		return self.cleaned_data['email']
コード例 #2
0
ファイル: forms.py プロジェクト: confederacion-pirata/bandera
	def save(self):
		candidate = None
		with transaction.atomic():
			supporter = Supporter(
				name = self.cleaned_data['name'],
				email = self.cleaned_data['email'],
				region = self.cleaned_data['region'],
				ok_candidate = self.cleaned_data['ok_candidate'],
				ok_tos = self.cleaned_data['ok_tos'],
				confirmed = False,
				scanned_id = 'v',
			)
			supporter.token = salted_hmac(settings.SECRET_SALT, self.cleaned_data['email'], settings.SECRET_KEY).hexdigest()
			supporter.save()
			candidate = Candidate(
				supporter = supporter,
				phase = self.cleaned_data['phase'],
				twitter = self.cleaned_data['twitter'],
				facebook = self.cleaned_data['facebook'],
				website = self.cleaned_data['website'],
				bio = self.cleaned_data['bio'],
				photo = self.cleaned_data['photo'],
			)
			candidate.save()
		return candidate
コード例 #3
0
 def generate_security_hash(self, content_type, object_pk, key, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     key_salt = 'ratings.forms.VoteForm'
     value = '-'.join((content_type, object_pk, key, timestamp))
     return salted_hmac(key_salt, value).hexdigest()
コード例 #4
0
ファイル: cookie.py プロジェクト: nbsky/django
 def _hash(self, value):
     """
     Creates an HMAC/SHA1 hash based on the value and the project setting's
     SECRET_KEY, modified to make it unique for the present purpose.
     """
     key_salt = 'django.contrib.messages'
     return salted_hmac(key_salt, value).hexdigest()
コード例 #5
0
ファイル: tokens.py プロジェクト: AviorAlong/haiwen-5.1.3
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change (the password salt will change as soon as
        # the password is set, at least for current Django auth, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short
        key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"

        # Ensure results are consistent across DB backends
        user_last_login = UserLastLogin.objects.get_by_username(user.username)
        if user_last_login is None:
            from seahub.utils.timeutils import dt
            login_dt = dt(user.ctime)
        else:
            login_dt = user_last_login.last_login
        login_timestamp = login_dt.replace(microsecond=0, tzinfo=None)

        value = (six.text_type(user.id) + user.enc_password +
                 six.text_type(login_timestamp) + six.text_type(timestamp))
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #6
0
ファイル: BaseUser.py プロジェクト: apiaas/gae-search
 def get_session_auth_hash(self):
     """
     Returns an HMAC of the password field.
     """
     # This can be any string. It is added to the secret key from settings.
     key_salt = "models.ndb.BaseUser.get_session_auth_hash"
     return salted_hmac(key_salt, self.password_hash).hexdigest()
コード例 #7
0
ファイル: token.py プロジェクト: Cadasta/cadasta-platform
 def _make_token_with_timestamp(self, user, timestamp):
     ts_b36 = int_to_base36(timestamp)
     hash = salted_hmac(
         self.key_salt,
         self._make_hash_value(user, timestamp),
     ).hexdigest()[::2]
     return "%s-%s" % (ts_b36, hash)
コード例 #8
0
ファイル: tokens.py プロジェクト: UH-CI/django-tokenapi
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        if not user.password: 
            password = make_password(None)
            key_salt = make_password(None)
            key_salt = base64.b64encode(salted_hmac(six.text_type(user.pk), key_salt).hexdigest())
            user.password = "******"%(password, key_salt)
            user.save()
        else:
            password, key_salt = user.password.split("$")
        value = (six.text_type(user.pk) + user.password + six.text_type(timestamp))
        hashval = salted_hmac(key_salt, value).hexdigest()        
        return base64.urlsafe_b64encode("%s-%s" % (ts_b36,hashval))
コード例 #9
0
 def create(self, user, purpose, key=None, **kwargs):
     if key is None:
         salt = get_random_string(32)
         value = '%s-%s-%s' % (user.email, user.node, user.domain)
         key = salted_hmac(salt, value).hexdigest()
     return super(ConfirmationManager, self).create(
         user=user, purpose=purpose, key=key, **kwargs)
コード例 #10
0
ファイル: models.py プロジェクト: panuta/playplearn
    def create_registration(self, email):
        key_salt = 'accounts.models.UserRegistrationManager_%d' % random.randint(1, 99999999)
        email = email.encode('utf-8')
        value = email
        registration_key = salted_hmac(key_salt, value).hexdigest()

        return self.create(email=email, registration_key=registration_key)
コード例 #11
0
ファイル: tokens.py プロジェクト: in6kPythonDev/open-action
    def _make_token_with_timestamp(self, user, timestamp):

        # IMPORTANT: Django API user parameter = OpenAction (action, user)!
        # The user is the one that called for action
        action, user = user
        log.debug("MAKE TOKEN: action=%s, user=%s, timestamp=%s" % (action,user, timestamp))

        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # NOT hashing the internal state of the action or the calling user,
        # because there is no invalidation method
        key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
        value = unicode(user.id) + unicode(action.id) + \
            unicode(action.bare_title) + unicode(timestamp)
            #KO: this would invalidate the token
            #KO: user.password + user.last_login.strftime('%Y-%m-%d %H:%M:%S') + \
        hash = salted_hmac(key_salt, value).hexdigest()[::2]

        # UID PART to recognize user by token
        uid_part = base64.encodestring("%s%s" % (TOKEN_UID_PREFIX, user.id))

        log.debug("\nts_b36:%s!\nuid_part:%s!\nTOK_UID_POSTFIX:%s!\nhash:%s!\n" % (ts_b36, uid_part, TOKEN_UID_POSTFIX, hash))

        return "%s-%s%s%s" % (ts_b36, uid_part, TOKEN_UID_POSTFIX, hash)
コード例 #12
0
ファイル: forms.py プロジェクト: okonkwo/prospere
 def generate_security_hash(self, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     key_salt = "Ax5Sfs32i45g8ra"
     value = "-".join(timestamp)
     return salted_hmac(key_salt, value).hexdigest()
コード例 #13
0
ファイル: base.py プロジェクト: aibon/django-sitemessage
    def get_dispatch_hash(cls, dispatch_id, message_id):
        """Returns a hash string for validation purposes.

        :param int dispatch_id:
        :param int message_id:
        :return:
        """
        return salted_hmac('%s' % dispatch_id, '%s|%s' % (message_id, dispatch_id)).hexdigest()
コード例 #14
0
ファイル: tokens.py プロジェクト: poleha/appeal_django
 def _make_token_with_timestamp(self, user):
     timestamp = int(format(user.date_joined, 'U'))
     ts_b36 = int_to_base36(timestamp)
     hash = salted_hmac(
         self.key_salt,
         self._make_hash_value(user),
     ).hexdigest()[::2]
     return "%s-%s" % (ts_b36, hash)
コード例 #15
0
ファイル: forms.py プロジェクト: okonkwo/prospere
 def generate_security_hash(self, content_type, object_pk, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     info = (content_type, object_pk, timestamp)
     key_salt = "Ax5Sfs32i45g8ra"
     value = "-".join(info)
     return salted_hmac(key_salt, value).hexdigest()
コード例 #16
0
ファイル: utils.py プロジェクト: Doist/powerapp
def create_webhook_token(integration):
    """
    Create a signed dict with integration_id (i) and user_id (u) attributes
    """
    qs = {'i': integration.id, 'u': integration.user_id}
    string = parse.urlencode(qs)
    token = salted_hmac(WEBHOOK_HMAC_SALT, string).hexdigest()
    return '%s?%s' % (token, string)
コード例 #17
0
ファイル: forms.py プロジェクト: LagunaISW/Midori
 def generate_security_hash(self, content_type, object_pk, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     info = (content_type, object_pk, timestamp)
     key_salt = "django.contrib.forms.CommentSecurityForm"
     value = "-".join(info)
     return salted_hmac(key_salt, value).hexdigest()
コード例 #18
0
 def _generate_security_hash(self, content_type, object_pk, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     return salted_hmac(
         key_salt="content_interactions.forms.CommentForm",
         value="-".join([content_type, object_pk, timestamp])
     ).hexdigest()
コード例 #19
0
ファイル: models.py プロジェクト: Parbhat/julython.org
 def find_valid_email(self, token):
     result = None
     for email_auth in self.social_auth.filter(provider="email"):
         email = email_auth.uid
         expected = salted_hmac(settings.SECRET_KEY, email).hexdigest()
         if expected == token:
             result = email_auth
     return result
コード例 #20
0
 def generate_security_hash(self, object_pk, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     info = (object_pk, timestamp)
     key_salt = "vodkamartiniqa.forms.AnswerSecurityForm"
     value = "-".join(info)
     return salted_hmac(key_salt, value).hexdigest()
コード例 #21
0
ファイル: views.py プロジェクト: h4l/RavenPy
def _get_per_session_raven_secret(request):
    """Gets a pseudorandom string which is always the same for a given session,
    but does not leak any information about the session (e.g. the actual session
    id). 
    """
    session_key = request.session.session_key
    assert session_key, "session_key must not be empty"
    hmac = salted_hmac(settings.RAVEN_ANTI_CSRF_HMAC_SALT, session_key)
    return hmac.hexdigest()
コード例 #22
0
ファイル: models.py プロジェクト: panuta/openreader
    def create_invitation(self, email, organization, groups, created_by):
        key_salt = 'domain.models.UserInvitationManager' + settings.SECRET_KEY
        encode_key = (email+organization.slug).encode('utf-8')
        invitation_key = salted_hmac(key_salt, encode_key).hexdigest()

        invitation = self.create(email=email, organization=organization, invitation_key=invitation_key, created_by=created_by)
        invitation.groups = groups

        return invitation
コード例 #23
0
ファイル: utils.py プロジェクト: cognitiva/django-twostepauth
 def _make_token(self, user, timestamp):
     """
     Internal generation of the token based in the user and timestamp
     """
     key_salt = "RememberComputerTokenGenerator"
     ts_b36 = int_to_base36(timestamp)
     value = unicode(user.id) + unicode(timestamp)
     hash = salted_hmac(key_salt, value).hexdigest()[::2]
     return "%s-%s" % (ts_b36, hash)
コード例 #24
0
ファイル: views.py プロジェクト: agoravoting/agora-identity
def check_hmac(hmac, value):
    '''
    Checks the hmac
    '''
    hmac_calculated = salted_hmac(key_salt=settings.LOGIN_HMAC_SALT,
                                  value=value,
                                  secret=settings.LOGIN_HMAC_SECRET)
    print("hmac_calculated = /auth/%s/%s" % (hmac_calculated.hexdigest(), value))
    return constant_time_compare(hmac, hmac_calculated.hexdigest())
コード例 #25
0
ファイル: forms.py プロジェクト: RobinRamael/django-files
 def generate_security_hash(self, content_type, object_id, timestamp):
     """
     Generate a HMAC security hash from the provided info.
     """
     ctype = u".".join((content_type.app_label, content_type.model))
     info = (ctype, object_id, timestamp)
     key_salt = "files.forms.AttachmentForm"
     value = "-".join(info)
     return salted_hmac(key_salt, value).hexdigest()
コード例 #26
0
    def hash_answer(self, answer, timestamp):
        timestamp = str(timestamp)
        answer = str(answer)
        hashed = ''

        for _ in range(CAPTCHA_ITERATIONS):
            hashed = salted_hmac(timestamp, answer).hexdigest()

        return hashed
コード例 #27
0
    def _make_token_with_timestamp(self, user, timestamp):
        """ Token function pulled from Django 1.11 """
        ts_b36 = int_to_base36(timestamp)

        hash = salted_hmac(
            self.key_salt,
            unicode(user.pk) + unicode(timestamp)
        ).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #28
0
ファイル: utils.py プロジェクト: Codeprh/django-users2
    def _make_token_with_timestamp(self, user, timestamp):

        ts_b36 = int_to_base36(timestamp)
        key_salt = 'users.utils.EmailActivationTokenGenerator'
        login_timestamp = '' if user.last_login is None else \
            user.last_login.replace(microsecond=0, tzinfo=None)
        value = (six.text_type(user.pk) + six.text_type(user.email) +
                 six.text_type(login_timestamp) + six.text_type(timestamp))
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return '%s-%s' % (ts_b36, hash)
コード例 #29
0
ファイル: tokens.py プロジェクト: jonaqp/heroku
    def _make_token_with_timestamp(self, user, timestamp):

        ts_b36 = int_to_base36(timestamp)

        key_salt = "tokenapi.tokens.PasswordResetTokenGenerator"

        value = (
            six.text_type(user.pk) + user.password + six.text_type(timestamp))
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #30
0
ファイル: utils.py プロジェクト: Doist/powerapp
def validate_webhook_token(string):
    """
    Verifies the webhook token, andn raises "Invalid webhook token" exception,
    or return {u: <user_id>, i: <integration_id>} dict
    """
    token, qs = parse.splitquery(string)
    expected_token = salted_hmac(WEBHOOK_HMAC_SALT, qs or '').hexdigest()
    if not constant_time_compare(token, expected_token):
        raise PowerAppError('Invalid Webhook token')
    return dict(parse.parse_qsl(qs))
コード例 #31
0
ファイル: base_user.py プロジェクト: GentleWarrior/RBMR
 def get_session_auth_hash(self):
     """
     Return an HMAC of the password field.
     """
     key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
     return salted_hmac(
         key_salt,
         self.password,
         # RemovedInDjango40Warning: when the deprecation ends, replace
         # with:
         # algorithm='sha256',
         algorithm=settings.DEFAULT_HASHING_ALGORITHM,
     ).hexdigest()
コード例 #32
0
    def get_session_auth_hash(self):
        """Return a hash used to invalidate sessions of users when necessary.

        Can return None if auth_id is not set on this user."""
        if self.auth_id is None:
            # Old user that has not re-logged since we introduced that field,
            # return None, it won't be used by django session invalidation
            # mechanism.
            return None
        # Mimic what the AbstractBaseUser implementation does, but with our
        # own custom field instead of password, which we don't have.
        key_salt = 'olympia.models.users.UserProfile.get_session_auth_hash'
        return salted_hmac(key_salt, str(self.auth_id)).hexdigest()
コード例 #33
0
ファイル: video_calls.py プロジェクト: yurakozlovskiy/zulip
def get_zoom_sid(request: HttpRequest) -> str:
    # This is used to prevent CSRF attacks on the Zoom OAuth
    # authentication flow.  We want this value to be unpredictable and
    # tied to the session, but we don’t want to expose the main CSRF
    # token directly to the Zoom server.

    csrf.get_token(request)
    # Use 'mark_sanitized' to cause Pysa to ignore the flow of user controlled
    # data out of this function. 'request.META' is indeed user controlled, but
    # post-HMAC output is no longer meaningfully controllable.
    return mark_sanitized(
        "" if getattr(request, "_dont_enforce_csrf_checks", False) else
        salted_hmac("Zulip Zoom sid", request.META["CSRF_COOKIE"]).hexdigest())
コード例 #34
0
ファイル: tokens.py プロジェクト: TUBklima/DMS_backend
 def _make_token_with_timestamp(self, user_pk, timestamp, action):
     # timestamp is number of days since 2001-1-1.  Converted to
     # base 36, this gives us a 3 digit string until about 2121
     ts_b36 = int_to_base36(timestamp)
     # convert the user pk to bytes. We can not assume it will always be an int
     pk_byte = str(user_pk).encode('UTF-8')
     # convert the byte representation to something that can be printed in an url
     pk_b64 = urlsafe_base64_encode(pk_byte)
     hash_string = salted_hmac(
         self.key_salt,
         self._make_hash_value(user_pk, timestamp, action),
         secret=self.secret,
     ).hexdigest()[::2]  # Limit to 20 characters to shorten the URL.
     return "%s-%i-%s-%s" % (pk_b64, action.value, ts_b36, hash_string)
コード例 #35
0
ファイル: tokens.py プロジェクト: btbroot/exmo2010
    def _make_hash(self, user, timestamp):
        # By hashing on the internal state of the user and using state
        # that is sure to change (the password salt will change as soon as
        # the password is set, at least for current Django auth, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.

        # Ensure results are consistent across DB backends
        login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None)

        userdata = six.text_type(
            user.pk) + user.password + six.text_type(login_timestamp)
        return salted_hmac(self.key_salt, userdata +
                           six.text_type(timestamp)).hexdigest()[::2]
コード例 #36
0
 def make_token(self, project):
     """
     Return a token that can be used to upload archives throug the API.
     After hash is calculated, we concat the project id in order to simplify
     the token check, otherwise we would have to go through all the objects
     in the database.
     """
     project_b36 = int_to_base36(project.pk)
     digest = salted_hmac(
         self.key_salt,
         self._make_hash_value(project),
         secret=self.secret,
     ).hexdigest()
     return "{project}-{digest}".format(project=project_b36, digest=digest)
コード例 #37
0
def _make_token_with_timestamp(user, ip_address, timestamp):
    ts_b36 = int_to_base36(timestamp)
    uid_b36 = int_to_base36(user.id)

    key_salt = 'WebSocketTokenGenerator'

    # ws_auth_key_salt allows the user's ws token to be invalidated, it should return a string,
    # changing that string will invalidate the websocket token
    no_user_key_salt = lambda: ''
    custom_key_salt = getattr(user, 'ws_auth_key_salt', no_user_key_salt)()

    value = uid_b36 + user.password + str(ip_address) + str(custom_key_salt) + str(timestamp)
    hash = salted_hmac(key_salt, value).hexdigest()
    return '%s-%s-%s' % (ts_b36, uid_b36, hash)
コード例 #38
0
    def get_session_auth_hash(self):
        """
        Return an HMAC of the password field.
        """

        # utiliser le même salt pour ne pas invalider les sessions
        key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"

        to_hash = self.password

        if self.type == self.PERSON_ROLE and self.person:
            to_hash += self.person.auto_login_salt

        return salted_hmac(key_salt, to_hash).hexdigest()
コード例 #39
0
ファイル: tokens.py プロジェクト: g10f/sso
    def _make_token_with_timestamp(user_email, timestamp):
        # timestamp is number of minutes since 2001-1-1.  Converted to
        # base 36, this gives us a 6 digit string until later then 3000
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user_email we produce a hash that will be
        # invalid as soon as the email, user or confirmed flag changed.
        # We limit the hash to 20 chars to keep URL short
        key_salt = "sso.accounts.tokens.EmailConfirmationTokenGenerator"

        value = (str(user_email.user.pk) + user_email.email + str(user_email.confirmed) +
                 str(timestamp))
        hash_value = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash_value)
コード例 #40
0
ファイル: tokens.py プロジェクト: Ganibalishe/ossp
 def _make_token_with_timestamp(self, user, timestamp, legacy=False):
     # timestamp is number of seconds since 2001-1-1. Converted to base 36,
     # this gives us a 6 digit string until about 2069.
     ts_b36 = int_to_base36(timestamp)
     hash_string = salted_hmac(
         self.key_salt,
         self._make_hash_value(user, timestamp),
         secret=self.secret,
         # RemovedInDjango40Warning: when the deprecation ends, remove the
         # legacy argument and replace with:
         #   algorithm=self.algorithm,
         algorithm='sha1' if legacy else self.algorithm,
     ).hexdigest()[::2]  # Limit to 20 characters to shorten the URL.
     return "%s-%s" % (ts_b36, hash_string)
コード例 #41
0
    def _make_token_with_timestamp(self, instance, timestamp, flag=None):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the instance and using state
        # that is sure to change (the public salt will change as soon as
        # the public field is changed)
        # We limit the hash to 20 chars to keep URL short
        hash = salted_hmac(
            self.key_salt,
            self._make_hash_value(instance, timestamp, flag),
        ).hexdigest()[::2]
        return '{}-{}'.format(ts_b36, hash)
コード例 #42
0
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        key_salt = "portfoliyo.view.users.tokens.EmailConfirmTokenGenerator"

        # By hashing on user ID and email, we ensure this token can only ever
        # be used to confirm this email address for this user.
        value = (unicode(user.id) + user.email + unicode(timestamp))

        # We limit the hash to 20 chars to keep URL short
        hash = salted_hmac(key_salt, value).hexdigest()[::2]

        return "%s-%s" % (ts_b36, hash)
コード例 #43
0
ファイル: __init__.py プロジェクト: g10f/sso
def get_session_auth_hash(user, client=None):
    # Returns an HMAC of the password and client_secret field.
    if user is None:
        logger.debug("get_session_auth_hash with user == None")
        return ""
    key_salt = HASH_SESSION_KEY
    data = user.password
    # deactivate session when user was deactivated
    # TODO: write test
    if not user.is_active:
        data += "0"
    if client is not None:
        data += client.client_secret

    auth_hash = salted_hmac(key_salt, data, algorithm='sha256').hexdigest()
    return auth_hash[:10]
コード例 #44
0
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change (the email salt will change since
        # the email address was changed, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short
        key_salt = "apps.user.tokens.ExclusiveClubTokenGenerator"

        value = (unicode(user.id) + user.email + unicode(timestamp))
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #45
0
    def _make_token_with_timestamp(self, email, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change (the password salt will change as soon as
        # the password is set, at least for current Django auth, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short
        key_salt = "cosinnus.core.utils.tokens.EmailBlacklistTokenGenerator"

        value = (email + six.text_type(timestamp))
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #46
0
    def success(self, profile):
        login_successful.send(sender=LinkedAccount, profile=profile)
        if self.api:
            result = {}
            if profile and profile.user:
                user_id = profile.user.id
                result['user_id'] = user_id
                signature = salted_hmac("linked_accounts.views.login", str(user_id)).hexdigest()
                result['hash'] = signature
                result[User.USERNAME_FIELD] = getattr(profile.user, User.USERNAME_FIELD)

            return HttpResponse(
                json.dumps(result),
                mimetype="application/json"
            )
        return redirect(self.get_next_url())
コード例 #47
0
    def _make_token_with_timestamp_fixed(self, user, timestamp, legacy=True):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121

        # current_datetime = datetime.now()
        # timestamp = to_integer(current_datetime)
        #print(timestamp)

        ts_b36 = int_to_base36(timestamp)
        # print(timestamp)
        #print(timestamp)
        hash = salted_hmac(
            self.key_salt,
            self._make_hash_value(user, timestamp),
        ).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #48
0
 def save(self, fail_silently=False):
     try:
         data_request = super(UserDataRequestForm, self).save()
         data_request.token = salted_hmac(
             data_request.request_sent,
             data_request.user_email_address).hexdigest()
         data_request.save()
         subject = "Request for data from OpenfMRI.org"
         body = render_to_string(
             "dataset/user_data_request_email_body.txt",
             {'url': reverse('user_dataset', args=[data_request.token])})
         send_mail(subject, body, '*****@*****.**',
                   [data_request.user_email_address], fail_silently)
         return data_request
     except smtplib.SMTPException:
         raise smtplib.SMTPException
コード例 #49
0
ファイル: tokens.py プロジェクト: kahihia/django
    def _make_token_with_timestamp(self, instance, num_days):
        # num_days is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        nd_b36 = int_to_base36(num_days)

        # By hashing on the internal state of the instance and using state
        # that is sure to change (must be implemented by subclasses), we
        # can produce a hash that only works for this instance and will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short.
        default_state = (instance._meta.app_label, instance._meta.model_name,
                         six.text_type(instance.pk), six.text_type(num_days))
        value = u"".join(default_state + tuple(self._instance_state(instance)))

        hash = salted_hmac(self.key_salt, value).hexdigest()[::2]
        return "%s-%s" % (nd_b36, hash)
コード例 #50
0
def create_multi_use_login_hash(user, used_for='default'):
    """
    Creates a hash that can be used to login or identify
    a user multiple times (works until the user changes
    their username or password).

    Works by hashing ``used_for``, the user's username and password hash.

    :param str used_for: An arbitrary string to identify the use of
        this hash, so as not to conflict if using multiple
        different purposes for login hashes.
    """
    value = user.username + user.password + used_for
    hash = salted_hmac(KEY_SALT, value).hexdigest()
    uidb64 = force_text(urlsafe_base64_encode(force_bytes(user.pk)))
    return '{}+{}'.format(uidb64, hash)
コード例 #51
0
def make_timed_token(user_id, minutes, persistent=0, test_value_now=None):
    """Make a URL-safe timed token that's valid for minutes minutes.

    This is meant for use with confirmation mails to avoid having to
    hold state on the server.

    The token is tied to a specific user to avoid frauds where a token
    is used to validate a different user than the one intended (i.e.,
    to validate a user whose email the person doesn't control or by
    simple fishing for user id).  We insert a random number (and our
    own secret key) to avoid replay attacks.

    The integer persistent is meant for setting session cookies, but
    these functions make no assumption other than that it is an
    integer.  The auth functions should assume that 0 means unchecked
    "remember me" and 1 means "remember me" and anything else is
    invalid.

    The test_value_now is for testing and should not normally be set.

    """

    # As this function should only be used for auth, once_token value must be set to True before
    # to make token used only once. If not set to True token may not be created

    user = User.objects.get(pk=user_id)

    user.profile.once_token = True
    user.save()

    if user.profile.once_token:

        secret = settings.SECRET_KEY
        rand_value = secrets.token_urlsafe(20)
        if test_value_now is not None:
            now = test_value_now
        else:
            now = datetime.datetime.now().timestamp()
        soon_seconds = int_to_base36(int(now + 60 * minutes))
        persistent_str = int_to_base36(int(persistent))
        hmac = salted_hmac(soon_seconds + persistent_str, rand_value + str(user_id)).hexdigest()[:20]
        return '{rnd}|{u}|{t}|{p}|{h}'.format(
            rnd=rand_value,
            u=user_id,
            t=soon_seconds,
            p=persistent_str,
            h=hmac)
コード例 #52
0
def _parse_token(token, salt):
    try:
        payload, sig = token.split('.')
    except ValueError:
        raise ValidationError("Invalid signup link!")

    mac = salted_hmac(salt, payload).digest()

    if mac != urlsafe_base64_decode(sig):
        raise ValidationError("Corrupted signup link!")

    content = json.loads(urlsafe_base64_decode(payload).decode('utf-8'))

    if content['ts'] < calendar.timegm(time.gmtime()) - (60 * 60 * 1):
        raise ValidationError("Link has expired!")

    return content
コード例 #53
0
ファイル: utils.py プロジェクト: Shriukan33/tn_web
def token_valid(timed_token):
    """Validate a timed token.

    Return the user id for which the token is valid, if the token is
    valid.  Return -1 if the token is not (either because it is
    malformed or because it has expired).

    """
    the_rand_value, the_user_id, the_soon, the_hmac = timed_token.split('|')
    computed_hmac = salted_hmac(the_soon, the_rand_value +
                                str(the_user_id)).hexdigest()[:20]
    if computed_hmac != the_hmac:
        return -1
    now = datetime.datetime.now().timestamp()
    if now > base36_to_int(the_soon):
        return -1
    return int(the_user_id)
コード例 #54
0
ファイル: tokens.py プロジェクト: Goutham2591/OMK_PART2
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change (the password salt will change as soon as
        # the password is set, at least for current Django auth, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short

        hash = salted_hmac(
            self.key_salt,
            self._make_hash_value(user, timestamp),
        ).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #55
0
    def _generate_token(self, save=True):
        """
        Generate token using sessionid and time_asked

        """

        if not self.time_asked:
            self.time_asked = datetime.now()

        ts_b36 = int_to_base36(int(time.mktime(self.time_asked.timetuple())))
        hash = salted_hmac(settings.SECRET_KEY,
                           six.text_type(self.sessionid)).hexdigest()

        self.token = f'{ts_b36}-{hash}'

        if save:
            self.save()
コード例 #56
0
ファイル: views.py プロジェクト: shreyarora12/julython.org
def send_verify_email(email, user_id, domain):
    token = salted_hmac(SECRET, email).hexdigest()
    c = {
        'email': email,
        'domain': domain,
        'uid': int_to_base36(user_id),
        'token': token
    }
    subject = _('Julython - verify your email')
    html = loader.render_to_string('registration/verify_email.html', c)
    text = strip_tags(html)
    msg = EmailMultiAlternatives(subject, text, None, [email])
    msg.attach_alternative(html, 'text/html')
    try:
        msg.send()
    except:
        logging.exception("Unable to send email!")
コード例 #57
0
    def test_make_token_with_timestamp(self):
        tola_user = factories.TolaUser()
        timestamp = self.token_generator._num_days(
            self.token_generator._today())

        test_hash = (
            six.text_type(True) + tola_user.tola_user_uuid.__str__()
            + six.text_type(timestamp)
        )

        ts_b36 = int_to_base36(timestamp)
        hash = salted_hmac(self.token_generator.key_salt,
                           test_hash).hexdigest()[::2]

        generated_hash = self.token_generator._make_token_with_timestamp(
            tola_user, timestamp, flag=True)
        self.assertEqual(generated_hash, '{}-{}'.format(ts_b36, hash))
コード例 #58
0
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change (the password salt will change as soon as
        # the password is set, at least for current Django auth, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short
        key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
        value = unicode(user.id) + \
            user.password + user.last_login.strftime('%Y-%m-%d %H:%M:%S') + \
            unicode(timestamp)
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
コード例 #59
0
    def test_check_token_invalid_token(self):
        dashboard = factories.Dashboard(
            public={'all': False, 'org': False, 'url': True})
        timestamp = self.token_generator._num_days(
            self.token_generator._today())

        test_hash = (
                six.text_type(True) + dashboard.dashboard_uuid.__str__() +
                six.text_type(timestamp)
        )

        hash = salted_hmac(self.token_generator.key_salt,
                           test_hash).hexdigest()[::2]
        final_hash = '{}-{}'.format(timestamp, hash)

        is_valid = self.token_generator.check_token(dashboard, final_hash)
        self.assertFalse(is_valid)
コード例 #60
0
ファイル: views.py プロジェクト: rboulton/behabitual
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change, we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short

        # Ensure results are consistent across DB backends
        login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None)

        value = (six.text_type(user.pk) + user.password +
                six.text_type(login_timestamp) + six.text_type(timestamp))
        hash = salted_hmac(self.key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)