add firebase and sign up
This commit is contained in:
72
src/lib/auth/userStore.svelte.js
Normal file
72
src/lib/auth/userStore.svelte.js
Normal file
@@ -0,0 +1,72 @@
|
||||
import { auth, db, googleProvider } from '../firebase.js';
|
||||
import { onAuthStateChanged, signInWithPopup, signOut as fbSignOut } from 'firebase/auth';
|
||||
import { doc, getDoc, setDoc, serverTimestamp } from 'firebase/firestore';
|
||||
import { initSelectionListener } from '../layout/selection.svelte.js';
|
||||
import { initEntriesListener } from '../stores/entriesStore.svelte.js';
|
||||
|
||||
let _initialized = false;
|
||||
|
||||
let user = $state(null);
|
||||
let userProfile = $state(null);
|
||||
let loading = $state(true);
|
||||
let needsCountry = $state(false);
|
||||
|
||||
export function getUser() { return user; }
|
||||
export function getUserProfile() { return userProfile; }
|
||||
export function getLoading() { return loading; }
|
||||
export function getNeedsCountry() { return needsCountry; }
|
||||
|
||||
export async function signInWithGoogle() {
|
||||
await signInWithPopup(auth, googleProvider);
|
||||
}
|
||||
|
||||
export async function signOut() {
|
||||
await fbSignOut(auth);
|
||||
user = null;
|
||||
userProfile = null;
|
||||
needsCountry = false;
|
||||
}
|
||||
|
||||
export async function setHomeCountry(country) {
|
||||
if (!user) return;
|
||||
await setDoc(doc(db, 'users', user.uid), {
|
||||
displayName: user.displayName,
|
||||
photoURL: user.photoURL,
|
||||
email: user.email,
|
||||
homeCountry: country,
|
||||
visitedCountries: [],
|
||||
createdAt: serverTimestamp(),
|
||||
});
|
||||
userProfile = { ...userProfile, homeCountry: country, visitedCountries: [] };
|
||||
needsCountry = false;
|
||||
}
|
||||
|
||||
export function initAuth() {
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
onAuthStateChanged(auth, async (fbUser) => {
|
||||
if (fbUser) {
|
||||
user = fbUser;
|
||||
initSelectionListener(fbUser.uid);
|
||||
initEntriesListener(fbUser.uid);
|
||||
const docRef = doc(db, 'users', fbUser.uid);
|
||||
const docSnap = await getDoc(docRef);
|
||||
if (docSnap.exists()) {
|
||||
userProfile = docSnap.data();
|
||||
needsCountry = false;
|
||||
} else {
|
||||
userProfile = {
|
||||
displayName: fbUser.displayName,
|
||||
photoURL: fbUser.photoURL,
|
||||
email: fbUser.email,
|
||||
};
|
||||
needsCountry = true;
|
||||
}
|
||||
} else {
|
||||
user = null;
|
||||
userProfile = null;
|
||||
needsCountry = false;
|
||||
}
|
||||
loading = false;
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user