I was wondering about the safety of some thing in my app.py flask app. First the database, I'm using mysql and currently I am connecting to it in the following way:
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'databasename'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
And to me this feels very weird, just putting in your password in plain text etc. I've been searching online but have not found any other way of doing this other than putting it in a seperate python file and just importing it. Which kinda feels like doing nothing at all.. Is there a better way to do this security wise?
Then the secret key I use for password encoding. Which is also just stored in plain text in my code, is there also a way to make this more secure or make it less obvious?
Thanks in advance!
The computer which runs your code needs to know the password, so you can't secure against the owner of the computer (if that's not you). But if you are having the password in the sourcecode it can easily happen that you put it into version control and if you use a public github it can easily happen that you publish your key.
As alternative you can put the password in a config file (take care to not put it into version control e.g. via .gitignore) or you can use environmental variables.
I would suggest to store the credentials in the OS environment.
app.config['MYSQL_HOST'] = os.environ.get('HOST')
app.config['MYSQL_USER'] = os.environ.get('USER')
app.config['MYSQL_PASSWORD'] = os.environ.get('PASSWORD')
app.config['MYSQL_DB'] = os.environ.get('DB')
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
It will help you to get those information from a standalone application or as a dockerized application (using docker file).
Another way is .env file
pip install python-dotenv
from dotenv import load_dotenv
load_dotenv()
class Config:
SECRET_KEY = os.getenv("SECRET_KEY")
Remember to gitignore .env as well
Related
I have a flask application where I login to another service for which I need login data. So I have my endpoint in the flask application /service and this endpoint uses a username and password which I currently have in clear text, meaning
#app.route('/service'), methods = ['GET','POST'])
def access_service(test: str):
username = 'user1'
password = 'passwordincleartext'
req = 'https://anotherservice.com/'
headers = {'Content-type': 'application/json'}
HTTPAUTH = HTTPBasicAuth(username, password)
my_data = '''{"myjsonfield":''' + test + '''}'''
requests.get(req,headers=headers,data=my_data,auth=HTTPAUTH)
My problem is that I can not provide the username and password with the request because another program is using my flask application and this program is an external one where I can not manipulate the request on /service. Is there a way to use a username and password securely, meaning not in clear text, in flask, without having to create a database?
Your passwords or any login credentials should not be included in your code, for that it's preferable and more secure to use something like dot.env, and you'll keep this based to where you project is and not upload this file any way, not even your github repo. please check the following it's a simple and clear explanation of how you can use dot.env
https://dev.to/emma_donery/python-dotenv-keep-your-secrets-safe-4ocn
I suggest you create 2 files, where one will be local to each machine running the code and one will be pushed to github with your code where it shows only the variable names, and example bellow:
# .env file (local machine specific)
USERNAME=user1
PASSWORD=passwordincleartext
# example.env file (pushed with your code)
USERNAME=<ask-from-maintainer>
PASSWORD=<ask-from-maintainer>
NOTE: example.env file will not be used in your code, but you will need it if you are running the code on a different machine, this way all you need is to copy and paste the file, rename it to .env and replace the variables values with the right credentials. This way when you run your code it will work on the new environment without any issue
I'm a newbie learning flask. I found this following code in YouTube. He said he has configured the email USERNAME & PASSWORD in 'config.cfg'. Could anyone please tell me how this can be done. How to configure those values in 'config.cfg'?
You should create config.cfg file. Inside this file, you should store all your configurations.
config.cfg
MAIL_USERNAME = 'your#mail.com'
MAIL_PASSWORD = 'YourPa$$w0rd'
If you any other configs you can add in the file like above and import it like below:
app.config.from_pyfile('config.cfg')
Just wondering locally, I could access environment variables within google app engine? For example, I've stored an email and password and would like to access it like this:
import os
email = os.environ.get("EMAIL")
password = os.environ.get("PASSWORD")
Is there any way to do this?
You can define variables in app.yaml to make them available to the os.environ dictionary:
env_variables:
EMAIL: 'email#example.com'
Then access the variable with:
email = os.environ.get("EMAIL")
More info is in the documentation.
How can I send "AUTH" command to authenticate the connection using Flask-Redis in Flask app?
I know Flask-Redis is just a small wrapper for redis-py but I can't figure out how to handle the authorization.
Do you mean this Flask_Redis: https://pypi.python.org/pypi/Flask-Redis/0.0.5 ?
If so, there is a better way to handle this than placing it in the URL. According to the docs, in your Flask config place the following:
REDIS_HOST = "localhost"
REDIS_PASSWORD = "password"
REDIS_PORT = 6379
If placing the config in code, as in your example:
app.config["REDIS_PASSWORD"] = 'password'
Doing this in the config should be more maintainable and configurable without modifying code.
Ok I have found how to solve this.
You can pass the password in URL, example:
...
app.config["REDIS_URL"] = 'redis://:password#localhost/0'
redis_db = Redis(app, "REDIS")
...
I'm working with some friends to build a PostgreSQL/SQLAlchemy Python app and have the following line:
engine = create_engine('postgresql+pg8000://oldmba#localhost/helloworld')
Newbie question: Instead of having to edit in "oldmba" (my username) all the time whenever I git pull someone else's code, what's the simple way to make that line equally applicable to all users so we don't have to constantly edit it? Thanks in advance!
have a config file with your settings.
It can store data in python config dictionary or variables
The config file can import from a local_settings.py file. This file can be ignored in your gitignore. It can contain your individdual settings , username , password, database urls, pretty much anything that you need to configure and that may differ depending on your enviornment (production vs devel)
This is how settings in django projects are usually handled. It allows for multiple users to devlop on the same project with different settings. You might want a 'database_url' field or something too so on production if you need to set your database to a different server but on development you use 'localhost'
# config.py
database = {
'username': 'production_username',
'password': 'production_password'
}
try:
from local_config import *
catch ImportError:
pass
# local_config.py
database = {
'username': 'your_username',
'password': 'your_password'
}
from config import *
engine = create_engine('postgresql+pg8000://{0}#localhost/helloworld'.format(database['username']))