shaheerawan3 commited on
Commit
0437283
·
verified ·
1 Parent(s): 66c1f04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -265
app.py CHANGED
@@ -1,288 +1,191 @@
1
  import streamlit as st
2
  from cryptography.fernet import Fernet
3
- from datetime import datetime
4
- import uuid
5
- import bcrypt
6
  import sqlite3
7
- import os
 
 
 
 
 
8
  import json
9
-
10
- class DigitalHeir:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def __init__(self):
12
- self.key = Fernet.generate_key()
13
- self.cipher_suite = Fernet(self.key)
 
 
 
 
 
14
 
15
- def encrypt_data(self, data):
16
- return self.cipher_suite.encrypt(str(data).encode())
 
 
 
17
 
18
- def decrypt_data(self, encrypted_data):
19
- return self.cipher_suite.decrypt(encrypted_data).decode()
20
-
21
- def create_connection():
22
- conn = sqlite3.connect("digital_heir.db")
23
- return conn
24
-
25
- def initialize_db():
26
- conn = create_connection()
27
- cursor = conn.cursor()
28
-
29
- # Create tables if they don't exist
30
- cursor.execute('''CREATE TABLE IF NOT EXISTS users (
31
- id TEXT PRIMARY KEY,
32
- username TEXT UNIQUE NOT NULL,
33
- password TEXT NOT NULL,
34
- role TEXT NOT NULL,
35
- created_at TEXT NOT NULL)''')
 
 
 
 
 
 
36
 
37
- cursor.execute('''CREATE TABLE IF NOT EXISTS accounts (
38
- id TEXT PRIMARY KEY,
39
- user_id TEXT NOT NULL,
40
- platform TEXT NOT NULL,
41
- username TEXT NOT NULL,
42
- password TEXT NOT NULL,
43
- created_at TEXT NOT NULL,
44
- FOREIGN KEY (user_id) REFERENCES users(id))''')
 
 
45
 
46
- cursor.execute('''CREATE TABLE IF NOT EXISTS heirs (
47
- id TEXT PRIMARY KEY,
48
- user_id TEXT NOT NULL,
49
- name TEXT NOT NULL,
50
- email TEXT NOT NULL,
51
- relationship TEXT NOT NULL,
52
- created_at TEXT NOT NULL,
53
- FOREIGN KEY (user_id) REFERENCES users(id))''')
54
-
55
- conn.commit()
56
- conn.close()
57
-
58
- def get_user_by_username(username):
59
- conn = create_connection()
60
- cursor = conn.cursor()
61
- cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
62
- user = cursor.fetchone()
63
- conn.close()
64
- return user
65
-
66
- def get_user_by_id(user_id):
67
- conn = create_connection()
68
- cursor = conn.cursor()
69
- cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
70
- user = cursor.fetchone()
71
- conn.close()
72
- return user
73
-
74
- def get_accounts_by_user_id(user_id):
75
- conn = create_connection()
76
- cursor = conn.cursor()
77
- cursor.execute("SELECT * FROM accounts WHERE user_id = ?", (user_id,))
78
- accounts = cursor.fetchall()
79
- conn.close()
80
- return accounts
81
-
82
- def get_heirs_by_user_id(user_id):
83
- conn = create_connection()
84
- cursor = conn.cursor()
85
- cursor.execute("SELECT * FROM heirs WHERE user_id = ?", (user_id,))
86
- heirs = cursor.fetchall()
87
- conn.close()
88
- return heirs
89
-
90
- def insert_user(username, password, role):
91
- conn = create_connection()
92
- cursor = conn.cursor()
93
- user_id = str(uuid.uuid4())
94
- cursor.execute("INSERT INTO users (id, username, password, role, created_at) VALUES (?, ?, ?, ?, ?)",
95
- (user_id, username, password, role, datetime.now().isoformat()))
96
- conn.commit()
97
- conn.close()
98
- return user_id
99
-
100
- def insert_account(user_id, platform, username, password):
101
- conn = create_connection()
102
- cursor = conn.cursor()
103
- account_id = str(uuid.uuid4())
104
- cursor.execute("INSERT INTO accounts (id, user_id, platform, username, password, created_at) VALUES (?, ?, ?, ?, ?, ?)",
105
- (account_id, user_id, platform, username, password, datetime.now().isoformat()))
106
- conn.commit()
107
- conn.close()
108
-
109
- def insert_heir(user_id, name, email, relationship):
110
- conn = create_connection()
111
- cursor = conn.cursor()
112
- heir_id = str(uuid.uuid4())
113
- cursor.execute("INSERT INTO heirs (id, user_id, name, email, relationship, created_at) VALUES (?, ?, ?, ?, ?, ?)",
114
- (heir_id, user_id, name, email, relationship, datetime.now().isoformat()))
115
- conn.commit()
116
- conn.close()
117
-
118
- def delete_account(account_id):
119
- conn = create_connection()
120
- cursor = conn.cursor()
121
- cursor.execute("DELETE FROM accounts WHERE id = ?", (account_id,))
122
- conn.commit()
123
- conn.close()
124
-
125
- def delete_heir(heir_id):
126
- conn = create_connection()
127
- cursor = conn.cursor()
128
- cursor.execute("DELETE FROM heirs WHERE id = ?", (heir_id,))
129
- conn.commit()
130
- conn.close()
131
-
132
- def delete_user(user_id):
133
- conn = create_connection()
134
- cursor = conn.cursor()
135
- cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))
136
- cursor.execute("DELETE FROM accounts WHERE user_id = ?", (user_id,))
137
- cursor.execute("DELETE FROM heirs WHERE user_id = ?", (user_id,))
138
- conn.commit()
139
- conn.close()
140
-
141
- def initialize_state():
142
- if 'current_user' not in st.session_state:
143
- st.session_state.current_user = None
144
-
145
- def show_auth():
146
- tab1, tab2 = st.tabs(["Login", "Register"])
147
 
