added auth so subscribe request

This commit is contained in:
cpu
2025-03-28 15:06:02 +01:00
parent 0414bdb217
commit 451a61d357
4 changed files with 133 additions and 9 deletions

View File

@@ -10,12 +10,32 @@ let actionHandlers = {}; // Store handlers for different Flic actions
function getBasicAuthCredentials() {
const storedAuth = localStorage.getItem('basicAuthCredentials');
if (storedAuth) {
try { return JSON.parse(storedAuth); } catch (error) { console.error('Failed to parse stored credentials:', error); }
try {
const credentials = JSON.parse(storedAuth);
// Check if the credentials are valid
if (credentials.username && credentials.password) {
console.log('Using stored basic auth credentials.');
return credentials;
}
} catch (error) {
console.error('Failed to parse stored credentials:', error);
}
}
// No valid stored credentials found
// The function will return null and the caller should handle prompting if needed
console.log('No valid stored credentials found.');
return null;
}
// Prompt the user for credentials after permissions are granted
function promptForCredentials() {
console.log('Prompting user for auth credentials.');
const username = prompt('Please enter your username for backend authentication:');
if (!username) return null;
const password = prompt('Please enter your password:');
if (!password) return null;
const credentials = { username, password };
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
return credentials;
@@ -59,12 +79,33 @@ async function subscribeToPush() {
}
try {
// First request notification permission
console.log('Requesting notification permission...');
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
console.warn('Notification permission denied.');
alert('Please enable notifications to link the Flic button.');
return;
}
console.log('Notification permission granted.');
// After permission is granted, check for stored credentials or prompt user
let credentials = getBasicAuthCredentials();
if (!credentials) {
const confirmAuth = confirm('Do you want to set up credentials for push notifications now?');
if (!confirmAuth) {
console.log('User declined to provide auth credentials.');
return;
}
credentials = promptForCredentials();
if (!credentials) {
console.log('User canceled credential input.');
alert('Authentication required to set up push notifications.');
return;
}
}
const registration = await navigator.serviceWorker.ready;
let existingSubscription = await registration.pushManager.getSubscription();
@@ -113,8 +154,20 @@ async function sendSubscriptionToServer(subscription, buttonId) {
console.log(`Sending subscription for button "${buttonId}" to backend...`);
const credentials = getBasicAuthCredentials();
if (!credentials) {
alert('Authentication required to save button link.');
return;
// One more chance to enter credentials if needed
const confirmAuth = confirm('Authentication required to complete setup. Provide credentials now?');
if (!confirmAuth) {
alert('Authentication required to save button link.');
return;
}
const newCredentials = promptForCredentials();
if (!newCredentials) {
alert('Authentication required to save button link.');
return;
}
credentials = newCredentials;
}
const headers = { 'Content-Type': 'application/json' };
@@ -122,16 +175,18 @@ async function sendSubscriptionToServer(subscription, buttonId) {
if (authHeader) headers['Authorization'] = authHeader;
try {
// Add support for handling CORS preflight with credentials
const response = await fetch(`${BACKEND_URL}/subscribe`, {
method: 'POST',
body: JSON.stringify({ button_id: buttonId, subscription: subscription }),
headers: headers
headers: headers,
credentials: 'include' // This ensures credentials are sent with OPTIONS requests too
});
if (response.ok) {
const result = await response.json();
console.log('Subscription sent successfully:', result.message);
// Maybe show a success message to the user
alert('Push notification setup completed successfully!');
} else {
let errorMsg = `Server error: ${response.status}`;
if (response.status === 401 || response.status === 403) {