Я считаю, что веб -приложение nuxt.js (vue.js) с Firebase правильно настроено, так как я могу войти в систему с Firebase/Apple, используя SignInWithPopup. Проблема возникает только при входе с перенаправлением. Я правильно перенаправлен на страницу входа Apple. Я ввожу свои учетные данные и перенаправлен обратно на страницу входа. Абсолютно ничего не происходит-нет сообщения об ошибке, ничего.
// Define page meta to use appropriate layout
definePageMeta({
layout: 'web-no-tab-bar'
});
useSeoMeta({
title: 'Sign-In'
});
import { httpsCallable } from 'firebase/functions'
import { GoogleAuthProvider, OAuthProvider, signInWithPopup, updateProfile, getAdditionalUserInfo, signInWithRedirect, getRedirectResult, getAuth } from 'firebase/auth'
import { doc, getDoc, Firestore } from 'firebase/firestore'
// Store instances
const authStore = useAuthStore()
const flashStore = useFlashStore()
// Firebase instances
const { $auth, $firestoreDb, $functionsInstance } = useNuxtApp()
const auth = getAuth();
getRedirectResult(auth)
.then((result) => { //-----------> ALWAYS NULL
// Check if result is not null before processing
if (result) {
alert('result')
const credential = OAuthProvider.credentialFromResult(result);
if (credential) {
// You can also get the Apple OAuth Access and ID Tokens.
const accessToken = credential.accessToken;
const idToken = credential.idToken;
}
// The signed-in user info.
const user = result.user;
}
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The credential that was used.
const credential = OAuthProvider.credentialFromError(error);
// ...
});
/**
* ================================
* Apple Sign-In
* ================================
*/
const signInWithApple = async () => {
try {
const provider = new OAuthProvider('apple.com')
// Configure Apple provider with required scopes
provider.addScope('email')
provider.addScope('name')
const result = await signInWithRedirect($auth, provider)
} catch (err: any) {
// eslint-disable-next-line no-console
console.error('Apple sign-in failed:', err)
flashStore.show(err?.message || 'Apple sign-in failed. Please try again.')
}
}
/**
* ================================
* Providers Sign-In
* ================================
*/
// Verify user profile after authentication. Not for email sign-in. For providers.
const checkUserProfileAfterProvidersSignIn = async (userId: string) => {
try {
const userDoc = await getDoc(doc($firestoreDb as Firestore, 'users', userId))
// If missing username or country, treat as new user
if (!userDoc.exists() || !userDoc.data()?.username || !userDoc.data()?.country) {
navigateTo('/authentication/user-info-collect')
} else {
// Persist user country in localStorage for later use
if (utils.isLocalStorageAvailable()) {
const key = `selectedCountry_${userId}`
window.localStorage.setItem(key, userDoc.data()?.country.toLowerCase())
}
// Redirect back to the page the visitor came from (or home)
const target = utils.isLocalStorageAvailable()
? window.localStorage.getItem('previousUrlForAfterSignIn') || '/'
: '/'
navigateTo(target)
}
} catch (err) {
// eslint-disable-next-line no-console
console.error('Error verifying user profile after Google sign-in:', err)
navigateTo('/')
}
}
// Store previous URL in localStorage for future redirect handling
onMounted(() => {
if (utils.isLocalStorageAvailable()) {
const previousUrl = (window.history.state && window.history.state.back) || document.referrer || '/';
localStorage.setItem('previousUrlForAfterSignIn', previousUrl);
}
});
Подробнее здесь: https://stackoverflow.com/questions/796 ... tjs-js-app
Firebase SignInwithredIrect с Apple Login не удается в приложении Nuxtjs / JS ⇐ Javascript
Форум по Javascript
1752166010
Anonymous
Я считаю, что веб -приложение nuxt.js (vue.js) с Firebase правильно настроено, так как я могу войти в систему с Firebase/Apple, используя SignInWithPopup. Проблема возникает только при входе с перенаправлением. Я правильно перенаправлен на страницу входа Apple. Я ввожу свои учетные данные и перенаправлен обратно на страницу входа. Абсолютно ничего не происходит-нет сообщения об ошибке, ничего.
// Define page meta to use appropriate layout
definePageMeta({
layout: 'web-no-tab-bar'
});
useSeoMeta({
title: 'Sign-In'
});
import { httpsCallable } from 'firebase/functions'
import { GoogleAuthProvider, OAuthProvider, signInWithPopup, updateProfile, getAdditionalUserInfo, signInWithRedirect, getRedirectResult, getAuth } from 'firebase/auth'
import { doc, getDoc, Firestore } from 'firebase/firestore'
// Store instances
const authStore = useAuthStore()
const flashStore = useFlashStore()
// Firebase instances
const { $auth, $firestoreDb, $functionsInstance } = useNuxtApp()
const auth = getAuth();
getRedirectResult(auth)
.then((result) => { //-----------> ALWAYS NULL
// Check if result is not null before processing
if (result) {
alert('result')
const credential = OAuthProvider.credentialFromResult(result);
if (credential) {
// You can also get the Apple OAuth Access and ID Tokens.
const accessToken = credential.accessToken;
const idToken = credential.idToken;
}
// The signed-in user info.
const user = result.user;
}
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The credential that was used.
const credential = OAuthProvider.credentialFromError(error);
// ...
});
/**
* ================================
* Apple Sign-In
* ================================
*/
const signInWithApple = async () => {
try {
const provider = new OAuthProvider('apple.com')
// Configure Apple provider with required scopes
provider.addScope('email')
provider.addScope('name')
const result = await signInWithRedirect($auth, provider)
} catch (err: any) {
// eslint-disable-next-line no-console
console.error('Apple sign-in failed:', err)
flashStore.show(err?.message || 'Apple sign-in failed. Please try again.')
}
}
/**
* ================================
* Providers Sign-In
* ================================
*/
// Verify user profile after authentication. Not for email sign-in. For providers.
const checkUserProfileAfterProvidersSignIn = async (userId: string) => {
try {
const userDoc = await getDoc(doc($firestoreDb as Firestore, 'users', userId))
// If missing username or country, treat as new user
if (!userDoc.exists() || !userDoc.data()?.username || !userDoc.data()?.country) {
navigateTo('/authentication/user-info-collect')
} else {
// Persist user country in localStorage for later use
if (utils.isLocalStorageAvailable()) {
const key = `selectedCountry_${userId}`
window.localStorage.setItem(key, userDoc.data()?.country.toLowerCase())
}
// Redirect back to the page the visitor came from (or home)
const target = utils.isLocalStorageAvailable()
? window.localStorage.getItem('previousUrlForAfterSignIn') || '/'
: '/'
navigateTo(target)
}
} catch (err) {
// eslint-disable-next-line no-console
console.error('Error verifying user profile after Google sign-in:', err)
navigateTo('/')
}
}
// Store previous URL in localStorage for future redirect handling
onMounted(() => {
if (utils.isLocalStorageAvailable()) {
const previousUrl = (window.history.state && window.history.state.back) || document.referrer || '/';
localStorage.setItem('previousUrlForAfterSignIn', previousUrl);
}
});
Подробнее здесь: [url]https://stackoverflow.com/questions/79697369/firebase-signinwithredirect-with-apple-login-fails-on-a-nuxtjs-js-app[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия