We all make mistakes, especially when starting out. Recently, the ultimate developer mishap happened to me: I accidentally pushed my Django SECRET_KEY to a public GitHub repository.
In Django, the SECRET_KEY is used for cryptographic signing, like session cookies or password reset tokens. It is essential for protecting sensitive data and preventing tampering or unauthorized access. Leaving it publicly exposed is a massive NO-GO.
But that is exactly what learning projects are for! Luckily this happened to a project with no real user data. We learn the most from our mistakes, and I now know exactly how to handle this situation. Here is how to fix it:
Simply changing the key in your code and pushing it again is not enough. The old key remains visible forever in your GitHub commit history. The first step is damage control, so we need to generate a new key. Start the Python shell in your project terminal:
python manage.py shell
Then enter the following lines:
from django.core.management.utils import get_random_secret_key
print(get_random_secret_key())
The first line imports the required utility function and the second line generates the new key and prints it to the terminal so you can copy it.
(Note: If you want to be completely secure, you should also purge you Git history using tools like git-filter-repo or temporarily take the sensitive repository offline).
Step 2: Move the Secret Key to environment variables
To make sure this never happens again, I moved the key into a .env file. Create this file in your root directory and make sure to add it to your .gitignore file so it never gets tracked by GitHub.
To load the environment variables from the .env file into the Django project, we use the python-dotenv library. Install it first:
pip install python-dotenv
Next update your settings.py file like this:
import os
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv("SECRET_KEY")
Finally store your actual key inside the .env file:
SECRET_KEY="your_new_secret_key_here"
Conclusion: Mistakes happen, it's how you handle them that matters
Thanks to this faux pas my Django project is now secure and follows configuration management best practices. My brain has permanently saved this lesson so it won't happen again! 😊