diff options
| author | Pinapelz <yukais@pinapelz.com> | 2026-06-02 02:12:57 -0700 |
|---|---|---|
| committer | Pinapelz <yukais@pinapelz.com> | 2026-06-02 02:13:10 -0700 |
| commit | 0335b0ad81169232a3dbb1be1341fdcfce548645 (patch) | |
| tree | 910593fa5e072ea77f594b6f10ddd96e49452446 /src/app/context/auth.tsx | |
| parent | 0d35e75edbc75f186e4a1ed52fbc3549ee9f5cd6 (diff) | |
migrate to pocketbase backend + auth/login
Diffstat (limited to 'src/app/context/auth.tsx')
| -rw-r--r-- | src/app/context/auth.tsx | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/app/context/auth.tsx b/src/app/context/auth.tsx new file mode 100644 index 0000000..f7e7cc2 --- /dev/null +++ b/src/app/context/auth.tsx @@ -0,0 +1,69 @@ +"use client"; +import { + createContext, + useCallback, + useContext, + useEffect, + useState, +} from "react"; +import type { RecordModel } from "pocketbase"; +import pb from "../lib/pocketbase"; + +interface AuthContextValue { + user: RecordModel | null; + loading: boolean; + signIn: (email: string, password: string) => Promise<void>; + signUp: (email: string, username: string, password: string, passwordConfirm: string) => Promise<void>; + signOut: () => void; +} + +const AuthContext = createContext<AuthContextValue>({ + user: null, + loading: true, + signIn: async () => {}, + signUp: async () => {}, + signOut: () => {}, +}); + +export function AuthProvider({ children }: { children: React.ReactNode }) { + const [user, setUser] = useState<RecordModel | null>(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + setUser(pb.authStore.record ?? null); + setLoading(false); + const unsub = pb.authStore.onChange(() => { + setUser(pb.authStore.record ?? null); + }); + return () => unsub(); + }, []); + + const signIn = useCallback(async (email: string, password: string) => { + await pb.collection("users").authWithPassword(email, password); + setUser(pb.authStore.record ?? null); + }, []); + + const signUp = useCallback( + async (email: string, username: string, password: string, passwordConfirm: string) => { + await pb.collection("users").create({ email, username, password, passwordConfirm }); + await pb.collection("users").authWithPassword(email, password); + setUser(pb.authStore.record ?? null); + }, + [] + ); + + const signOut = useCallback(() => { + pb.authStore.clear(); + setUser(null); + }, []); + + return ( + <AuthContext.Provider value={{ user, loading, signIn, signUp, signOut }}> + {children} + </AuthContext.Provider> + ); +} + +export function useAuth() { + return useContext(AuthContext); +} |
