|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { usePopup } from "@/components/admin/connectors/Popup"; |
| 4 | +import { basicLogin, basicSignup } from "@/lib/user"; |
| 5 | +import { useRouter } from "next/navigation"; |
| 6 | +import { useEffect } from "react"; |
| 7 | +import { Spinner } from "@/components/Spinner"; |
| 8 | + |
| 9 | +export function HeaderLoginLoading({ |
| 10 | + user, groups |
| 11 | +}: { |
| 12 | + user: string; |
| 13 | + groups: string[]; |
| 14 | +}) { |
| 15 | + console.log(user, groups); |
| 16 | + |
| 17 | + const router = useRouter(); |
| 18 | + const { popup, setPopup } = usePopup(); |
| 19 | + const email = `${user}@default.com`; |
| 20 | + const password = `not-used-${window.crypto.randomUUID()}` |
| 21 | + const role = groups.includes("/admins") ? "admin" : "basic" |
| 22 | + |
| 23 | + async function tryLogin() { |
| 24 | + // TODO: Update user role here if groups have changed? |
| 25 | + |
| 26 | + // TODO: Use other API endpoints here to update user roles |
| 27 | + // and check for existence instead of attempting sign up |
| 28 | + // Endpoints: |
| 29 | + // - /api/manage/users |
| 30 | + // - /api/manage/promote-user-to-admin (auth required) |
| 31 | + // - /api/manage/demote-admin-to-user (auth required) |
| 32 | + |
| 33 | + // signup every time. |
| 34 | + // Ensure user exists |
| 35 | + const response = await basicSignup(email, password, role); |
| 36 | + if (!response.ok) { |
| 37 | + const errorDetail = (await response.json()).detail; |
| 38 | + |
| 39 | + if (errorDetail !== "REGISTER_USER_ALREADY_EXISTS") { |
| 40 | + setPopup({ |
| 41 | + type: "error", |
| 42 | + message: `Failed to sign up - ${errorDetail}`, |
| 43 | + }); |
| 44 | + } |
| 45 | + } |
| 46 | + // Login as user |
| 47 | + const loginResponse = await basicLogin(email, password); |
| 48 | + if (loginResponse.ok) { |
| 49 | + router.push("/"); |
| 50 | + } else { |
| 51 | + const errorDetail = (await loginResponse.json()).detail; |
| 52 | + setPopup({ |
| 53 | + type: "error", |
| 54 | + message: `Failed to login - ${errorDetail}`, |
| 55 | + }); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + useEffect(() => { |
| 60 | + tryLogin() |
| 61 | + }, []); |
| 62 | + |
| 63 | + return ( |
| 64 | + <> |
| 65 | + {popup} |
| 66 | + <Spinner /> |
| 67 | + </> |
| 68 | + ); |
| 69 | +} |
0 commit comments