This commit is contained in:
miles authored and GitHub committed 2025-02-25 17:11:32 +00:00
1 parent ba96c2a70c
commit 9f6a23940f
3 files changed
+119 -86

No files matched your search

@@ -3,12 +3,11 @@ userbase.init({ appId: '7cd8e25b-723d-4af7-8bdf-ef558bd0dfcc' }); // Replace wit
document.getElementById('signup-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('signup-email').value;
const username = document.getElementById('signup-username').value; // Email as username
const password = document.getElementById('signup-password').value;
try {
const user = await userbase.signUp({ username: email, password });
// Save user info in cookies
const user = await userbase.signUp({ username: username, password });
document.cookie = `user=${user.username}; path=/;`;
alert('Signup successful!');
} catch (error) {
@@ -19,78 +18,121 @@ document.getElementById('signup-form').addEventListener('submit', async (e) => {
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('login-email').value;
const username = document.getElementById('login-username').value; // Email as username
const password = document.getElementById('login-password').value;
try {
const user = await userbase.signIn({ username: email, password });
// Save user info in cookies
const user = await userbase.signIn({ username: username, password });
document.cookie = `user=${user.username}; path=/;`;
alert('Login successful!');
document.getElementById('form-container').style.display = 'none';
document.getElementById('notes-container').style.display = 'block';
loadNotes();
document.getElementById('note-management').style.display = 'block';
} catch (error) {
console.error('Login error:', error);
alert('Login failed: ' + error.message);
}
});
// Function to load cookies
function loadCookies() {
const cookies = document.cookie.split('; ');
const userCookie = cookies.find(row => row.startsWith('user='));
if (userCookie) {
const user = userCookie.split('=')[1];
alert(`Welcome back, ${user}!`);
document.getElementById('form-container').style.display = 'none';
document.getElementById('notes-container').style.display = 'block';
loadNotes();
// Function to save note to Userbase
async function saveNote() {
const note = document.getElementById('note-input').value;
if (!note) {
alert('Please enter a note to save.');
return;
}
try {
const user = await userbase.getCurrentUser(); // Get the current user
await userbase.insert({
database: 'user_notes',
item: { userId: user.userId, text: note }
});
alert('Note saved successfully!');
document.getElementById('note-input').value = ''; // Clear input
loadNotes(); // Reload notes after saving
} catch (error) {
console.error('Error saving note:', error);
alert('Failed to save note: ' + error.message);
}
}
// Load notes from local storage
function loadNotes() {
const notes = JSON.parse(localStorage.getItem('userNotes')) || [];
const savedNotesDiv = document.getElementById('saved-notes');
savedNotesDiv.innerHTML = '';
notes.forEach((note, index) => {
const noteDiv = document.createElement('div');
noteDiv.className = 'note';
noteDiv.textContent = note;
// Function to load notes from Userbase
async function loadNotes() {
try {
const user = await userbase.getCurrentUser(); // Get the current user
const result = await userbase.query({
database: 'user_notes',
filter: { userId: user.userId }
});
const notesList = document.getElementById('notes-list');
notesList.innerHTML = ''; // Clear existing notes
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.className = 'delete-note';
deleteButton.onclick = () => deleteNote(index);
if (result.length > 0) {
result.forEach(note => {
const noteItem = document.createElement('li');
noteItem.className = 'note-item';
noteItem.textContent = note.text;
noteDiv.appendChild(deleteButton);
savedNotesDiv.appendChild(noteDiv);
});
}
// Create delete button
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.style.marginLeft = '10px';
deleteButton.onclick = () => deleteNote(note.id); // Bind delete function
// Delete note from local storage
function deleteNote(index) {
const notes = JSON.parse(localStorage.getItem('userNotes')) || [];
notes.splice(index, 1);
localStorage.setItem('userNotes', JSON.stringify(notes));
loadNotes();
}
// Save note to local storage
document.getElementById('save-note').addEventListener('click', () => {
const noteInput = document.getElementById('note-input');
const note = noteInput.value;
if (note) {
const notes = JSON.parse(localStorage.getItem('userNotes')) || [];
notes.push(note);
localStorage.setItem('userNotes', JSON.stringify(notes));
noteInput.value = '';
loadNotes();
} else {
alert('Please enter a note.');
noteItem.appendChild(deleteButton);
notesList.appendChild(noteItem);
});
} else {
alert('No notes found for this user.');
}
} catch (error) {
console.error('Error loading notes:', error);
alert('Failed to load notes: ' + error.message);
}
}
// Function to delete a note from Userbase
async function deleteNote(noteId) {
try {
await userbase.delete(noteId);
alert('Note deleted successfully!');
loadNotes(); // Reload notes after deletion
} catch (error) {
console.error('Error deleting note:', error);
alert('Failed to delete note: ' + error.message);
}
}
// Function to get user metadata
async function getUserMetadata(userId, accessToken) {
try {
const response = await fetch(`https://v1.userbase.com/v1/admin/users/${userId}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
throw new Error('Failed to fetch user metadata');
}
const userData = await response.json();
console.log('User Metadata:', userData);
alert(`User Metadata Retrieved: ${JSON.stringify(userData)}`);
} catch (error) {
console.error('Error fetching user metadata:', error);
alert('Error fetching user metadata: ' + error.message);
}
}
// Example usage of getUserMetadata
document.getElementById('get-user-metadata').addEventListener('click', async () => {
const userId = 'USER_ID'; // Replace with the actual user ID
const accessToken = 'ACCESS_TOKEN'; // Replace with the actual access token
await getUserMetadata(userId, accessToken);
});
// Load cookies on page load
window.onload = loadCookies;
// Event listeners for buttons
document.getElementById('save-note').addEventListener('click', saveNote);
document.getElementById('load-notes').addEventListener('click', loadNotes);
@@ -3,34 +3,36 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Userbase Login/Signup</title>
<title>Userbase Note Management</title>
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="https://sdk.userbase.com/2/userbase.js"></script>
</head>
<body>
<div class="container">
<h1>Userbase Login/Signup</h1>
<h1>Userbase Note Management</h1>
<div id="form-container">
<form id="signup-form">
<h2>Sign Up</h2>
<input type="email" id="signup-email" placeholder="Email" required>
<input type="text" id="signup-username" placeholder="Username (Email)" required>
<input type="password" id="signup-password" placeholder="Password" required>
<button type="submit">Sign Up</button>
</form>
<form id="login-form">
<h2>Login</h2>
<input type="email" id="login-email" placeholder="Email" required>
<input type="text" id="login-username" placeholder="Username (Email)" required>
<input type="password" id="login-password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
</div>
<div id="notes-container" style="display: none;">
<h2>Your Notes</h2>
<textarea id="note-input" placeholder="Write your note here..."></textarea>
<div id="note-management">
<h2>Note Management</h2>
<input type="text" id="note-input" placeholder="Write your note here..." />
<button id="save-note">Save Note</button>
<div id="saved-notes"></div>
<button id="load-notes">Load Notes</button>
<button id="get-user-metadata">Get User Metadata</button>
<ul id="notes-list" style="margin-top: 20px;"></ul>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
</html>
@@ -22,9 +22,8 @@ form {
margin-bottom: 20px;
}
input[type="email"],
input[type="password"],
textarea {
input[type="text"],
input[type="password"] {
width: 100%;
padding: 10px;
margin: 10px 0;
@@ -45,27 +44,17 @@ button:hover {
background-color: #4cae4c;
}
#saved-notes {
margin-top: 20px;
#notes-list {
list-style-type: none;
padding: 0;
}
.note {
.note-item {
display: flex;
justify-content: space-between;
align-items: center;
background: #e9ecef;
padding: 10px;
margin: 5px 0;
border-radius: 4px;
}
.delete-note {
margin-left: 10px;
padding: 5px 10px;
background-color: #d9534f;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.delete-note:hover {
background-color: #c9302c;
}