148
- with tab1:
149
- with st.form("login_form"):
150
- username = st.text_input("Username")
151
- password = st.text_input("Password", type="password")
 
 
 
152
 
153
- if st.form_submit_button("Login"):
154
- login_user(username, password)
 
 
155
 
156
- with tab2:
157
- with st.form("register_form"):
158
- new_username = st.text_input("Username")
159
- new_password = st.text_input("Password", type="password")
160
- confirm_password = st.text_input("Confirm Password", type="password")
 
161
 
162
- if st.form_submit_button("Register"):
163
- register_user(new_username, new_password, confirm_password)
164
-
165
- def login_user(username, password):
166
- user = get_user_by_username(username)
167
- if user and bcrypt.checkpw(password.encode(), user[2].encode()):
168
- st.session_state.current_user = {'id': user[0], 'username': user[1], 'role': user[3]}
169
- st.success("Login successful!")
170
- st.rerun()
171
- else:
172
- st.error("Invalid username or password")
173
-
174
- def register_user(username, password, confirm_password):
175
- if password != confirm_password:
176
- st.error("Passwords do not match")
177
- return
178
-
179
- if get_user_by_username(username):
180
- st.error("Username already exists")
181
- return
182
-
183
- password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
184
- user_id = insert_user(username, password_hash, 'user')
185
- st.session_state.current_user = {'id': user_id, 'username': username, 'role': 'user'}
186
- st.success("Registration successful! Please login.")
187
-
188
- def show_user_accounts():
189
- st.title("My Accounts")
190
- user_id = st.session_state.current_user['id']
 
 
 
191
 
192
- with st.form("add_account"):
193
- st.subheader("Add New Account")
194
- platform = st.text_input("Platform Name")
195
- username = st.text_input("Username/Email")
 
 
196
  password = st.text_input("Password", type="password")
 
 
 
 
 
 
 
 
 
 
 
197
 
198
- if st.form_submit_button("Add Account"):
199
- insert_account(user_id, platform, username, app.encrypt_data(password))
200
- st.success("Account added successfully!")
201
- st.rerun()
202
-
203
- st.subheader("My Accounts")
204
- accounts = get_accounts_by_user_id(user_id)
205
- for account in accounts:
206
- with st.expander(f"{account[2]} - {account[3]}"):
207
- st.write(f"Created: {account[5]}")
208
- if st.button("Delete Account", key=f"del_acc_{account[0]}"):
209
- delete_account(account[0])
210
- st.success("Account deleted successfully!")
211
- st.rerun()
212
 
213
- def show_user_heirs():
214
- st.title("My Heirs")
215
- user_id = st.session_state.current_user['id']
 
 
 
216
 
217
- with st.form("add_heir"):
218
- st.subheader("Add New Heir")
219
- name = st.text_input("Full Name")
220
- email = st.text_input("Email Address")
221
- relationship = st.text_input("Relationship")
222
-
223
- if st.form_submit_button("Add Heir"):
224
- insert_heir(user_id, name, email, relationship)
225
- st.success("Heir added successfully!")
226
- st.rerun()
227
 
