chore: add firebase dependency to package.json

This commit is contained in:
Frank John Begornia
2025-11-07 17:38:13 +08:00
parent a545cbfcca
commit 50f08f8177
7 changed files with 1180 additions and 20 deletions

View File

@@ -1,29 +1,58 @@
<script setup lang="ts">
const { user, signOut, initAuth, isLoading } = useAuth()
const showLoginModal = ref(false)
// Initialize auth on component mount
onMounted(() => {
initAuth()
})
const handleSignOut = async () => {
try {
await signOut()
} catch (error) {
console.error('Sign out failed:', error)
}
}
</script>
<template>
<nav class="sticky top-0 z-30 border-b border-slate-800/60 bg-slate-950/80 backdrop-blur">
<div class="mx-auto max-w-6xl px-4 py-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between gap-6">
<p class="text-lg font-semibold text-white sm:text-xl">Slipmatz</p>
<div class="flex items-center gap-3">
<button
type="button"
class="rounded-full border border-slate-700/80 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-slate-500 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
>
Login
</button>
<button
type="button"
class="rounded-full bg-sky-500/90 px-4 py-2 text-sm font-semibold text-white transition hover:bg-sky-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
>
Register
</button>
<button
type="button"
class="rounded-full border border-slate-700/80 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-rose-500 hover:text-rose-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
>
Logout
</button>
<!-- Show user info and logout when authenticated -->
<div v-if="user && !isLoading" class="flex items-center gap-3">
<span class="text-sm text-slate-300">{{ user.email }}</span>
<button
type="button"
@click="handleSignOut"
class="rounded-full border border-slate-700/80 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-rose-500 hover:text-rose-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
>
Logout
</button>
</div>
<!-- Show login button when not authenticated -->
<div v-else-if="!isLoading" class="flex items-center gap-3">
<button
type="button"
@click="showLoginModal = true"
class="rounded-full border border-slate-700/80 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-slate-500 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
>
Login
</button>
</div>
<!-- Loading state -->
<div v-else class="flex items-center gap-3">
<div class="h-8 w-16 animate-pulse rounded bg-slate-700"></div>
</div>
</div>
</div>
</div>
<LoginModal v-model="showLoginModal" />
</nav>
</template>

View File

@@ -0,0 +1,98 @@
<script setup lang="ts">
const { signInWithEmail, signInWithGoogle, error, isLoading } = useAuth()
const isOpen = defineModel<boolean>()
const email = ref('')
const password = ref('')
const loginError = ref<string | null>(null)
const handleEmailLogin = async () => {
try {
loginError.value = null
await signInWithEmail(email.value, password.value)
isOpen.value = false
// Reset form
email.value = ''
password.value = ''
} catch (err) {
loginError.value = 'Login failed. Please check your credentials.'
}
}
const handleGoogleLogin = async () => {
try {
loginError.value = null
await signInWithGoogle()
isOpen.value = false
} catch (err) {
loginError.value = 'Google login failed. Please try again.'
}
}
</script>
<template>
<div
v-if="isOpen"
class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
@click.self="isOpen = false"
>
<div class="w-full max-w-md rounded-lg bg-slate-900 p-6 shadow-xl">
<h2 class="mb-6 text-2xl font-bold text-white">Sign In</h2>
<form @submit.prevent="handleEmailLogin" class="space-y-4">
<div>
<label class="block text-sm font-medium text-slate-300">Email</label>
<input
v-model="email"
type="email"
required
class="mt-1 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-white focus:border-sky-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-slate-300">Password</label>
<input
v-model="password"
type="password"
required
class="mt-1 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-white focus:border-sky-400 focus:outline-none"
/>
</div>
<button
type="submit"
:disabled="isLoading"
class="w-full rounded-md bg-sky-600 px-4 py-2 text-white hover:bg-sky-700 disabled:opacity-50"
>
{{ isLoading ? 'Signing in...' : 'Sign In' }}
</button>
</form>
<div class="my-4 flex items-center">
<div class="flex-1 border-t border-slate-700"></div>
<span class="px-3 text-sm text-slate-400">or</span>
<div class="flex-1 border-t border-slate-700"></div>
</div>
<button
@click="handleGoogleLogin"
:disabled="isLoading"
class="w-full rounded-md border border-slate-700 bg-slate-800 px-4 py-2 text-white hover:bg-slate-700 disabled:opacity-50"
>
Sign in with Google
</button>
<div v-if="loginError || error" class="mt-4 text-sm text-red-400">
{{ loginError || error }}
</div>
<button
@click="isOpen = false"
class="mt-4 text-sm text-slate-400 hover:text-white"
>
Cancel
</button>
</div>
</div>
</template>

