Сброс пароля SupabaseJavascript

Форум по Javascript
Ответить
Anonymous
 Сброс пароля Supabase

Сообщение Anonymous »

Я делаю сайт для сброса пароля с помощью приложения Supabase and Flutter. Пользователь входит в свою электронную почту и нажимает отправку ссылки на сброс < /p>
try {

await supabase.auth.resetPasswordForEmail(
email,
redirectTo: 'https://snapchatpages.github.io/changepassword/' );
< /code>
Проблема в том, что я понимаю, что #_TOKEN_HASH требуется, но Supabse отправляет A = код? В URL -адресу, которое недостаточно, чтобы проверить и изменить пароль пользователя. Что мне нужно сделать или изменить?


Reset Password

body {
font-family: Arial, sans-serif;
max-width: 400px;
margin: 50px auto;
padding: 20px;
text-align: center;
border: 1px solid #ddd;
border-radius: 8px;
}

input {
width: 90%;
padding: 10px;
margin: 10px 0;
font-size: 16px;
}

button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}

.error-message {
color: #d00;
margin-top: 10px;
}

.success-message {
color: #080;
margin-top: 10px;
}

#loading-message {
color: #555;
margin-bottom: 20px;
}



Reset Your Password

Loading, please wait...




Save New Password








< /code>
js file < /p>

// Supabase configuration
const supabaseUrl = 'my-actual-url';
const supabaseAnonKey = 'my-actual-annonkey';

const SupabaseLoad = supabase.createClient(supabaseUrl, supabaseAnonKey);

document.addEventListener('DOMContentLoaded', () => {
const newPasswordInput = document.getElementById('new-password');
const confirmPasswordInput = document.getElementById('confirm-password');
const updateButton = document.getElementById('update-password-btn');
const messageDiv = document.getElementById('message');
const passwordForm = document.getElementById('password-form');
const loadingMessage = document.getElementById('loading-message');

// Function to display messages to the user
function showMessage(text, isError) {
messageDiv.textContent = text;
messageDiv.className = isError ? 'error-message' : 'success-message';
}

// --- FIXED: Handle Supabase recovery code from query param ---
const queryParams = new URLSearchParams(window.location.search);
const code = queryParams.get('code');
const emailParam = queryParams.get('email');
const email = emailParam ? decodeURIComponent(emailParam) : null;

if (code && email) {
SupabaseLoad.auth.verifyOtp({
type: 'recovery',
token: code,
email: email
}).then(({ data, error }) => {
if (error) {
console.error('Error verifying recovery code:', error);
showMessage('Invalid or expired reset link.', true);
} else {
console.log('Session set via recovery code:', data);
window.history.replaceState({}, document.title, window.location.pathname);
}
});
} else {
loadingMessage.style.display = 'none';
showMessage('Missing code or email in the reset link.', true);
}

// --- Rely on Supabase's automatic session restoration OR the manual set session ---
SupabaseLoad.auth.onAuthStateChange((event, session) => {
console.log('Auth state changed:', event);
if (session) {
// A session was found. The user is authenticated.
console.log('Session restored from recovery code:', session);
loadingMessage.style.display = 'none'; // Hide the loading message
passwordForm.style.display = 'block'; // Show the password form
showMessage('Session established. Please enter your new password.', false);
} else if (event === 'SIGNED_OUT') {
// User signed out, hide the form
loadingMessage.style.display = 'none';
passwordForm.style.display = 'none';
showMessage('Your session has expired or you have signed out. Please use a valid password reset link.', true);
} else if (event === 'INITIAL_SESSION') {
// This event fires on page load if no session is found.
loadingMessage.style.display = 'none';
passwordForm.style.display = 'none';
showMessage('No session found. Please use the complete link from your password reset email.', true);
}
});

// --- Handle form submission ---
if (updateButton) {
updateButton.addEventListener('click', async (e) => {
e.preventDefault();

const newPassword = newPasswordInput.value;
const confirmPassword = confirmPasswordInput.value;

if (newPassword.length < 6) {
showMessage('Password must be at least 6 characters long.', true);
return;
}

if (newPassword !== confirmPassword) {
showMessage('Passwords do not match.', true);
return;
}

try {
const { data, error } = await SupabaseLoad.auth.updateUser({ password: newPassword });

if (error) {
console.error('Password update error:', error);
showMessage(`Password update failed: ${error.message}`, true);
} else {
console.log('Password updated successfully:', data);
showMessage('Your password has been updated successfully! You can now close this page.', false);
if (updateButton) updateButton.disabled = true;
}
} catch (err) {
console.error('An unexpected error occurred:', err);
showMessage('An unexpected error occurred. Please try again.', true);
}
});
}
});


Подробнее здесь: https://stackoverflow.com/questions/796 ... et-by-link
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»