228
- st.subheader("My Heirs")
229
- heirs = get_heirs_by_user_id(user_id)
230
- for heir in heirs:
231
- with st.expander(f"{heir[2]} - {heir[3]}"):
232
- st.write(f"Email: {heir[4]}")
233
- st.write(f"Added: {heir[5]}")
234
- if st.button("Delete Heir", key=f"del_heir_{heir[0]}"):
235
- delete_heir(heir[0])
236
- st.success("Heir deleted successfully!")
237
- st.rerun()
238
-
239
- def main():
240
- st.set_page_config(page_title="Digital Heir", layout="wide")
241
- initialize_db()
242
- initialize_state()
243
 
244
- if not st.session_state.current_user:
245
- show_auth()
246
  else:
247
- if st.session_state.current_user['role'] == 'admin':
248
- show_admin_panel()
249
- else:
250
- show_user_panel()
251
-
252
- def show_admin_panel():
253
- st.sidebar.title("Admin Panel")
254
- menu = ["Users", "Settings"]
255
- choice = st.sidebar.selectbox("Menu", menu)
256
-
257
- if choice == "Users":
258
- show_user_management()
259
- elif choice == "Settings":
260
- show_admin_settings()
261
-
262
- def show_user_management():
263
- st.title("User Management")
264
- # User list (admin can see all users)
265
- users = get_all_users()
266
- for user in users:
267
- if user[3] != 'admin': # Skip the admin user
268
- with st.expander(f"User: {user[1]}"):
269
- st.write(f"Created: {user[4]}")
270
- if st.button("Delete User", key=f"del_user_{user[0]}"):
271
- delete_user(user[0])
272
- st.success("User deleted successfully!")
273
- st.rerun()
274
-
275
- def get_all_users():
276
- conn = create_connection()
277
- cursor = conn.cursor()
278
- cursor.execute("SELECT * FROM users")
279
- users = cursor.fetchall()
280
- conn.close()
281
- return users
282
-
283
- def show_admin_settings():
284
- st.title("Admin Settings")
285
- st.write("Admin settings and controls.")
286
 
287
  if __name__ == "__main__":
288
- main()
 
1
  import streamlit as st
2
  from cryptography.fernet import Fernet
3
+ from datetime import datetime, timedelta
 
 
4
  import sqlite3
5
+ import bcrypt
6
+ import uuid
7
+ import smtplib
8
+ import schedule
9
+ import threading
10
+ import time
11
  import json
12
+ import logging
13
+ from email.mime.text import MIMEText
14
+ from typing import Optional, Dict
15
+ from dataclasses import dataclass
16
+ import requests
17
+ from selenium import webdriver
18
+ from selenium.webdriver.common.by import By
19
+ from selenium.webdriver.support.ui import WebDriverWait
20
+ from selenium.webdriver.support import expected_conditions as EC
21
+
22
+ @dataclass
23
+ class AccountStatus:
24
+ last_active: datetime
25
+ is_active: bool
26
+ platform: str
27
+ username: str
28
+
29
+ class ActivityMonitor:
30
  def __init__(self):
31
+ self.driver = webdriver.Chrome(headless=True)
32
+ self.platform_checkers = {
33
+ 'facebook': self._check_facebook,
34
+ 'twitter': self._check_twitter,
35
+ 'instagram': self._check_instagram,
36
+ 'linkedin': self._check_linkedin
37
+ }
38
 
39
+ def check_account_activity(self, platform: str, username: str) -> AccountStatus:
40
+ checker = self.platform_checkers.get(platform.lower())
41
+ if not checker:
42
+ raise ValueError(f"Unsupported platform: {platform}")
43
+ return checker(username)
44
 
45
+ def _check_facebook(self, username: str) -> AccountStatus:
46
+ try:
47
+ url = f"https://www.facebook.com/{username}"
48
+ self.driver.get(url)
49
+ last_post = WebDriverWait(self.driver, 10).until(
50
+ EC.presence_of_element_located((By.CSS_SELECTOR, "[data-testid='post_timestamp']"))
51
+ )
52
+ last_active = datetime.fromisoformat(last_post.get_attribute('datetime'))
53
+ return AccountStatus(last_active, True, 'facebook', username)
54
+ except Exception as e:
55
+ logging.error(f"Error checking Facebook activity: {e}")
56
+ return AccountStatus(datetime.min, False, 'facebook', username)
57
+
58
+ # Similar implementations for other platforms...
59
+
60
+ class DigitalInheritance:
61
+ def __init__(self, email_config: Dict):
62
+ self.key = self._load_or_create_key()
63
+ self.cipher_suite = Fernet(self.key)
64
+ self.db = Database()
65
+ self.activity_monitor = ActivityMonitor()
66
+ self.email_config = email_config
67
+ self._setup_scheduler()
68
+ self._setup_logging()
69
 
