/*
This file is part of GNU Taler
(C) 2022-2024 Taler Systems S.A.
GNU Taler is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
GNU Taler; see the file COPYING. If not, see
*/
import {
HttpStatusCode
} from "@gnu-taler/taler-util";
import {
Button,
LocalNotificationBanner,
ShowInputErrorLabel,
useLocalNotificationHandler,
useTranslationContext
} from "@gnu-taler/web-util/browser";
import { VNode, h } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
import { useBankCoreApiContext } from "../context/config.js";
import { useSessionState } from "../hooks/session.js";
import { RouteDefinition } from "../route.js";
import { undefinedIfEmpty } from "../utils.js";
import { doAutoFocus } from "./PaytoWireTransferForm.js";
/**
* Collect and submit login data.
*/
export function LoginForm({
currentUser,
fixedUser,
routeRegister,
}: {
fixedUser?: boolean;
currentUser?: string;
routeRegister?: RouteDefinition;
}): VNode {
const session = useSessionState();
const sessionUser =
session.state.status !== "loggedOut" ? session.state.username : undefined;
const [username, setUsername] = useState(
currentUser ?? sessionUser,
);
const [password, setPassword] = useState();
const { i18n } = useTranslationContext();
const { authenticator } = useBankCoreApiContext();
const [notification, withErrorHandler] = useLocalNotificationHandler();
const { config } = useBankCoreApiContext();
const ref = useRef(null);
useEffect(function focusInput() {
ref.current?.focus();
}, []);
const errors =
undefinedIfEmpty({
username: !username
? i18n.str`Missing username`
: // : !USERNAME_REGEX.test(username)
// ? i18n.str`Use letters and numbers only, and start with a lowercase letter`
undefined,
password: !password ? i18n.str`Missing password` : undefined,
});
async function doLogout() {
session.logOut();
}
const loginHandler = !username || !password ? undefined : withErrorHandler(
async () => authenticator(username)
.createAccessToken(password, {
// scope: "readwrite" as "write", // FIX: different than merchant
scope: "readwrite",
duration: { d_us: "forever" },
refreshable: true,
}),
(result) => {
session.logIn({ username, token: result.body.access_token })
},
(fail) => {
switch (fail.case) {
case HttpStatusCode.Unauthorized: return i18n.str`Wrong credentials for "${username}"`;
case HttpStatusCode.NotFound: return i18n.str`Account not found`;
}
}
)
return (