# Practical 6 – Cloud Security: Role-Based Download
# Install: pip install boto3 cryptography
# First run init_db, keys, s3_setup, and upload; use the same bucket name as
# those scripts and configure AWS credentials. Run: python p6_cloudSec_download.py
# Enter token456 to download as the example user; output is downloaded_sample.txt.
import sqlite3
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

# Authenticate user
token = input("Enter access token: ")

conn = sqlite3.connect("cloud.db")
cur = conn.cursor()

cur.execute(
    "SELECT username, role FROM users WHERE token = ?",
    (token,)
)
user = cur.fetchone()
conn.close()

if not user:
    print("Access denied.")
    exit()

print("Access granted to:", user[0], "| Role:", user[1])

# Download encrypted file
with open("cloud_storage/sample.txt", "rb") as f:
    encrypted = f.read()

# Read AES key
with open("secret.key", "rb") as f:
    key = f.read()

# Decrypt file
nonce = encrypted[:12]
ciphertext = encrypted[12:]

data = AESGCM(key).decrypt(nonce, ciphertext, None)

# Save decrypted file
with open("downloaded_sample.txt", "wb") as f:
    f.write(data)

print("File downloaded and decrypted successfully.")

# What this code does: checks a user's token, decrypts the stored AES-GCM
# file, and saves the plaintext as downloaded_sample.txt.