70
+ def _load_or_create_key(self) -> bytes:
71
+ key_file = "encryption.key"
72
+ try:
73
+ with open(key_file, "rb") as f:
74
+ return f.read()
75
+ except FileNotFoundError:
76
+ key = Fernet.generate_key()
77
+ with open(key_file, "wb") as f:
78
+ f.write(key)
79
+ return key
80
 
81
+ def _setup_scheduler(self):
82
+ schedule.every(12).hours.do(self.check_inactive_accounts)
83
+ thread = threading.Thread(target=self._run_scheduler, daemon=True)
84
+ thread.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ def check_inactive_accounts(self):
87
+ accounts = self.db.get_pending_accounts()
88
+ for account in accounts:
89
+ status = self.activity_monitor.check_account_activity(
90
+ account['platform'],
91
+ account['username']
92
+ )
93
 
94
+ if not status.is_active:
95
+ days_inactive = (datetime.now() - status.last_active).days
96
+ if days_inactive >= account['inactivity_threshold']:
97
+ self._trigger_inheritance(account)
98
 
99
+ def _trigger_inheritance(self, account: Dict):
100
+ try:
101
+ heir = self.db.get_heir(account['heir_id'])
102
+ decrypted_password = self.cipher_suite.decrypt(
103
+ account['password'].encode()
104
+ ).decode()
105
 
106
+ self._send_credentials_email(
107
+ heir['email'],
108
+ account['platform'],
109
+ account['username'],
110
+ decrypted_password
111
+ )
112
+
113
+ self.db.update_account_status(
114
+ account['id'],
115
+ 'inherited',
116
+ datetime.now().isoformat()
117
+ )
118
+
119
+ logging.info(f"Inheritance triggered for account {account['id']}")
120
+ except Exception as e:
121
+ logging.error(f"Error in inheritance process: {e}")
122
+
123
+ def _send_credentials_email(self, email: str, platform: str,
124
+ username: str, password: str):
125
+ msg = MIMEText(self._generate_email_content(platform, username, password))
126
+ msg['Subject'] = 'Digital Account Access Information'
127
+ msg['From'] = self.email_config['sender']
128
+ msg['To'] = email
129
+
130
+ with smtplib.SMTP_SSL(self.email_config['smtp_server'],
131
+ self.email_config['port']) as server:
132
+ server.login(self.email_config['username'],
133
+ self.email_config['password'])
134
+ server.send_message(msg)
135
+
136
+ def create_account_ui():
137
+ st.title("Digital Account Setup")
138
 
139
+ with st.form("account_setup"):
140
+ platform = st.selectbox(
141
+ "Platform",
142
+ ["Facebook", "Twitter", "Instagram", "LinkedIn"]
143
+ )
144
+ username = st.text_input("Username")
145
  password = st.text_input("Password", type="password")
146
+ heir = st.selectbox(
147
+ "Select Heir",
148
+ options=get_user_heirs(),
149
+ format_func=lambda x: x['name']
150
+ )
151
+ inactive_days = st.slider(
152
+ "Days of Inactivity Before Transfer",
153
+ min_value=30,
154
+ max_value=365,
155
+ value=90
156
+ )
157
 
158
+ if st.form_submit_button("Save Account"):
159
+ save_social_account(
160
+ platform=platform,
161
+ username=username,
162
+ password=password,
163
+ heir_id=heir['id'],
164
+ inactive_days=inactive_days
165
+ )
166
+ st.success("Account saved successfully!")
 
 
 
 
 
167
 
168
+ def main():
169
+ st.set_page_config(
170
+ page_title="Digital Inheritance System",
171
+ layout="wide",
172
+ initial_sidebar_state="expanded"
173
+ )
174
 
175
+ email_config = {
176
+ 'smtp_server': st.secrets["SMTP_SERVER"],
177
+ 'port': st.secrets["SMTP_PORT"],
178
+ 'username': st.secrets["SMTP_USERNAME"],
179
+ 'password': st.secrets["SMTP_PASSWORD"],
180
+ 'sender': st.secrets["SENDER_EMAIL"]
181
+ }
 
 
 
182
 
183
+ app = DigitalInheritance(email_config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
+ if 'current_user' not in st.session_state:
186
+ show_login()
187
  else:
188
+ show_dashboard(app)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  if __name__ == "__main__":
191
+ main()