Alot of time is wasted on re-entering password for every deployment in google app engine launcher. Is there a way I can hard code the email and password in their with a text file? I tried editing the appcfg.py but no use. I understand the risks involved in this approach, however I would still like to know.
Please consider to use --oauth2 param. This may not work with app engine launcher, but it will defenetely work if you will create custom bash script for deployment. You can read more on this page.
If you don't want to enter your login credentials, you can use an
OAuth2 token instead. This token gives access to App Engine, but not
to other parts of your Google account; if your Google account uses
two-factor authentication, you'll find this especially convenient. You
can store this token to permanently log in on this machine.
If you are Sublime Text user you can add this code into your project config file to be able to deploy with a hotkey like CMD + B or CTRL + B. I'm sure its easy to do for most major code editors.
{
"build_systems":
[
{
"name": "App Engine Deploy",
"cmd": ["cd $project_path; appcfg.py --oauth2 update ."],
"shell": true
}
]
}
You cannot hard code password directly but I did this trick to attach password to email parameter to hardcode password in bat files
1. you must backup YOURAPPENGINEURL/google/appengine/tools/appcfg.py.
Then Find following code block in that file
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = self.options.email
if email is None:
email = self.raw_input_fn('Email: ')
password_prompt = 'Password for %s: ' % email
if self.options.passin:
password = self.raw_input_fn(password_prompt)
else:
password = self.password_input_fn(password_prompt)
return (email, password)
This code parse email and prompt password at run time.
2. replace this code block with following code block
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = self.options.email
if email is None:
email = self.raw_input_fn('Email: ')
tmp=email.split(':')
email=tmp[0]
password=tmp[1]
return (email, password)
Then save your appcfg file.
3. now you can hardcode your password with following command
appcfg.py --no_cookies --email=youremail#gmail.com:YOURPASSWORD update ./
4. Important fact is that you can only update your app by attaching password to email. app.cfg never prompt for password
I decided to go with a third party on this issue; utilizing "autoit":
Thank Matt for this
Local $sLauncherPath = "C:\Program Files\Google\google_appengine\launcher\GoogleAppEngineLauncher.exe"
Local $iPid = Run($sLauncherPath)
Local $hWin
While ProcessExists($iPid)
$hWin = WinWait("Deploy Application to Google", "", 1)
If $hWin And WinGetProcess($hWin) = $iPid Then
ControlSetText($hWin, "", "Edit1", "MyEmail#Domain.com")
ControlSetText($hWin, "", "Edit2", "MyPassword123")
ControlClick($hWin, "", "Button2")
WinWaitClose($hWin)
EndIf
WEnd
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 using Firebase authentication to manage my users accounts.
Now, I need to change the uid of the users, then I'm trying to delete the user and import it again with the same password using python.
I'm trying to follow the documentation. But I might be missing something.
So, in the Firebase authentication page, I'm going to menu (in the right upper corner) and getting the base64_signer_key and base64_salt_separator values.
And trying to use the code below to delete the user, import the user and update the other fields:
for user in auth.list_users().iterate_all():
if user.email == 'myname#yahoo.com':
newId = CPF(cpf()).rawValue
oldId = user.uid
print('User: {}'.format(user._data))
# Delete the user
auth.delete_user(oldId)
# Recreate the user
users = [
auth.ImportUserRecord(
uid=newId,
email=user.email,
password_hash=user.password_hash.encode('utf-8'),
password_salt=None
),
]
hash_alg = auth.UserImportHash.scrypt(
key=base64.b64decode(base64_signer_key),
salt_separator=base64.b64decode(base64_salt_separator),
rounds=8,
memory_cost=14
)
try:
result = auth.import_users(users, hash_alg=hash_alg)
print('Successfully imported {0} users. Failed to import {1} users.'.format(
result.success_count, result.failure_count))
for err in result.errors:
print('Failed to import {0} due to {1}'.format(users[err.index].uid, err.reason))
except Exception as e:
print(e)
# Update user
auth.update_user(
newId,
phone_number=user.phone_number,
email_verified=user.email_verified,
display_name=user.display_name,
disabled=user.disabled
)
I'm following this documentation https://firebase.google.com/docs/auth/admin/import-users#import_users_with_firebase_scrypt_hashed_passwords
I'm able to delete and recreate the user, but when I try to login with the same user/password I'm getting FirebaseInvalidPasswordError.
What should I do recreate the user with same password and be able to authenticate in the standard way ?
After many tests, maybe I've managed to find a working way to solve the problem.
First of all, if you have created a new service account private key, go to GCP console here https://console.cloud.google.com/iam-admin/iam?authuser=0&project=[your_firebase-proect-id] and make sure your service account have the "Firebase Authentication" admin rights
(note the service account)
(check permission)
This was my first problem since without that permission, the firebase admin SDK always returns an empty password_salt and the string "UkVEQUNURUQ=" for the password_hash (which translates to "REDACTED").
Once I got the correct password hash and salt for user, your code should looks like this
# Recreate the user
users = [
auth.ImportUserRecord(
uid=newId,
email=user.email,
password_hash=base64.urlsafe_b64decode(user.password_hash),
password_salt=base64.urlsafe_b64decode(user.password_salt)
),
]
Note the base64.urlsafe_b64decode part? I've tried to manually export my probject users with the firebase cli though
firebase auth:export --project [project-id] users.csv
and noticed a big difference: Python password hash was
utfZLdz4phgAnRIKRUOxxFTKmbUEenbV1CbkQC0o4iorXpx-BJsdwofjAQkb1mUAgs_sO49cBv_lT8QuCztRzA== while CSV password hash was utfZLdz4phgAnRIKRUOxxFTKmbUEenbV1CbkQC0o4iorXpx+BJsdwofjAQkb1mUAgs/sO49cBv/lT8QuCztRzA== (in python slashes are undercores)
Don't know if my approach would cover all cases, but exporting auth from the cli and comparing their hashes with the python ones could lead you to solve further cases.
I am currently trying to push to Git via GitPython using HTTPS. I am able to do this successfully, but I am prompted to enter my username and password for every fetch, push, and pull operation.
I would like to have my username and password be entered as command line arguments as my script makes a couple of git interactions. This repo will be on probably 40+ servers as a method of config management, and I don't want to set up all the SSH keys especially since it will often be used from a user on the host that is not myself.
Does anyone know how to take context of the shell from the python script to programmatically enter my username and password (they are already in my code as variables from the command line) or a way to pass my username and password to GitPython so that the shell prompt never even happens?
git_repo = Repo.init(repo_dir)
origin = git_repo.remote('origin')
origin.fetch() # Shell prompted here for username and password
git_repo.heads.dev.checkout()
origin.pull() # Shell prompted here for username and password
git_repo.git.add([added_filename])
git_repo.git.commit(commit_message)
origin.push() # Shell prompted here for username and password
i created Line-bot app using heroku as host, which can create, read, and append into a txt_files on heroku by sending a command from Line account,
so i tried to sent message to my Line-bot with command like this:
username = "user_name"
password = "pass_word"
i sent that text to my Line-bot and it saves my username and password into a txt_file(of course it check if there was no txt_file for save those data it will create txt_file automatically) on heroku, and by another command which can read the text which my Line-bot saved last time, my Line-bot sent me message and it shows:
username is user_name
password is pass_word
however after a few hours when i need my username and password/read back my data, by sending the same command, the data is gone and becomes like this
username is //empty
password is //empty
what should i do for this problem?
thank you...
Are you using a free-level heroku account? If so, heroku does not allow permanent (long-term) file storage. As long as the dyno is shut down, any changes will be reverted.
An alternative is to use an external server as a database, but those may suffer from slower connection.
This article tells you more about heroku.
The app configuration used in a Flask Mail application (following Miguel Grinberg Flask developlemt book) :
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
The Mail Username and Password variables have been set correctly and rechecked. While trying to send a message using the following code,
from flask.ext.mail import Message
from hello import mail
msg = Message('test subject', sender='same as MAIL_USERNAME', recipients=['check#mail.com'])
msg.body = 'text body'
msg.html = '<b>HTML</b> body'
with app.app_context():
mail.send(msg)
While sending, the application is again and again resulting in the following error:
SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 qb10sm6828974pbb.9 - gsmtp', u'configured MAIL_USERNAME')
Any workaround for the error?
While digging into the issues faced, I rechecked the SMTP settings for Google,
Changing the
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
to
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
did the trick.
Also make sure that the full username is used as Gmail SMTP username, i.e., example#gmail.com as shown in the image above.
Hope this helps!!!
I also followed this book and get the same problem, after some digging here and there, I found out the root cause of the problem. However, I am not sure whether it will be the same case for you or not.
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
As you can see your flask app gets the your email credentials through os.environ.get(), and if you set this environment variables temporarily in your system, in my case Mac OSX, after your terminal session they will be gone, so you need to set them again for the next time you enter the terminal, like below:
export MAIL_USERNAME=**YOUR EMAIL**
export PASSWORD=**YOUR PASSWORD**
I got this error because of this scenario, in order to set them permanently you need to include these variables into .bash_profile file in your home directory.
You need to change your Google account settings. On this page, turn on the option to "Allow less secure apps".
As that page says:
Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks. Learn more
Do these 2 things to resolve:
Use this link and turn on 'Allow less secure apps'- https://myaccount.google.com/lesssecureapps
Use hard-coded value for email and password and it worked fine.
Simply in the file 'init.py', edit the following section:
Don't use os.environ.get
app.config['MAIL_USERNAME'] = 'youremail#gmail.com'
app.config['MAIL_PASSWORD'] = 'yourpassword'