-
Notifications
You must be signed in to change notification settings - Fork 41
Added Gargi Sarma's chat modules (ggserver, ggclient, chat_gg, auth_m… #150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Gargi2023
wants to merge
1
commit into
main
Choose a base branch
from
gargi-mentalhealth-hub
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
|
|
||
| # 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 :)