Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions mental_health_hub (GARGI SARMA)/auth_module 1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import streamlit as st
import bcrypt # Import bcrypt and jwt functionality
import jwt
import datetime
from logging_module import log_event # Import log_event function

# Secret key for signing JWTs
SECRET_KEY = "super-secret-key"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just needing to check regarding this secret key here, this is simply just a placeholder and the actual key is stored elsewhere right? If that's the case this is fine :)


# In-memory "database" for demo
if "users_db" not in st.session_state:
st.session_state.users_db = {}

# Session state for authentication
if "token" not in st.session_state:
st.session_state.token = None
if "user" not in st.session_state:
st.session_state.user = None


# Hash password, bcrypt, token generation, verification functionality
def hash_password(password: str) -> bytes:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())

def verify_password(password: str, hashed: bytes) -> bool:
return bcrypt.checkpw(password.encode("utf-8"), hashed)

def generate_token(username: str) -> str:
payload = {
"user": username,
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}
token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
return token

def verify_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return payload
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None


# Streamlit User-Interface
def run_auth():
st.title("🔑 User Authentication (JWT)")

choice = st.radio("Choose Action:", ["Login", "Register", "Logout"])

# Register functionality
if choice == "Register":
st.subheader("Create a new account")
username = st.text_input("Username (register)")
password = st.text_input("Password (register)", type="password")

if st.button("Register"):
if username in st.session_state.users_db:
st.error("User already exists.")
log_event(f"Failed registration attempt (user exists): {username}", 'ERROR') # Log failed registration
else:
st.session_state.users_db[username] = hash_password(password)
st.success(f"User {username} registered successfully!")
log_event(f"User successfully registered: {username}", 'INFO') # Log the successful registration event

# Login Functionality
elif choice == "Login":
st.subheader("Login")
username = st.text_input("Username (login)")
password = st.text_input("Password (login)", type="password")

if st.button("Login"):
if username not in st.session_state.users_db:
st.error("Invalid credentials.")
log_event(f"Failed login attempt (user does not exist): {username}", 'ERROR') # Log failed login
else:
stored_pw = st.session_state.users_db[username]
if verify_password(password, stored_pw):
token = generate_token(username)
st.session_state.token = token
st.session_state.user = username
st.success(f"Welcome, {username}!")
log_event(f"User successfuly logged in: {username}", 'INFO') # Log successful login
else:
st.error("Invalid credentials.")
log_event(f"Failed login attempt (incorrect password): {username}", 'ERROR') # Log failed login

# Logout functionality
elif choice == "Logout":
if st.session_state.token:
log_event(f"User logged out: {st.session_state.user}", 'INFO') # Log the logout event
st.session_state.token = None
st.session_state.user = None
st.success("You have successfully been logged out.")
else:
st.info("You are not logged in.")

# Protected Area
if st.session_state.token:
payload = verify_token(st.session_state.token)
if payload:
st.info(f"🔒 Protected: Hello {payload['user']}!")
else:
st.error("Your session expired. Please login again.")
log_event(f"Session expired for: {st.session_state.user}", 'ERROR') # Log session expiry event
st.session_state.token = None
st.session_state.user = None
31 changes: 31 additions & 0 deletions mental_health_hub (GARGI SARMA)/chat_gg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import streamlit as st
import time

# Initialize chat history in session state
if "chat_messages" not in st.session_state:
st.session_state.chat_messages = []

def run_chat():
st.title("Streamlit Group Chat (No Server)")

nickname = st.text_input("Choose a nickname", key="nickname")
if not nickname:
st.info("Enter a nickname to join the chat.")
st.stop()

# Display chat history
st.subheader("Chat Room")
chat_box = st.empty()
for msg in st.session_state.chat_messages:
chat_box.write(msg)

# Message input
msg = st.text_input("Type your message", key="msg")
if st.button("Send"):
if msg:
message = f"{nickname}: {msg}"
st.session_state.chat_messages.append(message)
st.experimental_rerun()

# Optionally, auto-refresh every few seconds for a "live" feel
st.button("Refresh Chat")
34 changes: 34 additions & 0 deletions mental_health_hub (GARGI SARMA)/ggclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import socket
import threading

HOST = '127.0.0.1'
PORT = 5000

nickname = input("Choose a nickname: ")

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

# Receive messages
def receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
if message == "GARGI":
client.send(nickname.encode('utf-8'))
else:
print(message)
except:
print("An error occurred. Connection closed.")
client.close()
break

# Send messages
def write():
while True:
message = f"{nickname}: {input('')}"
client.send(message.encode('utf-8'))

# Run both in parallel
threading.Thread(target=receive).start()
threading.Thread(target=write).start()
50 changes: 50 additions & 0 deletions mental_health_hub (GARGI SARMA)/ggserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import socket
import threading

HOST = '127.0.0.1'
PORT = 5000

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()

clients = []
nicknames = []

def broadcast(message):
for client in clients:
client.send(message)

def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f'{nickname} left the chat!'.encode('utf-8'))
nicknames.remove(nickname)
break

def receive():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")

client.send("GARGI".encode('utf-8'))
nickname = client.recv(1024).decode('utf-8')
nicknames.append(nickname)
clients.append(client)

print(f"Nickname of the client is {nickname}")
broadcast(f"{nickname} joined the chat!".encode('utf-8'))
client.send("Connected to the server!".encode('utf-8'))

thread = threading.Thread(target=handle, args=(client,))
thread.start()

print("Server is listening...")
receive()
30 changes: 30 additions & 0 deletions mental_health_hub (GARGI SARMA)/streamlit_hub_app 1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Import all necessary libraries and functions here
import streamlit as st
from auth_module import run_auth
from dashboard_module import run_dashboard
from mood_module import run_mood
from logging_module import run_logging, init_logging
from storytelling_module import run_storytelling # ⬅️ NEW
from chat_module import run_chat

# Page Directory for Streamlit
PAGES = {
"Authentication": run_auth, # Add Authentication Page
"Dashboard": run_dashboard, # Add Dashboard page
"Mood Predictor": run_mood, # Add Mood Predictor Page
"Activity Logging": run_logging, # Add Logging page
"Storytelling": run_storytelling, # Add Storytelling Page
"Group Chat": run_chat, # Add Group Chat Page
}

# Initialises logging session when the app starts
init_logging()

# Main Functionality
def main():
st.sidebar.title("Mental Health Hub")
choice = st.sidebar.radio("Go to:", list(PAGES.keys()))
PAGES[choice]() # run the selected page

if __name__ == "__main__":
main()
Loading