Merge branch 'main' into main

This commit is contained in:
Patrick 2024-10-01 15:45:37 +02:00
commit 119832ee39
6 changed files with 567 additions and 525 deletions

View file

@ -31,6 +31,19 @@ export const sendToDatabase = async (data: any): Promise<boolean> => {
} }
}; };
export const sendToDatabaseAndGetString = async (data: any): Promise<string> => {
try {
const response = await axios.post("http://localhost:5000/interstellar_ai/db", data);
const status = response.data.status;
const success = response.data.response;
postMessage({ status, success });
return success;
} catch (error) {
postMessage({ status: 500, success: false });
return "false";
}
};
// Functions for each action // Functions for each action
export const createAccount = async (username: string, email: string, password: string) => { export const createAccount = async (username: string, email: string, password: string) => {
const data = { const data = {
@ -60,7 +73,27 @@ export const getData = async (usernameOrEmail: string, password: string) => {
email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined, email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined,
password, password,
}; };
return await sendToDatabase(data); return await sendToDatabaseAndGetString(data);
};
export const getEmail = async (usernameOrEmail: string, password: string): Promise<string> => {
const data = {
action: "get_email",
username: usernameOrEmail.includes('@') ? undefined : usernameOrEmail,
email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined,
password,
};
return await sendToDatabaseAndGetString(data);
};
export const getName = async (usernameOrEmail: string, password: string): Promise<string> => {
const data = {
action: "get_name",
username: usernameOrEmail.includes('@') ? undefined : usernameOrEmail,
email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined,
password,
};
return await sendToDatabaseAndGetString(data);
}; };
export const changeData = async (usernameOrEmail: string, password: string, newData: any) => { export const changeData = async (usernameOrEmail: string, password: string, newData: any) => {
@ -81,7 +114,13 @@ export const checkCredentials = async (usernameOrEmail: string, password: string
email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined, email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined,
password, password,
}; };
return await sendToDatabase(data); var sendBack = await sendToDatabase(data);
if (sendBack) {
localStorage.setItem("accountEmail", await getEmail(usernameOrEmail, password))
localStorage.setItem("accountName", await getName(usernameOrEmail, password))
localStorage.setItem("accountPassword", password)
}
return sendBack
}; };
export const deleteAccount = async (usernameOrEmail: string, password: string) => { export const deleteAccount = async (usernameOrEmail: string, password: string) => {

View file

@ -50,25 +50,11 @@ const Login: React.FC = () => {
// Function to handle login // Function to handle login
const handleLogin = async () => { const handleLogin = async () => {
const savedAccountEmail = localStorage.getItem('accountEmail'); if (accountName && password) {
const savedAccountPassword = localStorage.getItem('accountPassword'); const success = await checkCredentials(accountName, password);
const savedAccountName = localStorage.getItem('accountName');
// Check if savedAccountName or savedAccountEmail is not null before passing to checkCredentials
var accountIdentifier = savedAccountName || savedAccountEmail;
if (!accountIdentifier) {
accountIdentifier = accountName
}
if (accountIdentifier && password) {
const success = await checkCredentials(accountIdentifier, password);
if (success) { if (success) {
setIsLoggedIn(true); // Successful login setIsLoggedIn(true); // Successful login
setShowLoginPopup(false); // Close the login popup setShowLoginPopup(false); // Close the login popup
// Save credentials to localStorage (optional in case of changes)
localStorage.setItem('accountName', savedAccountName || accountName);
localStorage.setItem('accountEmail', savedAccountEmail || email);
localStorage.setItem('accountPassword', savedAccountPassword || password);
} else { } else {
alert('Incorrect credentials'); alert('Incorrect credentials');
} }

View file

@ -39,9 +39,6 @@ const PrivacySettings: React.FC<PrivacySettingsProps> = ({ selectedOption, handl
</div> </div>
</div> </div>
<br /> <br />
<p>
After changing the preferred settings, please reload the website so it can update itself properly.
</p>
</div> </div>
</> </>
); );

View file

@ -11,13 +11,13 @@ import PrivacySettings from './PrivacySettings';
import FontSizeSetting from './FontSize'; import FontSizeSetting from './FontSize';
import OpenSourceModeToggle from './OpenSourceToggle'; import OpenSourceModeToggle from './OpenSourceToggle';
import { import {
changePassword,
changeData, changeData,
createAccount,
deleteAccount, deleteAccount,
getData,
} from '../../backend/database'; } from '../../backend/database';
import ThemeDropdown from './DropDownTheme'; import ThemeDropdown from './DropDownTheme';
const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = ({ closeSettings, accountName }) => { const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = ({ closeSettings, accountName }) => {
const getItemFromLocalStorage = (key: string) => { const getItemFromLocalStorage = (key: string) => {
@ -125,9 +125,6 @@ const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = (
disableChatHistory, disableChatHistory,
disableAIMemory, disableAIMemory,
openSourceMode, openSourceMode,
newName,
newEmail,
newPassword,
preferredMeasurement, preferredMeasurement,
}, },
theme: { theme: {
@ -284,6 +281,8 @@ const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = (
localStorage.removeItem('accountName'); localStorage.removeItem('accountName');
localStorage.removeItem('accountEmail'); localStorage.removeItem('accountEmail');
localStorage.removeItem('accountPassword'); localStorage.removeItem('accountPassword');
alert('Successfully logged out!');
window.location.reload();
}; };
useEffect(() => { useEffect(() => {
@ -327,7 +326,7 @@ const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = (
const handleRadioChange = (newValue: string) => { const handleRadioChange = (newValue: string) => {
setSelectedOption(newValue); // Update the state with the selected option setSelectedOption(newValue); // Update the state with the selected option
if (openSourceMode){ if (openSourceMode) {
newValue += " (FOSS)" newValue += " (FOSS)"
} }
localStorage.setItem('radioSelection', newValue); // Save the selection for persistence localStorage.setItem('radioSelection', newValue); // Save the selection for persistence
@ -335,38 +334,46 @@ const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = (
// Function to handle updating all credentials // Function to handle updating all credentials
const handleUpdateCredentials = async () => { const handleUpdateCredentials = async () => {
// Update account information var useName = localStorage.getItem("accountName")
const newData = { var useEmail = localStorage.getItem("accountEmail")
name: newName || accountName, // Keep old name if new name is not provided var usePassword = localStorage.getItem("accountPassword")
email: newEmail || '', // Optionally use empty string if not provided if (useName && useEmail && usePassword) {
}; await deleteAccount(useName, usePassword)
// First change the data if (newName != "") {
const dataSuccess = await changeData(accountName, currentPassword, newData); useName = newName
} if (newEmail != "") {
useEmail = newEmail
} if (newPassword != "") {
usePassword = newPassword
}
// Then change the password if a new password is provided if (await createAccount(useName, useEmail, usePassword)) {
const passwordSuccess = newPassword ? if (await changeData(useName, usePassword, settings)) {
await changePassword(accountName, currentPassword, newPassword) : localStorage.setItem("currentName", useName)
true; // If no new password, treat as success localStorage.setItem("currentPassword", usePassword)
localStorage.setItem("currentEmail", useEmail)
if (dataSuccess && passwordSuccess) { alert('Account successfully changed!')
alert('Credentials updated successfully!'); window.location.reload()
closeSettings(); // Close settings after updating }
} else { }
alert('Failed to update credentials. Please check your current password.');
} }
}; };
// Function to handle account deletion // Function to handle account deletion
const handleDeleteAccount = async () => { const handleDeleteAccount = async () => {
const success = await deleteAccount(accountName, currentPassword); var useName = localStorage.getItem("accountName")
var usePassword = localStorage.getItem("accountPassword")
if (useName && usePassword) {
const success = await deleteAccount(useName, usePassword);
if (success) { if (success) {
alert('Account deleted successfully!'); alert('Account deleted successfully!');
closeSettings(); // Close settings after deletion window.location.reload()
// Optionally, redirect or reset state here // Optionally, redirect or reset state here
} else { } else {
alert('Account deletion failed. Please check your password.'); alert('Account deletion failed. Please check your password.');
} }
}
}; };
@ -589,7 +596,7 @@ const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = (
</div> </div>
<div className="settings-option"> <div className="settings-option">
<h3>Import the settings</h3> <h3>Import the settings</h3>
<input type="file" onChange={handleImport} accept=".json" className='import-file'/> <input type="file" onChange={handleImport} accept=".json" className='import-file' />
</div> </div>
</div> </div>
); );
@ -635,9 +642,11 @@ const Settings: React.FC<{ closeSettings: () => void; accountName: string }> = (
<h2>Settings for {accountName}</h2> <h2>Settings for {accountName}</h2>
{renderSettingsContent()} {renderSettingsContent()}
<button className="close-popup" onClick={closeSettings}>Close</button> <button className="close-popup" onClick={closeSettings}>Close</button>
<button className="apply" onClick={() => { <button className="apply" onClick={async () => {
getAllLocalStorageItems(); getAllLocalStorageItems();
closeSettings(); closeSettings();
await changeData(localStorage.getItem('accountName') ?? "hello", localStorage.getItem('accountPassword') ?? "hello", settings) // ????
window.location.reload();
}}> }}>
Apply Apply
</button> </button>

View file

@ -97,6 +97,7 @@ class API:
@self.app.route('/interstellar_ai/db', methods=['POST']) @self.app.route('/interstellar_ai/db', methods=['POST'])
def db_manipulate(): def db_manipulate():
sent_data = request.get_json() sent_data = request.get_json()
print(sent_data)
action = sent_data.get('action') action = sent_data.get('action')
if action == "create_account": if action == "create_account":
return jsonify({'status': 200, 'response': self.db.add_user(sent_data)}) return jsonify({'status': 200, 'response': self.db.add_user(sent_data)})
@ -110,6 +111,10 @@ class API:
return jsonify({'status': 200, 'response': self.db.check_credentials(sent_data)}) return jsonify({'status': 200, 'response': self.db.check_credentials(sent_data)})
elif action == "delete_account": elif action == "delete_account":
return jsonify({'status': 200, 'response': self.db.delete_user(sent_data)}) return jsonify({'status': 200, 'response': self.db.delete_user(sent_data)})
elif action == "get_email":
return jsonify({'status': 200, 'response': self.db.get_email(sent_data)})
elif action == "get_name":
return jsonify({'status': 200, 'response': self.db.get_name(sent_data)})
return jsonify({'status': 401, 'response': "Invalid action"}) return jsonify({'status': 401, 'response': "Invalid action"})

View file

@ -9,13 +9,9 @@ class DB:
self.database = {} self.database = {}
def ensure_username(self, data): def ensure_username(self, data):
print(data)
print(self.database)
if 'username' in data: if 'username' in data:
print("usr")
return data.get('username') return data.get('username')
elif 'email' in data: elif 'email' in data:
print("email")
for index, entry in self.database: for index, entry in self.database:
if entry.get('email') == data.get('email'): if entry.get('email') == data.get('email'):
return index return index
@ -34,15 +30,12 @@ class DB:
user_data = {"hashed_password": hashed_password, "email": email, "data": None} user_data = {"hashed_password": hashed_password, "email": email, "data": None}
if username not in self.database: if username not in self.database:
self.database[username] = user_data self.database[username] = user_data
print("yes")
self.save_database() self.save_database()
return True return True
print("fail")
return False return False
def delete_user(self, data): def delete_user(self, data):
username = self.ensure_username(data) username = self.ensure_username(data)
data = data.get('data')
if not self.check_credentials(data): if not self.check_credentials(data):
return False return False
@ -52,11 +45,10 @@ class DB:
def change_data(self, data): def change_data(self, data):
username = self.ensure_username(data) username = self.ensure_username(data)
data = data.get('data')
if not self.check_credentials(data): if not self.check_credentials(data):
return False return False
self.database[username]['data'] = data self.database[username]['data'] = data.get('data')
self.save_database() self.save_database()
return True return True
@ -75,8 +67,6 @@ class DB:
username = self.ensure_username(data) username = self.ensure_username(data)
password = data.get('password') password = data.get('password')
if username not in self.database: if username not in self.database:
print("no username")
print(username)
return False return False
stored_hashed_password = self.database[username]["hashed_password"] stored_hashed_password = self.database[username]["hashed_password"]
@ -92,6 +82,22 @@ class DB:
send_back = self.database[username].get('data') send_back = self.database[username].get('data')
return send_back return send_back
def get_email(self, data):
username = self.ensure_username(data)
if not self.check_credentials(data):
return None
send_back = self.database[username].get('email')
return send_back
def get_name(self, data):
username = self.ensure_username(data)
if not self.check_credentials(data):
return None
send_back = self.ensure_username(data)
return send_back
def save_database(self): def save_database(self):
if os.environ.get('PRODUCTION') == "YES": if os.environ.get('PRODUCTION') == "YES":
server = pycouchdb.Server("http://admin:admin@localhost:5984/") server = pycouchdb.Server("http://admin:admin@localhost:5984/")