|
| 1 | +#database.py |
| 2 | + |
| 3 | +import firebase_admin |
| 4 | +from firebase_admin import credentials, db, auth |
| 5 | +import pyrebase |
| 6 | + |
| 7 | +class Firebase: |
| 8 | + def __init__(self): |
| 9 | + # Initialize Firebase Admin SDK with credentials and database URL |
| 10 | + CREDENTIALS_FILE = "cred.json" |
| 11 | + DATABASE_URL = "https://sftproject-a6eeb-default-rtdb.europe-west1.firebasedatabase.app/" |
| 12 | + API_KEY = "AIzaSyBgENniVkNeOgctnOFAl7GZm68J0wkAJHI" |
| 13 | + PROJECT_ID = "SFTProject" |
| 14 | + self.cred = credentials.Certificate(CREDENTIALS_FILE) |
| 15 | + firebase_admin.initialize_app(self.cred, {"databaseURL": DATABASE_URL}) |
| 16 | + |
| 17 | + # Reference to the root of the Firebase Realtime Database |
| 18 | + self.ref = db.reference("/") |
| 19 | + self.config = { |
| 20 | + "apiKey": API_KEY, |
| 21 | + "authDomain": f"{PROJECT_ID}.firebaseapp.com", |
| 22 | + "databaseURL": DATABASE_URL, |
| 23 | + "storageBucket": f"{PROJECT_ID}.appspot.com", |
| 24 | + } |
| 25 | + self.firebase = pyrebase.initialize_app(self.config) |
| 26 | + self.auth = self.firebase.auth() |
| 27 | + |
| 28 | + def login(self, email, password): |
| 29 | + user = self.auth.sign_in_with_email_and_password(email, password) |
| 30 | + return user |
| 31 | + |
| 32 | + def register(self, email, password): |
| 33 | + user = self.auth.create_user_with_email_and_password(email, password) |
| 34 | + return user |
| 35 | + |
| 36 | + def get_current_user(self): |
| 37 | + return self.auth.current_user |
| 38 | + |
| 39 | + def get_user_id(self): |
| 40 | + return self.auth.current_user["localId"] |
| 41 | + |
| 42 | + def get_user_email(self): |
| 43 | + return self.auth.current_user["email"] |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | + def logout(self): |
| 48 | + self.auth.current_user = None |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + # Instantiate Firebase object |
| 52 | + f = Firebase() |
| 53 | + |
| 54 | + # Access and modify data in Realtime Database |
| 55 | + print(f.ref.get()) |
| 56 | + f.ref.set({"name": "Enis Bulut"}) |
| 57 | + print(f.ref.get()) |
| 58 | + |
| 59 | + try: |
| 60 | + # Try logging in with existing user credentials |
| 61 | + f.login("example@gmail.com", "password") |
| 62 | + except Exception as e: |
| 63 | + # If login fails, register a new user |
| 64 | + f.register("example@gmail.com", "password") |
| 65 | + |
| 66 | + # Get details of current authenticated user |
| 67 | + print(f.get_current_user()) |
0 commit comments