167
app/composables/useAuth.ts Normal file
View File

@@ -0,0 +1,167 @@
import {
signInWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
signOut as firebaseSignOut,
onAuthStateChanged,
getAuth
} from 'firebase/auth'
import { getApps, initializeApp } from 'firebase/app'
import type { User } from 'firebase/auth'
export const useAuth = () => {
const user = ref<User | null>(null)
const isLoading = ref(true)
const error = ref<string | null>(null)
const config = useRuntimeConfig()
// Initialize Firebase if not already initialized
const initializeFirebase = () => {
if (process.client && getApps().length === 0) {
const firebaseConfig = {
apiKey: config.public.firebaseApiKey,
authDomain: config.public.firebaseAuthDomain,
projectId: config.public.firebaseProjectId,
storageBucket: config.public.firebaseStorageBucket,
messagingSenderId: config.public.firebaseMessagingSenderId,
appId: config.public.firebaseAppId
}
initializeApp(firebaseConfig)
}
}
// Get auth instance directly
const getAuthInstance = () => {
if (process.client) {
initializeFirebase()
return getAuth()
}
return null
}
// Initialize auth state listener
const initAuth = () => {
if (process.client) {
try {
const auth = getAuthInstance()
if (auth) {
onAuthStateChanged(auth, (firebaseUser) => {
user.value = firebaseUser
isLoading.value = false
})
}
} catch (err) {
console.error('Failed to initialize auth:', err)
isLoading.value = false
}
}
}
// Sign in with email and password
const signInWithEmail = async (email: string, password: string) => {
try {
error.value = null
isLoading.value = true
const auth = getAuthInstance()
if (!auth) {
throw new Error('Firebase not initialized')
}
const userCredential = await signInWithEmailAndPassword(auth, email, password)
const idToken = await userCredential.user.getIdToken()
// Send token to backend
await authenticateWithBackend(idToken)
return userCredential.user
} catch (err: any) {
error.value = err.message
throw err
} finally {
isLoading.value = false
}
}
// Sign in with Google
const signInWithGoogle = async () => {
try {
error.value = null
isLoading.value = true
const auth = getAuthInstance()
if (!auth) {
throw new Error('Firebase not initialized')
}
const provider = new GoogleAuthProvider()
const userCredential = await signInWithPopup(auth, provider)
const idToken = await userCredential.user.getIdToken()
// Send token to backend
await authenticateWithBackend(idToken)
return userCredential.user
} catch (err: any) {
error.value = err.message
throw err
} finally {
isLoading.value = false
}
}
// Authenticate with backend
const authenticateWithBackend = async (idToken: string) => {
try {
const response = await $fetch('/auth/login', {
baseURL: config.public.backendUrl,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
idToken
}
})
return response
} catch (err) {
console.error('Backend authentication failed:', err)
throw err
}
}
// Sign out
const signOut = async () => {
try {
const auth = getAuthInstance()
if (!auth) {
throw new Error('Firebase not initialized')
}
await firebaseSignOut(auth)
user.value = null
} catch (err: any) {
error.value = err.message
throw err
}
}
// Get current user's ID token
const getIdToken = async () => {
if (!user.value) return null
return await user.value.getIdToken()
}
return {
user: readonly(user),
isLoading: readonly(isLoading),
error: readonly(error),
initAuth,
signInWithEmail,
signInWithGoogle,
signOut,
getIdToken
}
}