def create_and_return(self, **kwargs):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        expires = kwargs.get('expires', None)
        if expires is not None:
            expires = timezone.now() + expires

        kwargs.update({
            'digest': digest,
            'salt': salt,
            'expires': expires,
            'token_key': token[:CONSTANTS.TOKEN_KEY_LENGTH]
        })

        auth_token = super(AuthTokenManager, self).create(**kwargs)
        auth_token.token = token

        return auth_token

        kwargs.update({
            'digest': digest,
            'salt': salt,
            'expires': expires
        })

        auth_token = super(AuthTokenManager, self).create(**kwargs)
        auth_token.token = token

        return auth_token
    def _create_user_tokens(self):
        # Hard code tokens used in gcapi integration tests
        user_tokens = {
            "admin": "1b9436200001f2eaf57cd77db075cbb60a49a00a",
            "retina": "f1f98a1733c05b12118785ffd995c250fe4d90da",
            "algorithmuser": "******",
            "readerstudy": "01614a77b1c0b4ecd402be50a8ff96188d5b011d",
            settings.RETINA_IMPORT_USER_NAME: "e8db90bfbea3c35f40b4537fdca9b3bf1cd78a51",
        }

        out = f"{'*' * 80}\n"
        for user, token in user_tokens.items():
            salt = crypto.create_salt_string()
            digest = crypto.hash_token(token, salt)

            AuthToken(
                token_key=token[: CONSTANTS.TOKEN_KEY_LENGTH],
                digest=digest,
                salt=salt,
                user=self.users[user],
                expiry=None,
            ).save()

            out += f"\t{user} token is: {token}\n"
        out += f"{'*' * 80}\n"
        logger.debug(out)
def _create_user_tokens(users):
    # Hard code tokens used in gcapi integration tests
    user_tokens = {
        "admin": "1b9436200001f2eaf57cd77db075cbb60a49a00a",
        "retina": "f1f98a1733c05b12118785ffd995c250fe4d90da",
        "readerstudy": "01614a77b1c0b4ecd402be50a8ff96188d5b011d",
        "demop": "00aa710f4dc5621a0cb64b0795fbba02e39d7700",
    }

    out = f"{'*' * 80}\n"
    for user, token in user_tokens.items():
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        AuthToken(
            token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH],
            digest=digest,
            salt=salt,
            user=users[user],
            expiry=None,
        ).save()

        out += f"\t{user} token is: {token}\n"
    out += f"{'*' * 80}\n"
    logger.debug(out)
Example #4
0
    def create(self,
               user,
               password=None,
               expires=knox_settings.TOKEN_TTL,
               return_instance=False):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        encrypted = None
        if password:
            fernet = Fernet(crypto.derive_fernet_key(password, salt))
            encrypted = fernet.encrypt(encoding.force_bytes(token))

        if expires is not None:
            expires = timezone.now() + expires

        auth_token = super(AuthTokenManager, self).create(digest=digest,
                                                          salt=salt,
                                                          encrypted=encrypted,
                                                          user=user,
                                                          expires=expires)
        if return_instance:
            return auth_token
        return token  # Note only the token - not the AuthToken object - is returned
Example #5
0
    def create(self, user, time=knox_settings.DEFAULT_TOKEN_TTL, use=knox_settings.DEFAULT_TOKEN_USE):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        auth_token = super(AuthTokenManager, self).create(digest=digest, salt=salt, user=user, time=time, use=use)
        return token # Note only the token - not the AuthToken object - is returned
