Merge branch 'main' of interstellardevelopment.org:YasinOnm08/interstellar_ai

This commit is contained in:
YasinOnm08 2024-10-01 15:46:33 +02:00
commit 99a42a1f3a
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
export const createAccount = async (username: string, email: string, password: string) => {
const data = {
@ -60,7 +73,27 @@ export const getData = async (usernameOrEmail: string, password: string) => {
email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined,
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) => {
@ -81,7 +114,13 @@ export const checkCredentials = async (usernameOrEmail: string, password: string
email: usernameOrEmail.includes('@') ? usernameOrEmail : undefined,
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) => {

View file

@ -50,25 +50,11 @@ const Login: React.FC = () => {
// Function to handle login
const handleLogin = async () => {
const savedAccountEmail = localStorage.getItem('accountEmail');
const savedAccountPassword = localStorage.getItem('accountPassword');
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 (accountName && password) {
const success = await checkCredentials(accountName, password);
if (success) {
setIsLoggedIn(true); // Successful login
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 {
alert('Incorrect credentials');
}

View file

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

View file

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

View file

@ -97,6 +97,7 @@ class API:
@self.app.route('/interstellar_ai/db', methods=['POST'])
def db_manipulate():
sent_data = request.get_json()
print(sent_data)
action = sent_data.get('action')
if action == "create_account":
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)})
elif action == "delete_account":
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"})

View file

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