This doesn't work. At least not securely. You're trying to replicate the authentication process of a website, but that's not how it works locally on a machine.
When you successfully log in to a website, it'll put an authentication token in your browser. This will be sent every time you visit the site the next time and act like your password. For it to work locally, you'd have to ask the user for the password every time (as in Tomerikoo's answer).
A hack to make it work is to store the some state on the user that tells them that they've logged in. A simple example would be:
login.py
import os
password = input('Please enter password')
if password == "admin":
os.environ['USER_PASSWORD'] = "Logged in"
else:
os.environ['USER_PASSWORD'] = "Not logged in"
main.py
import os
if os.environ.get('USER_PASSWORD', 'Not logged in') == "Logged in":
print('Running code...')
else:
print('Please log in')
This will work but doesn't provide any security at all. The problem is that all code and all data is already in the hand of the user. So they can just set USER_PASSWORD
manually, change the source code, or whatever, and they'll circumvent this security check.
Even checking password == "admin"
isn't secure. It could be more secure if you hashed it by downloading something like passlib
and stored the encrypted password as an environment variable SECRET_PASSWORD
:
from passlib.hash import sha256_crypt
encrypted_password = os.environ.get('SECRET_PASSWORD', '')
password = input('Please enter password')
if sha256_crypt.verify(password, encrypted_password):
# Do something on success.
But even then it's not secure, because you must set USER_PASSWORD
to something which the user can always introspect and figure out.