Files
Emailsorter/client/src/context/AuthContext.tsx
ANDJ abf761db07 Email Sorter Beta
Ich habe soweit automatisiert the Emails sortieren aber ich muss noch schauen was es fur bugs es gibt wenn die app online  ist deswegen wurde ich mit diesen Commit die website veroffentlichen obwohjl es sein konnte  das es noch nicht fertig ist und verkaufs bereit
2026-01-22 19:32:12 +01:00

75 lines
1.8 KiB
TypeScript

import React, { createContext, useContext, useEffect, useState } from 'react'
import { auth } from '@/lib/appwrite'
import type { Models } from 'appwrite'
interface AuthContextType {
user: Models.User<Models.Preferences> | null
loading: boolean
login: (email: string, password: string) => Promise<void>
register: (email: string, password: string, name?: string) => Promise<void>
logout: () => Promise<void>
refreshUser: () => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<Models.User<Models.Preferences> | null>(null)
const [loading, setLoading] = useState(true)
const refreshUser = async () => {
try {
const currentUser = await auth.getCurrentUser()
setUser(currentUser)
} catch {
setUser(null)
}
}
useEffect(() => {
const init = async () => {
await refreshUser()
setLoading(false)
}
init()
}, [])
const login = async (email: string, password: string) => {
await auth.login(email, password)
await refreshUser()
}
const register = async (email: string, password: string, name?: string) => {
await auth.register(email, password, name)
await refreshUser()
}
const logout = async () => {
await auth.logout()
setUser(null)
}
return (
<AuthContext.Provider
value={{
user,
loading,
login,
register,
logout,
refreshUser,
}}
>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}