import { useState, type FormEvent } from "react"; import { api, type Me } from "../api"; import { useAuth } from "../auth"; import { ErrorNote, PageHeader } from "../ui/Bits"; import { Icon } from "../ui/Icon"; import { useUi } from "../ui/Ui"; import { ThemeButton } from "../ui/ThemeButton"; export function ChangeCredentials({ forced = false }: { forced?: boolean }) { const { me, setMe, logout } = useAuth(); const ui = useUi(); const needUsername = !!me?.must_change_username; const [username, setUsername] = useState(needUsername ? "" : me?.username ?? ""); const [current, setCurrent] = useState(""); const [password, setPassword] = useState(""); const [repeat, setRepeat] = useState(""); const [error, setError] = useState(""); const mismatch = repeat.length > 0 && password !== repeat; const submit = async (e: FormEvent) => { e.preventDefault(); setError(""); if (password !== repeat) { setError("Пароли не совпадают"); return; } try { const updated = await api.post("/api/auth/change-credentials", { current_password: current, new_password: password, new_username: username.trim() || null, }); setMe(updated); if (!forced) ui.toast("Данные сохранены", "ok"); setCurrent(""); setPassword(""); setRepeat(""); } catch (err) { setError((err as Error).message); } }; const form = (
{forced ? (
Смена данных

{needUsername ? "Это первый вход администратора. Задайте собственный логин и пароль." : "Пароль был выдан администратором. Задайте свой пароль."}

) : null} {error && {error}} {forced && }
); if (forced) { return (
{form}
); } return (
Вы вошли как {me?.username} · {me?.role.name}} /> {form}
); }