import hmac
import hashlib
import time


def generate_csrf_token(uid, yandex_uid, secret_key, timestamp=None) -> str:
    if timestamp is None:
        timestamp = int(time.time())
    payload = f'{uid}:{yandex_uid}:{timestamp}'
    token = hmac.new(
        key=secret_key.encode(),
        msg=payload.encode(),
        digestmod=hashlib.sha1,
    ).hexdigest()
    return f'{token}:{timestamp}'


def check_csrf_token(uid, yandex_uid, secret_key, token_lifetime, csrf_token) -> bool:
    if not uid:
        return False
    if csrf_token is None:
        return False
    current_timestamp = int(time.time())
    token, timestamp = csrf_token.split(':')
    if int(timestamp) + token_lifetime < current_timestamp:
        return False
    expected_token = generate_csrf_token(uid, yandex_uid, secret_key, timestamp)
    return hmac.compare_digest(expected_token, csrf_token)