Example #6
0
    def authenticate_credentials(self, token):
        '''
        Due to the random nature of hashing a salted value, this must inspect
        each auth_token individually to find the correct one.

        Tokens that have expired will be deleted and skipped
        '''
        msg = _('Invalid token.')
        for auth_token in AuthToken.objects.filter(
                token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
            for other_token in auth_token.user.auth_token_set.all():
                if other_token.digest != auth_token.digest and other_token.expires is not None:
                    if other_token.expires < timezone.now():
                        other_token.delete()
            if auth_token.expires is not None:
                if auth_token.expires < timezone.now():
                    auth_token.delete()
                    continue
            try:
                digest = hash_token(token, auth_token.salt)
            except TypeError:
                raise exceptions.AuthenticationFailed(msg)
            if digest == auth_token.digest:
                return self.validate_user(auth_token)
        # Authentication with this token has failed
        raise exceptions.AuthenticationFailed(msg)
Example #7
0
    def create(self, user, expires=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        if expires is not None:
             expires = timezone.now() + expires

        auth_token = super(AuthTokenManager, self).create(digest=digest, salt=salt, user=user, expires=expires, token_slice=token[:16])
        return token # Note only the token - not the AuthToken object - is returned
Example #8
0
    def create_unsafe(self, user, expires=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        if expires is not None:
             expires = timezone.now() + expires

        auth_token = super(AuthTokenManager, self).create(digest=digest, salt=salt, user=user, expires=expires)
        return auth_token, token # Note only the token - not the AuthToken object - is returned
Example #9
0
    def ensure_valid_auth_token(self, user, token):
        for auth_token in AuthToken.objects.filter(user=user):
            if auth_token.expires is not None and auth_token.expires < timezone.now():
                auth_token.delete()
                continue
            digest = hash_token(token, auth_token.salt)
            if digest == auth_token.digest:
                return auth_token

        msg = _('Invalid token.')
        raise exceptions.AuthenticationFailed(msg)
Example #10
0
def get_user_by_token(token):
    log.debug("LOGIN - User by token - Token: " + token)
    for auth_token in AuthToken.objects.all():
        digest = hash_token(token, auth_token.salt)
        if (digest == auth_token.digest):
            auth_token.user.backend = 'django.contrib.auth.backends.ModelBackend'
            log.debug("LOGIN - User by token - User found")
            return auth_token.user

    log.error("LOGIN - User by token - User not found")
    return None
Example #11
0
    def create(self, user, expiry=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        if expiry is not None:
            expiry = timezone.now() + expiry

        instance = super(AuthTokenManager, self).create(
            token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH], digest=digest,
            salt=salt, user=user, expiry=expiry)
        return instance, token
Example #12
0
 def refresh_credentials(self, token):
     msg = _('Invalid token.')
     for auth_token in AuthToken.objects.filter(
             token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
         try:
             digest = hash_token(token, auth_token.salt)
         except (TypeError, binascii.Error):
             raise exceptions.AuthenticationFailed(msg)
         if compare_digest(digest, auth_token.digest):
             self.renew_token(auth_token)
             return
     raise exceptions.AuthenticationFailed(msg)
Example #13
0
    def ensure_valid_auth_token(self, user, token):
        for auth_token in AuthToken.objects.filter(user=user):
            if auth_token.expires is not None:
                if auth_token.expires < timezone.now():
                    auth_token.delete()
                    continue
            digest = hash_token(token, auth_token.salt)
            if digest == auth_token.digest:
                return auth_token

        msg = _('Invalid token.')
        raise exceptions.AuthenticationFailed(msg)
Example #14
0
    def create(self, user, expires=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        if expires is not None:
            expires = timezone.now() + expires

        super(AuthTokenManager, self).create(
            token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH], digest=digest,
            salt=salt, user=user, expires=expires)
        # Note only the token - not the AuthToken object - is returned
        return token
Example #15
0
    def create(self, user, expiry=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        digest = crypto.hash_token(token)

        if expiry is not None:
            expiry = timezone.now() + expiry

        instance = super(AuthTokenManager, self).create(
            token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH],
            digest=digest,
            user=user,
            expiry=expiry)
        return instance, token
Example #16
0
def get_token_validity(token):
    log.debug("LOGIN - Get token validity - Token : " + token)
    for auth_token in AuthToken.objects.all():
        digest = hash_token(token, auth_token.salt)
        if (digest == auth_token.digest):
            if auth_token.expires < timezone.now():
                log.error("LOGIN - Get token validity - Token expired")
                return False
            else:
                log.debug("LOGIN - Get token validity - Token valid")
                return True

    log.error("LOGIN - Get token validity - Token not found")
    return False
Example #17
0
    def create(self, user, expires=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        if expires is not None:
            expires = timezone.now() + expires

        super(AuthTokenManager,
              self).create(token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH],
                           digest=digest,
                           salt=salt,
                           user=user,
                           expires=expires)
        # Note only the token - not the AuthToken object - is returned
        return token
Example #18
0
def __delete_token(request):
    try:
        auth = get_authorization_header(request).split()
        if not auth or auth[0].lower() != b'token':
            log.info("Delete Token - No token exist to be deleted")
        if len(auth) == 2:
            # Everything is fine
            token_in_header = auth[1]
            log.info("Delete Token - Delete token " + str(token_in_header))
            for auth_token in AuthToken.objects.all():
                digest = hash_token(token_in_header, auth_token.salt)
                if (digest == auth_token.digest):
                    auth_token.delete()
                    return
    except Exception as e:
        log.error("Delete Token -  Exception triggered")
Example #19
0
    def authenticate_credentials(self, token):
        """
        Due to the random nature of hashing a salted value, this must inspect
        each auth_token individually to find the correct one.

        Tokens that have expired will be deleted and skipped
        """
        for auth_token in AuthToken.objects.all():
            if auth_token.expires is not None:
                if auth_token.expires < timezone.now():
                    auth_token.delete()
                    continue
            digest = hash_token(token, auth_token.salt)
            if digest == auth_token.digest:
                return self.validate_user(auth_token)
        # Authentication with this token has failed
        raise exceptions.AuthenticationFailed(_("Invalid token."))
Example #20
0
    def authenticate_credentials(self, token):
        '''
        Due to the random nature of hashing a salted value, this must inspect
        each auth_token individually to find the correct one.

        Tokens that have expired will be deleted and skipped
        '''
        for auth_token in AuthToken.objects.all():
            if auth_token.expires is not None:
                if auth_token.expires < timezone.now():
                    auth_token.delete()
                    continue
            digest = hash_token(token, auth_token.salt)
            if digest == auth_token.digest:
                return self.validate_user(auth_token)
        # Authentication with this token has failed
        raise exceptions.AuthenticationFailed(_('Invalid token.'))
Example #21
0
    def authenticate_credentials(self, token):
        '''
        Due to the random nature of hashing a salted value, this must inspect
        each auth_token individually to find the correct one.

        Tokens that have expired will be deleted and skipped
        '''
        for auth_token in AuthToken.objects.filter(
                token_slice__exact=token[:16]):
            # move the expired tokens deletion into an external manage.py command
            # if auth_token.expires is not None:
            #     if auth_token.expires < timezone.now():
            #         auth_token.delete()
            #         continue
            digest = hash_token(token, auth_token.salt)
            if digest == auth_token.digest:
                return self.validate_user(auth_token)
        # Authentication with this token has failed
        raise exceptions.AuthenticationFailed(_('Invalid token.'))
Example #22
0
    def create(
            self, user, password=None, expires=knox_settings.TOKEN_TTL,
            return_instance=False):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        encrypted = None
        if password:
            fernet = Fernet(crypto.derive_fernet_key(password, salt))
            encrypted = fernet.encrypt(encoding.force_bytes(token))

        if expires is not None:
             expires = timezone.now() + expires

        auth_token = super(AuthTokenManager, self).create(
            digest=digest, salt=salt, encrypted=encrypted,
            user=user, expires=expires)
        if return_instance:
            return auth_token
        return token # Note only the token - not the AuthToken object - is returned
Example #23
0
    def authenticate_credentials(self, token):
        '''
        Due to the random nature of hashing a salted value, this must inspect
        each auth_token individually to find the correct one.

        Tokens that have expired will be deleted and skipped
        '''
        token = token.decode("utf-8")
        for auth_token in AuthToken.objects.filter(
                token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
            if self._cleanup_token(auth_token):
                continue

            try:
                digest = hash_token(token, auth_token.salt)
            except (TypeError, binascii.Error):
                return None
            if compare_digest(digest, auth_token.digest):
                if knox_settings.AUTO_REFRESH and auth_token.expiry:
                    self.renew_token(auth_token)
                return self.validate_user(auth_token)
        return None
Example #24
0
def login_user_by_header_token(request):
    try:
        auth = get_authorization_header(request).split()
        if not auth or auth[0].lower() != b'token':
            log.debug("LOGIN - User by header token - No token exists")
        if len(auth) == 2:
            # Everything is fine
            token_in_header = auth[1]
            log.debug("LOGIN - User by header token - Token found: " +
                      str(token_in_header))
            for auth_token in AuthToken.objects.all():
                digest = hash_token(token_in_header, auth_token.salt)
                if (digest == auth_token.digest):
                    auth_token.user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, auth_token.user)
                    return True
    except Exception as e:
        log.error("LOGIN - User by header token - Exception triggered" +
                  str(e))

    log.error("LOGIN - User by header token - User could not be found")
    return False
Example #25
0
    def authenticate_credentials(self, token):
        '''
        Due to the random nature of hashing a salted value, this must inspect
        each auth_token individually to find the correct one.

        Tokens that have expired will be deleted and skipped
        '''
        msg = _('Invalid token.')
        token = token.decode("utf-8")
        for auth_token in AuthToken.objects.filter(
                token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
            if self._cleanup_token(auth_token):
                continue

            try:
                digest = hash_token(token, auth_token.salt)
            except (TypeError, binascii.Error):
                raise exceptions.AuthenticationFailed(msg)
            if compare_digest(digest, auth_token.digest):
                if knox_settings.AUTO_REFRESH and auth_token.expires:
                    self.renew_token(auth_token)
                return self.validate_user(auth_token)
        raise exceptions.AuthenticationFailed(msg)