diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/app/(auth)/_layout.tsx | 27 | ||||
| -rw-r--r-- | src/app/(auth)/login.tsx | 80 | ||||
| -rw-r--r-- | src/app/(auth)/register.tsx | 97 | ||||
| -rw-r--r-- | src/app/(auth)/welcome.tsx | 58 | ||||
| -rw-r--r-- | src/app/(protected)/_layout.tsx | 27 | ||||
| -rw-r--r-- | src/app/(protected)/home.tsx | 50 | ||||
| -rw-r--r-- | src/app/_layout.tsx | 62 | ||||
| -rw-r--r-- | src/app/index.tsx | 54 | ||||
| -rw-r--r-- | src/features/auth/hooks/useLogin.ts | 38 | ||||
| -rw-r--r-- | src/features/auth/hooks/useLogin.ts~ | 0 | ||||
| -rw-r--r-- | src/features/auth/hooks/useRegister.ts | 42 | ||||
| -rw-r--r-- | src/features/auth/hooks/useRegister.ts~ | 0 | ||||
| -rw-r--r-- | src/features/auth/services/authService.ts | 48 | ||||
| -rw-r--r-- | src/features/auth/services/authService.ts~ | 0 | ||||
| -rw-r--r-- | src/providers/AppProviders.tsx | 10 | ||||
| -rw-r--r-- | src/providers/AppProviders.tsx~ | 0 | ||||
| -rw-r--r-- | src/providers/AuthProvider.tsx | 51 | ||||
| -rw-r--r-- | src/providers/AuthProvider.tsx~ | 0 | ||||
| -rw-r--r-- | src/shared/lib/firebase/config.ts | 27 | ||||
| -rw-r--r-- | src/shared/lib/firebase/config.ts~ | 0 |
20 files changed, 583 insertions, 88 deletions
diff --git a/src/app/(auth)/_layout.tsx b/src/app/(auth)/_layout.tsx index e69de29..1fa69af 100644 --- a/src/app/(auth)/_layout.tsx +++ b/src/app/(auth)/_layout.tsx @@ -0,0 +1,27 @@ +import { Stack, Redirect } from 'expo-router'; +import { useAuthSession } from '@/providers/AuthProvider'; +import { ActivityIndicator, View } from 'react-native'; + +export default function AuthLayout() { + const { user, loading } = useAuthSession(); + + if (loading) { + return ( + <View + style={{ + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }} + > + <ActivityIndicator size="large" /> + </View> + ); + } + + if (user) { + return <Redirect href="/(protected)/home" />; + } + + return <Stack screenOptions={{ headerShown: false }} />; +} diff --git a/src/app/(auth)/login.tsx b/src/app/(auth)/login.tsx index e69de29..5664bbf 100644 --- a/src/app/(auth)/login.tsx +++ b/src/app/(auth)/login.tsx @@ -0,0 +1,80 @@ +import { Link } from 'expo-router'; +import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { useLogin } from '@/features/auth/hooks/useLogin'; + +export default function LoginScreen() { + const { email, password, setEmail, setPassword, submit, isSubmitting, error } = useLogin(); + + return ( + <View style={styles.container}> + <Text style={styles.title}>Iniciar sesión</Text> + + <TextInput + style={styles.input} + placeholder="Correo electrónico" + autoCapitalize="none" + keyboardType="email-address" + value={email} + onChangeText={setEmail} + /> + + <TextInput + style={styles.input} + placeholder="Contraseña" + secureTextEntry + value={password} + onChangeText={setPassword} + /> + + {error ? <Text style={styles.error}>{error}</Text> : null} + + <Pressable style={styles.button} onPress={submit} disabled={isSubmitting}> + <Text style={styles.buttonText}> + {isSubmitting ? 'Entrando...' : 'Entrar'} + </Text> + </Pressable> + + <Link href="/(auth)/register" style={styles.link}> + ¿No tienes cuenta? Regístrate + </Link> + </View> + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + padding: 24, + gap: 12, + }, + title: { + fontSize: 28, + fontWeight: '700', + marginBottom: 16, + }, + input: { + borderWidth: 1, + borderColor: '#ccc', + borderRadius: 10, + paddingHorizontal: 14, + paddingVertical: 12, + }, + button: { + backgroundColor: '#1f6feb', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + marginTop: 8, + }, + buttonText: { + color: '#fff', + fontWeight: '600', + }, + error: { + color: 'red', + }, + link: { + marginTop: 12, + }, +}); diff --git a/src/app/(auth)/register.tsx b/src/app/(auth)/register.tsx index e69de29..1a39a78 100644 --- a/src/app/(auth)/register.tsx +++ b/src/app/(auth)/register.tsx @@ -0,0 +1,97 @@ +import { Link } from 'expo-router'; +import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { useRegister } from '@/features/auth/hooks/useRegister'; + +export default function RegisterScreen() { + const { + displayName, + email, + password, + setDisplayName, + setEmail, + setPassword, + submit, + isSubmitting, + error, + } = useRegister(); + + return ( + <View style={styles.container}> + <Text style={styles.title}>Registrarse</Text> + + <TextInput + style={styles.input} + placeholder="Nombre" + value={displayName} + onChangeText={setDisplayName} + /> + + <TextInput + style={styles.input} + placeholder="Correo electrónico" + autoCapitalize="none" + keyboardType="email-address" + value={email} + onChangeText={setEmail} + /> + + <TextInput + style={styles.input} + placeholder="Contraseña" + secureTextEntry + value={password} + onChangeText={setPassword} + /> + + {error ? <Text style={styles.error}>{error}</Text> : null} + + <Pressable style={styles.button} onPress={submit} disabled={isSubmitting}> + <Text style={styles.buttonText}> + {isSubmitting ? 'Registrando...' : 'Crear cuenta'} + </Text> + </Pressable> + + <Link href="/(auth)/login" style={styles.link}> + ¿Ya tienes cuenta? Inicia sesión + </Link> + </View> + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + padding: 24, + gap: 12, + }, + title: { + fontSize: 28, + fontWeight: '700', + marginBottom: 16, + }, + input: { + borderWidth: 1, + borderColor: '#ccc', + borderRadius: 10, + paddingHorizontal: 14, + paddingVertical: 12, + }, + button: { + backgroundColor: '#1f6feb', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + marginTop: 8, + }, + buttonText: { + color: '#fff', + fontWeight: '600', + }, + error: { + color: 'red', + }, + link: { + marginTop: 12, + }, +}); diff --git a/src/app/(auth)/welcome.tsx b/src/app/(auth)/welcome.tsx index e69de29..9b00154 100644 --- a/src/app/(auth)/welcome.tsx +++ b/src/app/(auth)/welcome.tsx @@ -0,0 +1,58 @@ +import { Link } from 'expo-router'; +import { StyleSheet, Text, View, Pressable } from 'react-native'; + +export default function WelcomeScreen() { + return ( + <View style={styles.container}> + <Text style={styles.title}>App Oficina</Text> + <Text style={styles.subtitle}>Reserva de espacios de trabajo</Text> + + <Link href="/(auth)/login" asChild> + <Pressable style={styles.button}> + <Text style={styles.buttonText}>Iniciar sesión</Text> + </Pressable> + </Link> + + <Link href="/(auth)/register" asChild> + <Pressable style={styles.buttonSecondary}> + <Text style={styles.buttonText}>Registrarse</Text> + </Pressable> + </Link> + </View> + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + padding: 24, + gap: 16, + }, + title: { + fontSize: 32, + fontWeight: '700', + textAlign: 'center', + }, + subtitle: { + fontSize: 16, + textAlign: 'center', + marginBottom: 24, + }, + button: { + backgroundColor: '#1f6feb', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + }, + buttonSecondary: { + backgroundColor: '#444', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + }, + buttonText: { + color: '#fff', + fontWeight: '600', + }, +}); diff --git a/src/app/(protected)/_layout.tsx b/src/app/(protected)/_layout.tsx index e69de29..ffd3d5d 100644 --- a/src/app/(protected)/_layout.tsx +++ b/src/app/(protected)/_layout.tsx @@ -0,0 +1,27 @@ +import { Stack, Redirect } from 'expo-router'; +import { useAuthSession } from '@/providers/AuthProvider'; +import { ActivityIndicator, View } from 'react-native'; + +export default function ProtectedLayout() { + const { user, loading } = useAuthSession(); + + if (loading) { + return ( + <View + style={{ + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }} + > + <ActivityIndicator size="large" /> + </View> + ); + } + + if (!user) { + return <Redirect href="/(auth)/welcome" />; + } + + return <Stack screenOptions={{ headerShown: false }} />; +} diff --git a/src/app/(protected)/home.tsx b/src/app/(protected)/home.tsx index e69de29..76a5bda 100644 --- a/src/app/(protected)/home.tsx +++ b/src/app/(protected)/home.tsx @@ -0,0 +1,50 @@ +import { Pressable, StyleSheet, Text, View } from 'react-native'; +import { useAuthSession } from '@/providers/AuthProvider'; + +export default function HomeScreen() { + const { user, logout } = useAuthSession(); + + return ( + <View style={styles.container}> + <Text style={styles.title}>Inicio</Text> + <Text style={styles.subtitle}> + Bienvenido{user?.displayName ? `, ${user.displayName}` : ''} + </Text> + <Text style={styles.email}>{user?.email}</Text> + + <Pressable style={styles.button} onPress={logout}> + <Text style={styles.buttonText}>Cerrar sesión</Text> + </Pressable> + </View> + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + padding: 24, + gap: 12, + }, + title: { + fontSize: 28, + fontWeight: '700', + }, + subtitle: { + fontSize: 18, + }, + email: { + color: '#555', + marginBottom: 20, + }, + button: { + backgroundColor: '#c62828', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + }, + buttonText: { + color: '#fff', + fontWeight: '600', + }, +}); diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx index e2eb936..710f3f2 100644 --- a/src/app/_layout.tsx +++ b/src/app/_layout.tsx @@ -1,58 +1,10 @@ -import { Slot, Stack } from "expo-router"; -import React, { Suspense } from 'react' -import AppContextProvider from "../context/AppContextProvider"; -import { ActivityIndicator, Text, View } from "react-native"; -import { openDatabaseSync, SQLiteProvider } from "expo-sqlite"; -import { drizzle } from "drizzle-orm/expo-sqlite"; -import { sql } from 'drizzle-orm'; -import { migrate, useMigrations } from "drizzle-orm/expo-sqlite/migrator"; -import migrations from "../../drizzle/migrations"; -type Props = {} -export const DATABASE_NAME = 'prueba3Drizzle'; -const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); -function LoadingScreen() { +import { Stack } from 'expo-router'; +import { AppProviders } from '@/providers/AppProviders'; + +export default function RootLayout() { return ( - <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> - <ActivityIndicator size="large" color="#0000ff" /> - <Text >Cargando la app...</Text> - </View> + <AppProviders> + <Stack screenOptions={{ headerShown: false }} /> + </AppProviders> ); } -const RootLayout = (props: Props) => { - return ( - <AppContextProvider> - <Suspense fallback={<LoadingScreen />}> - <SQLiteProvider - databaseName={DATABASE_NAME} - options={{ enableChangeListener: true }} - useSuspense - onInit={async (database) => { - try { - console.log("Simulando carga lenta..."); - await sleep(2000); // 2 segundos retraso - const db = drizzle(database); - await migrate(db, migrations); - console.log("Migration success"); - - // Activa FK aquí (después de migraciones) - await db.run(sql`PRAGMA foreign_keys = ON`); - console.log("Foreign keys enabled"); - - } catch (error) { - console.error("Migration error", error); - } - }} - > - <Stack - screenOptions={{ headerShown: false }} - - /> - - </SQLiteProvider> - </Suspense> - </AppContextProvider> - - ) -} - -export default RootLayout;
\ No newline at end of file diff --git a/src/app/index.tsx b/src/app/index.tsx index cf5f7c1..eacde3c 100644 --- a/src/app/index.tsx +++ b/src/app/index.tsx @@ -1,39 +1,27 @@ -import { router } from "expo-router"; -import { Button, Text, View } from "react-native"; -import { SafeAreaView } from "react-native-safe-area-context"; +import { Redirect } from 'expo-router'; +import { ActivityIndicator, View } from 'react-native'; +import { useAuthSession } from '@/providers/AuthProvider'; -export default function Index() { +export default function IndexPage() { + const { user, loading } = useAuthSession(); - - function navegarGuardarPersona(){ - console.log("ir a pantalla") - router.push({ - pathname: "/GuardarPersona", - //params: - }) + if (loading) { + return ( + <View + style={{ + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }} + > + <ActivityIndicator size="large" /> + </View> + ); } + if (user) { + return <Redirect href="/(protected)/home" />; + } - function navegarGuardarProducto(){ - console.log("ir a pantalla") - router.push({ - pathname: "/GuardarProducto", - //params: - }) - } - return ( - <SafeAreaView - style={{ - flex: 1, - justifyContent: "center", - alignItems: "center", - }} - > - - <Button title="crear usuario " testID="btn-crear-usuario" color={"green"} onPress={()=> navegarGuardarPersona()} /> - {/* - <Button title="crear categorias y productos " testID="btn-crear-categoria-producto" color={"blue"} onPress={()=> navegarGuardarProducto()} /> - */} - </SafeAreaView> - ); + return <Redirect href="/(auth)/welcome" />; } diff --git a/src/features/auth/hooks/useLogin.ts b/src/features/auth/hooks/useLogin.ts new file mode 100644 index 0000000..5e4c881 --- /dev/null +++ b/src/features/auth/hooks/useLogin.ts @@ -0,0 +1,38 @@ +import { useState } from 'react'; +import { router } from 'expo-router'; +import { authService } from '@/features/auth/services/authService'; + +export function useLogin() { + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState<string | null>(null); + + const submit = async () => { + try { + setError(null); + setIsSubmitting(true); + + await authService.login({ + email: email.trim(), + password, + }); + + router.replace('/(protected)/home'); + } catch (err: any) { + setError(err?.message ?? 'No se pudo iniciar sesión'); + } finally { + setIsSubmitting(false); + } + }; + + return { + email, + password, + isSubmitting, + error, + setEmail, + setPassword, + submit, + }; +} diff --git a/src/features/auth/hooks/useLogin.ts~ b/src/features/auth/hooks/useLogin.ts~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/features/auth/hooks/useLogin.ts~ diff --git a/src/features/auth/hooks/useRegister.ts b/src/features/auth/hooks/useRegister.ts new file mode 100644 index 0000000..7b93e92 --- /dev/null +++ b/src/features/auth/hooks/useRegister.ts @@ -0,0 +1,42 @@ +import { useState } from 'react'; +import { router } from 'expo-router'; +import { authService } from '@/features/auth/services/authService'; + +export function useRegister() { + const [displayName, setDisplayName] = useState(''); + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState<string | null>(null); + + const submit = async () => { + try { + setError(null); + setIsSubmitting(true); + + await authService.register({ + displayName: displayName.trim(), + email: email.trim(), + password, + }); + + router.replace('/(protected)/home'); + } catch (err: any) { + setError(err?.message ?? 'No se pudo registrar el usuario'); + } finally { + setIsSubmitting(false); + } + }; + + return { + displayName, + email, + password, + isSubmitting, + error, + setDisplayName, + setEmail, + setPassword, + submit, + }; +} diff --git a/src/features/auth/hooks/useRegister.ts~ b/src/features/auth/hooks/useRegister.ts~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/features/auth/hooks/useRegister.ts~ diff --git a/src/features/auth/services/authService.ts b/src/features/auth/services/authService.ts new file mode 100644 index 0000000..54ff58f --- /dev/null +++ b/src/features/auth/services/authService.ts @@ -0,0 +1,48 @@ +import { + createUserWithEmailAndPassword, + signInWithEmailAndPassword, + signOut, + updateProfile, + User, +} from 'firebase/auth'; +import { doc, serverTimestamp, setDoc } from 'firebase/firestore'; +import { auth, db } from '@/shared/lib/firebase/config'; + +type RegisterParams = { + email: string; + password: string; + displayName: string; +}; + +type LoginParams = { + email: string; + password: string; +}; + +export const authService = { + async register({ email, password, displayName }: RegisterParams): Promise<User> { + const userCredential = await createUserWithEmailAndPassword(auth, email, password); + const user = userCredential.user; + + if (displayName.trim()) { + await updateProfile(user, { displayName }); + } + + await setDoc(doc(db, 'users', user.uid), { + email: user.email, + displayName: displayName.trim(), + createdAt: serverTimestamp(), + }); + + return user; + }, + + async login({ email, password }: LoginParams): Promise<User> { + const userCredential = await signInWithEmailAndPassword(auth, email, password); + return userCredential.user; + }, + + async logout(): Promise<void> { + await signOut(auth); + }, +}; diff --git a/src/features/auth/services/authService.ts~ b/src/features/auth/services/authService.ts~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/features/auth/services/authService.ts~ diff --git a/src/providers/AppProviders.tsx b/src/providers/AppProviders.tsx new file mode 100644 index 0000000..5246a42 --- /dev/null +++ b/src/providers/AppProviders.tsx @@ -0,0 +1,10 @@ +import React from 'react'; +import { AuthProvider } from './AuthProvider'; + +type AppProvidersProps = { + children: React.ReactNode; +}; + +export function AppProviders({ children }: AppProvidersProps) { + return <AuthProvider>{children}</AuthProvider>; +} diff --git a/src/providers/AppProviders.tsx~ b/src/providers/AppProviders.tsx~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/providers/AppProviders.tsx~ diff --git a/src/providers/AuthProvider.tsx b/src/providers/AuthProvider.tsx new file mode 100644 index 0000000..edcc89c --- /dev/null +++ b/src/providers/AuthProvider.tsx @@ -0,0 +1,51 @@ +import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'; +import { onAuthStateChanged, User } from 'firebase/auth'; +import { auth } from '@/shared/lib/firebase/config'; +import { authService } from '@/features/auth/services/authService'; + +type AuthContextValue = { + user: User | null; + loading: boolean; + logout: () => Promise<void>; +}; + +const AuthContext = createContext<AuthContextValue | undefined>(undefined); + +type AuthProviderProps = { + children: React.ReactNode; +}; + +export function AuthProvider({ children }: AuthProviderProps) { + const [user, setUser] = useState<User | null>(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const unsubscribe = onAuthStateChanged(auth, (nextUser) => { + setUser(nextUser); + setLoading(false); + }); + + return unsubscribe; + }, []); + + const value = useMemo<AuthContextValue>( + () => ({ + user, + loading, + logout: authService.logout, + }), + [user, loading] + ); + + return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; +} + +export function useAuthSession() { + const context = useContext(AuthContext); + + if (!context) { + throw new Error('useAuthSession must be used within AuthProvider'); + } + + return context; +} diff --git a/src/providers/AuthProvider.tsx~ b/src/providers/AuthProvider.tsx~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/providers/AuthProvider.tsx~ diff --git a/src/shared/lib/firebase/config.ts b/src/shared/lib/firebase/config.ts new file mode 100644 index 0000000..8bb5e7c --- /dev/null +++ b/src/shared/lib/firebase/config.ts @@ -0,0 +1,27 @@ +// src/shared/lib/firebase/config.ts +import { initializeApp, getApps, getApp } from 'firebase/app'; +import { + initializeAuth, + getReactNativePersistence, +} from 'firebase/auth'; +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { getFirestore } from 'firebase/firestore'; + +const firebaseConfig = { + apiKey: 'AIzaSyANl7xew69Y39IH1PrRL6rBbWs6qDgz7qM', + authDomain: 'appoficinas-f8c8d.firebaseapp.com', + projectId: 'appoficinas-f8c8d', + storageBucket: 'appoficinas-f8c8d.firebasestorage.app', + messagingSenderId: '734167380764', + appId: '1:734167380764:web:44ca60953f0624edc300d9', +}; + +const app = getApps().length ? getApp() : initializeApp(firebaseConfig); + +export const auth = initializeAuth(app, { + persistence: getReactNativePersistence(AsyncStorage), +}); + +export const db = getFirestore(app); + +export default app; diff --git a/src/shared/lib/firebase/config.ts~ b/src/shared/lib/firebase/config.ts~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/shared/lib/firebase/config.ts~ |