| 1 | "use client"; |
| 2 | |
| 3 | import { useContext, useState } from "react"; |
| 4 | import { UserContext } from "@/lib/current-user-context"; |
| 5 | import { useLogger } from "@/lib/logger"; |
| 6 | import { CurrentUser, db } from "@/lib/db"; |
| 7 | import { invoke } from "@tauri-apps/api/tauri"; |
| 8 | import { TAURI_ACCOUNT_LOGOUT } from "@/lib/tauri-handler"; |
| 9 | import { useRouter } from "next/navigation"; |
| 10 | import { Button } from "@/components/button"; |
| 11 | |
| 12 | enum State { |
| 13 | LOADING, |
| 14 | LOADED, |
| 15 | ERROR, |
| 16 | } |
| 17 | |
| 18 | export default function Page() { |
| 19 | const [state, setState] = useState(State.LOADED); |
| 20 | const log = useLogger("Logout/Page"); |
| 21 | const router = useRouter(); |
| 22 | const userContext = useContext(UserContext); |
| 23 | |
| 24 | const logout = async (update: (user: CurrentUser | null) => void) => { |
| 25 | try { |
| 26 | setState(State.LOADING); |
| 27 | log.debug("userContext", userContext); |
| 28 | const payload = { |
| 29 | accessToken: userContext.user?.accessToken, |
| 30 | }; |
| 31 | log.debug("Logging out", payload); |
| 32 | const res = await invoke(TAURI_ACCOUNT_LOGOUT, payload); |
| 33 | log.debug(res); |
| 34 | update(null); |
| 35 | db.currentUser.clear(); |
| 36 | router.push("/"); |
| 37 | } catch (error) { |
| 38 | log.error(error); |
| 39 | setState(State.ERROR); |
| 40 | } |
| 41 | }; |
| 42 | |
| 43 | const buttonText = state === State.LOADING ? "Logging out..." : "Logout"; |
| 44 | |
| 45 | return ( |
| 46 | <div className="prose prose-sm prose-invert max-w-none"> |
| 47 | <UserContext.Consumer> |
| 48 | {({ updateUser: update }) => ( |
| 49 | <div className="grid grid-cols-1 gap-6 lg:grid-cols-3"> |
| 50 | <Button |
| 51 | onClick={() => logout(update)} |
| 52 | variant={"outline"} |
| 53 | size={"lg"} |
| 54 | > |
| 55 | {buttonText} |
| 56 | </Button> |
| 57 | <div>This will remove your session and caches.</div> |
| 58 | </div> |
| 59 | )} |
| 60 | </UserContext.Consumer> |
| 61 | </div> |
| 62 | ); |
| 63 | } |