I am farely new to Pyrebase and Firebase and I was wondering why this code isn't working.
I want to write to the realtime database, for that the rules are
{
"rules": {
"userdata": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
And the python code is:
def login():
email = input("Enter email: ")
password = input("Enter password: ")
user = auth.sign_in_with_email_and_password(email, password)
user = auth.refresh(user['refreshToken'])
uid_variable = user['userId']
print(uid_variable)
print("Successfully logged in!")
data = {"test": "test"}
db.child("userdata").child(uid_variable).set(data)
But when it tries to write to the database it shows:
[Errno 401 Client Error: Unauthorized for url: https://xxxxxxxxxx-default-rtdb.europe-west1.firebasedatabase.app/userdata/xxxxxxxxxxxxxxxxxxxxxxxx.json] {
"error" : "Permission denied"
}
I don't seem to find any help anywhere so anything would be appreciated!
Depending on what you're using with your backend, this post on how to integrate Firebase Auth with a FastAPI backend using Pyrebase and Firebase Admin shows how you can create a login with Pyrebase using username and password
Based on the code here:
#app.post("/login", include_in_schema=False)
async def login(request: Request):
req_json = await request.json()
email = req_json['email']
password = req_json['password']
try:
user = pb.auth().sign_in_with_email_and_password(email, password)
jwt = user['idToken']
return JSONResponse(content={'token': jwt}, status_code=200)
except:
return HTTPException(detail={'message': 'There was an error logging in'}, status_code=400)
I believe you need to call the auth() function with the pyrebase object you created.
Related
working on a project in socket io python and JWT for tokens. Can enyone please help on how to authenticate user using JWT in socketio python. And I am also getting error while generating JWT token. The error is on line
response_data['data']['token'] = token //response data is refered before assignment
How to solve this error and below is my code:
encrypted_password, col_name = DBHandler.SignIn(email)
if encrypted_password:
encrypted_password = encrypted_password[0][0].encode()
f = Fernet(key)
encrypted_password = f.decrypt(encrypted_password).decode()
if password == encrypted_password:
token = jwt.encode({'user': email, 'exp': datetime.utcnow() + timedelta(minutes=600)}, private_key,
algorithm='HS256')
print(token)
response_data['data']['token'] = token
return jsonify(response_data)
else:
print('Incorrect Password')
response_data = {
"status": "Error",
"message": "Error in Getting User from DB",
"data": {}
}
return make_response(jsonify(response_data), 400)
I'm working on an app with flask backend and react front,
I want to save the username in a session and display it in the front post-login.
here is the current process:
configurations at the head of app.py (flask-server main file)
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "key"
app.config["SECRET_KEY"] = "pass"
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)
app.config["SESSION_TYPE"] = 'filesystem'
app.config["SESSION_PERMANENT"] = False
# app.config.from_object(__name__)
CORS(app)
Session(app)
jwt = JWTManager(app)
Login button with handler:
const data = {
username: loginForm.username,
password: loginForm.password
}
fetch("http://localhost:5000/token", {
method: "POST",
body: JSON.stringify(data)
})
.then((response) => {...
the route for "/token" - if the credentials are ok it renders my user homepage, and it works fine.
#app.route('/token', methods=["POST"])
def create_token():
username = json.loads(request.data)["username"]
password = json.loads(request.data)["password"]
sql_string = f"""select username, password from admins where username='{username}'"""
result = sql_call(sql_string) //this is a helper functino in db_connector file
if(result):
session["username"] = username
access_token = create_access_token(identity=username) //another helper function
response = app.response_class(response=json.dumps({"access_token": access_token}),
status=200,
mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
return response
on the app main page i have a span of "Hello " that tries to fetch the username from the session, sending request to route "/username":
#app.route("/username")
def getUsername():
username = session["username"]
response = jsonify({"username": "admin"})
return response
But it finds no key "username" in the session, and also the SID in 4 and SID in 3 are different.
how can I retrieve this data back?
my flask runs on port 5000 and react on port 3000,
thanks
In step 4 use this to get username
session.get("username")
Ok, I didn't manage to fix it,
session.get("username" also didn't work)
I noticed that the server is working fine when sending requests from postman, so the problem might be in React.
I used the get_jtw()
over the session and it works well :)
I am trying to login from my website developed in Angular to the back end flask API, The backend uses bcrypt for encoding and pymongo for interacting with a MongoDB. In postman, the login endpoint works fine but when an attempt to log in on the client side is made I receive a 401: UNAUTHORIZED ERROR. Can someone advise what the issue is/where I am going wrong?
The login function on the client side:
onLogin() {
let postData = new FormData();
postData.append('username', this.loginForm.get('username').value);
postData.append('password', this.loginForm.get('password').value);
this.http.post('http://localhost:5000/api/v1.0/login', postData)
.subscribe((_response: any) => {
console.log(this.loginForm.value);
this.loginForm.reset();
})
}
The login endpoint in backend:
app = Flask(__name__)
CORS(app)
#app.route('/api/v1.0/login', methods=['POST'])
def login():
auth = request.authorization
if auth:
user = users.find_one({'username': auth.username})
if user is not None:
if bcrypt.checkpw(bytes(auth.password, 'utf-8'),
user["password"]):
token = jwt.encode( \
{'user' : auth.username,
'admin': user["admin"],
'exp' : datetime.datetime.utcnow() + \
datetime.timedelta(minutes=30)
}, app.config['SECRET_KEY'])
return make_response(jsonify( \
{'token':token.decode('UTF-8')}), 200)
else:
return make_response(jsonify( \
{'message':'Bad password'}), 401)
else:
return make_response(jsonify( \
{'message':'Bad username'}), 401)
In order to use request.authorization you need to send the credentials in the Authorization-header. Try this on the client:
onLogin() {
const usn = this.loginForm.get('username').value;
const pwd = this.loginForm.get('password').value;
this.http.post('http://localhost:5000/api/v1.0/login', null, {
headers: new HttpHeaders({
Authorization: `Basic ${btoa(`${usn}:${pwd}`)}`
})
}).subscribe((_response: any) => {
console.log(_response);
});
}
As a sidenote; the credentials can be easily decoded by using atob(), so make sure you are using a secure connection (HTTPS) when not on localhost.
I'm creating an IAM user programmatically using boto3.
I also want to invite the user that I've just created using email.
Here's what I've tried so far for creating and updating the password.
iam.create_user(UserName='username')
iam.create_login_profile(
UserName='username',
Password='password',
PasswordResetRequired=False
)
But I haven't found an option to automatically send an invite email to the user after it's been created.
Is there any way to automatically send an invite mail with the password and so that user can login?
Something like
invite_mail='somemail'
There is no in-built AWS capability to send users their login information.
In fact, there is not even a standard field for storing email addresses for IAM Users.
You would need to code such functionality yourself.
1
You can use a cloud trail to trigger Lambda upon the IAM-user creation event and send email to newly created users using AWS SES client. You can validate the format of the email with a regex like abc.xyx#company.com. This you can only do if the user name is in email format.
2
import boto3
import logging
ses_client = boto3.client('ses', region_name='us-east-1')
iam_client = boto3.client('iam')
response = iam_client.create_user(
Path='string',
UserName='string',
PermissionsBoundary='string',
Tags=[
{
'Key': 'string',
'Value': 'string'
},
]
)
#if username as email id
user_email = response['User']['UserName']
#if user has tagged with email
#user_email = response['User']['Tags']['KeyName']
SMTP_FROM = 'EMAIL_ADDRESS'
html = "html_email_template"
SMTP_TO = user_email
try:
response = ses_client.send_email(
Source=SMTP_FROM,
Destination={
'ToAddresses': SMTP_TO
},
Message={
'Body': {
'Html': {
'Charset': "UTF-8",
'Data': html,
}
},
'Subject': {
'Data': 'New User Created '
}
}
)
logger.info(response)
except ClientError as e:
logger.error(e.response['Error']['Message'])
else:
logger.info("Email sent! Message ID: " + response['MessageId'])
im trying to build a simple api+lambda with chalice which can receive a POST request and then forward it to another API while adding some authentication. when i run my chalice code locally i can send a request and print the payload which i sent inside chalice console yet i cannot forward my request. i don't get back any errors or other print statements which i have in my code. i don't know where else to look for more answers so im asking here.
from chalice import Chalice
import requests
app = Chalice(app_name='redirect_url')
app.debug = True
TOKEN_URL = "https://redirect.com/v0/token"
USERNAME = 'email#email.com'
PASSWORD = 'Password01021'
#app.route('/redirect_url', methods=['POST'])
def get_payload():
update_payload = app.current_request.json_body
print(update_payload)
def fetch_auth_token():
username = USERNAME
password = PASSWORD
data = {
"grant_type": "password",
"username": username,
"password": password
}
response = requests.post(TOKEN_URL, data=data)
token = response.json()
print(token)
IF I send a request to the endpoint (http://127.0.0.1:8000/redirect_url) I see my request printed inside chalice logs, but i don't see the token request.
I would appreciate any help
This is a bit old, but I thought I would answer it for the community for those new to Chalice.
You are expecting to fire the function without calling it. It should be:
from chalice import Chalice
import requests
app = Chalice(app_name='redirect_url')
app.debug = True
TOKEN_URL = "https://redirect.com/v0/token"
USERNAME = 'email#email.com'
PASSWORD = 'Password01021'
#app.route('/redirect_url', methods=['POST'])
def get_payload():
update_payload = app.current_request.json_body
APIresponse = fetch_auth_token()
print(APIresponse) ## If you want to show it right before the update_payload
print(update_payload)
def fetch_auth_token():
username = USERNAME
password = PASSWORD
data = {
"grant_type": "password",
"username": username,
"password": password
}
response = requests.post(TOKEN_URL, data=data)
return response.json()