# Secure File Upload and Access on Cloud with Encryption and Access Control
# Install libraries:
# pip install cryptography boto3


# 1. init_db.py – Setup User-Role Database
# Create database and store user roles

import sqlite3

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

cur.execute("""
CREATE TABLE IF NOT EXISTS users (
    username TEXT PRIMARY KEY,
    role TEXT NOT NULL,
    token TEXT NOT NULL
)
""")

cur.execute("INSERT OR IGNORE INTO users VALUES ('alice', 'admin', 'token123')")
cur.execute("INSERT OR IGNORE INTO users VALUES ('bob', 'user', 'token456')")

conn.commit()
conn.close()

print("Database initialized!")


# 2. generate_keys.py – AES Key Generation
# Generate and save AES encryption key

from cryptography.fernet import Fernet

key = Fernet.generate_key()

with open("secret.key", "wb") as f:
    f.write(key)

print("AES key generated!")


# 3. s3_setup.py – Connect to AWS S3 (or Mock)
# Connect to AWS S3

import boto3

s3 = boto3.client("s3")

bucket = "secure-cloud-files"

if bucket not in [b["Name"] for b in s3.list_buckets()["Buckets"]]:
    s3.create_bucket(Bucket=bucket)

print("S3 bucket ready!")


# 4. cloud_encrypt_upload.py – Encrypt and Upload File
# Encrypt file and upload to S3

import boto3
from cryptography.fernet import Fernet

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

cipher = Fernet(key)

filename = "sample.txt"

with open(filename, "rb") as f:
    data = f.read()

encrypted = cipher.encrypt(data)

s3 = boto3.client("s3")
s3.put_object(
    Bucket="secure-cloud-files",
    Key=filename,
    Body=encrypted
)

print("Encrypted file uploaded!")


# 5. cloud_download_decrypt.py – Role-Based Secure Download
# Download and decrypt file using role-based access

import sqlite3
import boto3
from cryptography.fernet import Fernet

token = input("Enter token: ")

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

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

if result and result[0] in ("admin", "user"):
    with open("secret.key", "rb") as f:
        key = f.read()

    cipher = Fernet(key)
    s3 = boto3.client("s3")

    data = s3.get_object(
        Bucket="secure-cloud-files",
        Key="sample.txt"
    )["Body"].read()

    decrypted = cipher.decrypt(data)

    with open("downloaded_sample.txt", "wb") as f:
        f.write(decrypted)

    print("File downloaded successfully!")

else:
    print("Access denied!")


# Execution order:
# 1. init_db.py
# 2. generate_keys.py
# 3. s3_setup.py
# 4. cloud_encrypt_upload.py
# 5. cloud_download_decrypt.py
# Important practical notes:
# - This uses Fernet (AES-128-CBC with authentication) for simple file encryption, rather than raw AES.
# - Both admin and user roles currently have download permission.
# - For local testing without AWS, install LocalStack and configure the boto3 client with its endpoint URL.
# - Keep secret.key secure. Anyone possessing it can decrypt the files