2024-10-23 11:38:01 +00:00
|
|
|
import logging
|
2024-01-09 18:58:09 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from typing import Optional
|
|
|
|
from selfprivacy_api.migrations.migration import Migration
|
|
|
|
from selfprivacy_api.models.tokens.token import Token
|
|
|
|
|
|
|
|
from selfprivacy_api.repositories.tokens.redis_tokens_repository import (
|
|
|
|
RedisTokensRepository,
|
|
|
|
)
|
|
|
|
from selfprivacy_api.repositories.tokens.abstract_tokens_repository import (
|
|
|
|
AbstractTokensRepository,
|
|
|
|
)
|
|
|
|
from selfprivacy_api.utils import ReadUserData, UserDataFiles
|
|
|
|
|
2024-10-23 11:38:01 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2024-01-09 18:58:09 +00:00
|
|
|
|
|
|
|
class WriteTokenToRedis(Migration):
|
|
|
|
"""Load Json tokens into Redis"""
|
|
|
|
|
2024-06-26 12:00:51 +00:00
|
|
|
def get_migration_name(self) -> str:
|
2024-01-09 18:58:09 +00:00
|
|
|
return "write_token_to_redis"
|
|
|
|
|
2024-06-26 12:00:51 +00:00
|
|
|
def get_migration_description(self) -> str:
|
2024-01-09 18:58:09 +00:00
|
|
|
return "Loads the initial token into redis token storage"
|
|
|
|
|
|
|
|
def is_repo_empty(self, repo: AbstractTokensRepository) -> bool:
|
|
|
|
if repo.get_tokens() != []:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def get_token_from_json(self) -> Optional[Token]:
|
|
|
|
try:
|
|
|
|
with ReadUserData(UserDataFiles.SECRETS) as userdata:
|
|
|
|
return Token(
|
|
|
|
token=userdata["api"]["token"],
|
|
|
|
device_name="Initial device",
|
|
|
|
created_at=datetime.now(),
|
|
|
|
)
|
|
|
|
except Exception as e:
|
2024-10-23 11:38:01 +00:00
|
|
|
logging.error(e)
|
2024-01-09 18:58:09 +00:00
|
|
|
return None
|
|
|
|
|
2024-06-26 12:00:51 +00:00
|
|
|
def is_migration_needed(self) -> bool:
|
2024-01-09 18:58:09 +00:00
|
|
|
try:
|
|
|
|
if self.get_token_from_json() is not None and self.is_repo_empty(
|
|
|
|
RedisTokensRepository()
|
|
|
|
):
|
|
|
|
return True
|
|
|
|
except Exception as e:
|
2024-10-23 11:38:01 +00:00
|
|
|
logging.error(e)
|
2024-01-09 18:58:09 +00:00
|
|
|
return False
|
2024-06-26 12:00:51 +00:00
|
|
|
return False
|
2024-01-09 18:58:09 +00:00
|
|
|
|
2024-06-26 12:00:51 +00:00
|
|
|
def migrate(self) -> None:
|
2024-01-09 18:58:09 +00:00
|
|
|
# Write info about providers to userdata.json
|
|
|
|
try:
|
|
|
|
token = self.get_token_from_json()
|
|
|
|
if token is None:
|
2024-10-23 11:38:01 +00:00
|
|
|
logging.error("No token found in secrets.json")
|
2024-01-09 18:58:09 +00:00
|
|
|
return
|
|
|
|
RedisTokensRepository()._store_token(token)
|
|
|
|
|
2024-10-23 11:38:01 +00:00
|
|
|
logging.error("Done")
|
2024-01-09 18:58:09 +00:00
|
|
|
except Exception as e:
|
2024-10-23 11:38:01 +00:00
|
|
|
logging.error(e)
|
|
|
|
logging.error("Error migrating access tokens from json to redis")
|