aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/context/auth.tsx
blob: f7e7cc2cd37fe5a9f5fc305c4eec9cb987924a8f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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);
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage