added full keycloak support. Partial Quantum backend support, Moved to

.env for config

- removed the globalVars variable for a lack of need
- changed the documentation page for test of multilevel navigation
- added machines page to route
- cleaned up dependencies for build
- changed config to split imports
This commit is contained in:
2026-04-26 16:25:02 +03:00
parent 8e78b8cb47
commit 8449da8373
33 changed files with 863 additions and 417 deletions

View File

@@ -1,19 +1,20 @@
import axios, { AxiosError } from "axios";
import type { ConvertSchema } from "Types/ApiCalls/ConvertBackendCallsTypes";
const openbableBackendRoot = "http://localhost:1654";
export async function ConvertMoleculeToStandart(
data: ConvertSchema,
): Promise<string | AxiosError> {
try {
const response = await axios.post(openbableBackendRoot + "/convert", {
text: data.inputText,
format: data.inputFormat,
convert_3d: data.make_3d,
add_hydrogen: data.add_h,
optimize_geometry: data.optimize,
});
const response = await axios.post(
import.meta.env.VITE_MOLECULAR_BACKEND_URL + "/convert",
{
text: data.inputText,
format: data.inputFormat,
convert_3d: data.make_3d,
add_hydrogen: data.add_h,
optimize_geometry: data.optimize,
},
);
// Response from the FastAPI JSONResponse
return response.data.molfile;
@@ -32,7 +33,9 @@ export async function GetInFormats(): Promise<
{ [key: string]: string } | AxiosError
> {
try {
const response = await axios.get(openbableBackendRoot + "/informats");
const response = await axios.get(
import.meta.env.VITE_MOLECULAR_BACKEND_URL + "/informats",
);
return response.data;
} catch (error) {
//Error handling

View File

@@ -1,28 +1,97 @@
import axios from "axios";
import { keycloakURI } from "GlobalVars";
import Keycloak from "keycloak-js";
import Keycloak, { type KeycloakProfile } from "keycloak-js";
import { routes } from "Routes/Routes";
const keycloak = new Keycloak({
url: keycloakURI,
realm: "dev-realm",
url: import.meta.env.VITE_KEYCLOAK_URL
? import.meta.env.VITE_KEYCLOAK_URL
: "",
realm: "quant_sim-realm",
clientId: "react-frontend",
});
const api = axios.create({
baseURL: `${keycloak.authServerUrl}/realms/${keycloak.realm}`,
});
export default keycloak;
export async function getProfile(keycloak: Keycloak) {
return keycloak.loadUserProfile();
}
export const handleSubmit = async (profile) => {
export const updateUserData = async (
profile: KeycloakProfile,
): Promise<KeycloakProfile | undefined> => {
try {
await api.put("/account", profile);
alert("Profile updated!");
await keycloak.updateToken(30);
const response = await axios.post(
`${keycloak.authServerUrl}/realms/${keycloak.realm}/account/`,
{
firstName: profile.firstName,
lastName: profile.lastName,
email: profile.email,
username: profile.username,
attributes: profile.attributes || {},
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${keycloak.token}`,
},
withCredentials: true, // Important: allows credentials in CORS
},
);
if (response.status === 204) {
// Refresh the local profile after successful update
const updatedProfile = await keycloak.loadUserProfile();
return updatedProfile;
}
} catch (err) {
console.error(err);
}
};
export const updatePasswordWithRedirect = async (
successRedirectUrl?: string,
) => {
try {
await keycloak.updateToken(30);
// Trigger the UPDATE_PASSWORD required action
// This will redirect the user to Keycloak's password change page
return keycloak.login({
action: "UPDATE_PASSWORD",
redirectUri:
successRedirectUrl ||
window.location.origin +
"/" +
import.meta.env.VITE_BASE_PATH +
"/" +
routes.SettingsPage.path +
"?password_updated=true",
// Optional: Force re-authentication
prompt: "login",
});
} catch (error) {
console.error("Failed to initiate password update:", error);
throw error;
}
};
export const SendEmailVerification = async () => {
try {
await keycloak.updateToken(30);
// Trigger the UPDATE_PASSWORD required action
// This will redirect the user to Keycloak's password change page
return keycloak.login({
action: "VERIFY_EMAIL",
redirectUri:
window.location.origin +
import.meta.env.VITE_BASE_PATH +
"/" +
routes.SettingsPage.path +
"?email_sent=true",
});
} catch (error) {
console.error("Failed to initiate password update:", error);
throw error;
}
};

View File

@@ -0,0 +1,52 @@
import keycloak from "Api/Keycloak/Keycloak";
import axios from "axios";
import type { UserData } from "Types/User/User";
export const GetCurrentUserInfo = async (): Promise<UserData | undefined> => {
try {
// Trigger the UPDATE_PASSWORD required action
// This will redirect the user to Keycloak's password change page
const response = await axios.get(
`${import.meta.env.VITE_QUANTUM_BACKEND_URL}/user`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${keycloak.token}`,
},
withCredentials: true, // Important: allows credentials in CORS
},
);
if (response.status === 200) {
return response.data;
}
} catch (error) {
console.error("Error Getting User Data", error);
throw error;
}
};
export const UpdateCurrentUserInfo = async (
profile_picture_path: string,
): Promise<UserData | undefined> => {
try {
// Trigger the UPDATE_PASSWORD required action
// This will redirect the user to Keycloak's password change page
const response = await axios.put(
`${import.meta.env.VITE_QUANTUM_BACKEND_URL}/user`,
{ profile_picture_path: profile_picture_path },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${keycloak.token}`,
},
withCredentials: true, // Important: allows credentials in CORS
},
);
if (response.status === 200) {
return response.data;
}
} catch (error) {
console.error("Error Getting User Data", error);
throw error;
}
};

View File

@@ -7,27 +7,17 @@ import "@mantine/notifications/styles.css";
import "@mantine/core/styles.css";
import { Notifications } from "@mantine/notifications";
import { useLayoutStore } from "Stores/LayoutStore";
import {
defaultAnimationDuration,
headerHeight,
sideMenuWidth,
} from "GlobalVars";
import Sidebar from "Components/Layout/Sidebar/Sidebar";
import { Outlet, useLocation } from "react-router";
import { Helmet } from "react-helmet";
import { useEffect } from "react";
import { useMediaQuery } from "@mantine/hooks";
import BreadCrumbs from "Routes/Breadcrumbs/Breadcrumbs";
import keycloak, { getProfile } from "Api/Keycloak/Keycloak";
import keycloak from "Api/Keycloak/Keycloak";
import { AuthenticationStore } from "Stores/AuthenticationStore";
import type { KeycloakProfile } from "keycloak-js";
import { useNavigate } from "react-router";
function App() {
const { is_navbar_open, set_navbar_open } = useLayoutStore();
const { set_token, set_profile } = AuthenticationStore();
const navigate = useNavigate();
const { set_token } = AuthenticationStore();
const theme = useMantineTheme();
const location = useLocation();
@@ -70,9 +60,9 @@ function App() {
<Notifications />
<AppShell
header={{ height: headerHeight }}
header={{ height: 50 }}
aside={{
width: sideMenuWidth,
width: 280,
breakpoint: "sm",
collapsed: {
desktop: !is_navbar_open,
@@ -80,7 +70,7 @@ function App() {
},
}}
padding="md"
transitionDuration={defaultAnimationDuration}
transitionDuration={100}
>
<AppShell.Header id="Header" zIndex={1000}>
<Header />

View File

@@ -1,4 +1,4 @@
import { Card, Text, Button, Title, Space } from "@mantine/core";
import { Card, Text, Space } from "@mantine/core";
import "./CardWithButton.css";
import { Link } from "react-router";
import CustomButton from "Components/CustomButton/CustomButton";

View File

@@ -35,10 +35,11 @@
border-color: var(--color);
background: transparent;
color: var(--color);
--hover_color: color-mix(in srgb, var(--hovercolor) 20%, transparent);
}
.outline:hover {
background: color-mix(in srgb, var(--hovercolor) 20%, transparent);
background: var(--hover_color);
}
/* ###################### */
@@ -46,10 +47,11 @@
.color {
background: var(--color);
color: var(--textcolor);
--hover_color: var(--hovercolor);
}
.color:hover {
background-color: var(--hovercolor);
background-color: var(--hover_color);
}
.primary {
@@ -98,8 +100,14 @@
.subtle {
color: var(--color);
--hover_color: color-mix(in srgb, var(--color) 20%, transparent);
}
.subtle:hover {
background-color: color-mix(in srgb, var(--color) 20%, transparent);
background-color: --hover_color;
}
.button-Disabled {
background-color: var(--hover_color);
cursor: inherit;
}

View File

@@ -34,7 +34,10 @@ function CustomButton({
console.log(color);
return (
<UnstyledButton
className={`colored ${style} ${color} textAlign-${textAlign}`}
className={
`colored ${style} ${color} textAlign-${textAlign} ` +
(disabled ? "button-Disabled" : "")
}
style={
color !== "primary" &&
color !== "secondary" &&

View File

@@ -2,9 +2,11 @@ import { Burger, Image, Text } from "@mantine/core";
import "./Header.css";
import { useLayoutStore } from "Stores/LayoutStore";
import { Link } from "react-router";
import { baseUrl } from "GlobalVars";
import { routes } from "Routes/Routes";
const logoUrl =
window.location.origin + "/" + import.meta.env.VITE_BASE_PATH + "/bitmap.png";
function Header() {
const { is_navbar_open, set_navbar_open } = useLayoutStore();
return (
@@ -14,7 +16,7 @@ function Header() {
className="logo"
w="auto"
fit="contain"
src={baseUrl + "/bitmap.png"}
src={logoUrl}
alt="image"
/>
<Text size="xl">QMolSim</Text>

View File

@@ -1,6 +1,5 @@
import {
Avatar,
Button,
Divider,
Modal,
Stack,
@@ -25,7 +24,6 @@ import { useState, type ForwardRefExoticComponent } from "react";
import { routes } from "Routes/Routes";
import keycloak from "Api/Keycloak/Keycloak";
import { AuthenticationStore } from "Stores/AuthenticationStore";
import { baseUri, baseUrl } from "GlobalVars";
import CustomButton from "Components/CustomButton/CustomButton";
interface SubtleLinkButtonProps {
@@ -69,7 +67,12 @@ function Sidebar() {
<div className="sidebar_bottom_bottom">
<CustomButton
text="Подтвердить"
onClick={() => keycloak.logout({ redirectUri: baseUri + baseUrl })}
onClick={() =>
keycloak.logout({
redirectUri:
window.location.origin + "/" + import.meta.env.VITE_BASE_PATH,
})
}
textSize="lg"
color="contrast"
></CustomButton>

View File

@@ -2,11 +2,17 @@ import { Pagination } from "@mantine/core";
import "./PaginationContainer.css";
import type { PropsWithChildren } from "react";
export function PaginationContainer(a: PropsWithChildren) {
interface PaginationContainerProps extends PropsWithChildren {
numberOfPages: number;
}
export function PaginationContainer(a: PaginationContainerProps) {
return (
<div className="PaginationContainer">
<div className="PaginationContents">{a.children}</div>
<Pagination total={10} color="accent" />
{a.numberOfPages > 1 && (
<Pagination total={a.numberOfPages} color="accent" />
)}
</div>
);
}

View File

@@ -1,11 +0,0 @@
export const baseUrl = "/quantum";
export const baseDomain = "localhost";
export const basePort = 8001;
export const keycloakURI = "http://auth.localhost";
export const baseUri = `http://${baseDomain}:${basePort}`;
//AppShell vars
export const headerHeight = 50;
export const sideMenuWidth = 280;
// Global Style vars
export const defaultAnimationDuration = 100;

View File

@@ -0,0 +1,4 @@
.MantineInput {
background-color: var(--mantine-color-secondary-filled);
color: var(--mantine-color-contrast-filled) !important;
}

View File

@@ -1,5 +1,4 @@
import {
Button,
Center,
Modal,
Select,
@@ -7,9 +6,8 @@ import {
Textarea,
TextInput,
Title,
UnstyledButton,
} from "@mantine/core";
import { useEffect, useState, type ChangeEvent } from "react";
import { useEffect, useState } from "react";
import "./NewExperiment.css";
import { useExperimentStore } from "Stores/ExperimentStore";
import CustomButton from "Components/CustomButton/CustomButton";
@@ -68,6 +66,7 @@ export function NewExperimentModal(props: NewExperimentModalProps) {
label="Имя эксперимента"
placeholder="Введите имя эксперимента"
required
classNames={{ input: "MantineInput" }}
onChange={(event) => {
setName(event.currentTarget.value);
}}
@@ -80,6 +79,7 @@ export function NewExperimentModal(props: NewExperimentModalProps) {
minRows={4}
maxRows={10}
autosize
classNames={{ input: "MantineInput" }}
onChange={(event) => {
setDescription(event.currentTarget.value);
}}
@@ -91,6 +91,7 @@ export function NewExperimentModal(props: NewExperimentModalProps) {
placeholder="Выберите команду эксперимента"
searchable
data={[]}
classNames={{ input: "MantineInput" }}
onChange={() => {}}
/>
<Space h="md" />

View File

View File

@@ -0,0 +1,31 @@
import { Helmet } from "react-helmet";
import "./DevicesPage.css";
import { PaginationContainer } from "Components/PaginationContainer/PaginationContainer";
import { Alert } from "@mantine/core";
import { Link } from "react-router";
function DevicesPage() {
return (
<>
<Helmet>
<title>Device Page | QMolSim</title>
<meta
name="description"
content="Get all the devices connected to your or your team account"
/>
</Helmet>
<div className="DevicesPage">
<PaginationContainer numberOfPages={1}>
<Alert title="Подключенные устройства не найдены" color="blue">
Для того, чтобы добавить устройство, простмотрите{" "}
<Link to={"documentaion"} className="invisible_link">
документацию
</Link>
</Alert>
</PaginationContainer>
</div>
</>
);
}
export default DevicesPage;

View File

@@ -1,26 +1,26 @@
.DocumentationPage {
display: flex;
flex-direction: row-reverse;
justify-content: space-between;
padding-top: 25px;
}
.contents {
flex-grow: 1;
}
.tableOfContents {
position: sticky;
top: 60px;
width: 150px;
height: min-content;
}
.docTitle {
padding-bottom: 50px;
}
.hoverCard {
position: fixed;
bottom: 10px;
}
.DocumentationPage {
display: flex;
flex-direction: row-reverse;
justify-content: space-between;
padding-top: 25px;
}
.contents {
flex-grow: 1;
}
.tableOfContents {
position: sticky;
top: 60px;
width: 190px;
height: min-content;
}
.docTitle {
padding-bottom: 50px;
}
.hoverCard {
position: fixed;
bottom: 10px;
}

View File

@@ -1,13 +1,5 @@
import {
ActionIcon,
Box,
Divider,
Menu,
TableOfContents,
Title,
} from "@mantine/core";
import { Box, Divider, TableOfContents, Title } from "@mantine/core";
import "./DocumentationPage.css";
import { IconMenu2 } from "@tabler/icons-react";
import { Helmet } from "react-helmet";
function DocumentationPage() {
@@ -31,9 +23,12 @@ function DocumentationPage() {
color="accent"
size="sm"
radius="sm"
minDepthToOffset={0}
depthOffset={20}
scrollSpyOptions={{
selector: "section h2",
selector: "section h1, h2",
}}
className=""
getControlProps={({ data }) => ({
onClick: () =>
data
@@ -43,56 +38,12 @@ function DocumentationPage() {
})}
/>
</Box>
<Box className="hoverCard" hiddenFrom="md">
<Menu
width={280}
shadow="md"
openDelay={100}
closeDelay={100}
closeOnClickOutside
closeOnItemClick
floatingStrategy="fixed"
>
<Menu.Target>
<ActionIcon
aria-label="navigation"
variant="gradient"
gradient={{ from: "blue", to: "cyan", deg: 90 }}
radius={"50%"}
size={40}
>
<IconMenu2 size={25} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<TableOfContents
variant="light"
color="accent"
size="sm"
radius="sm"
scrollSpyOptions={{
selector: "section h2",
}}
getControlProps={({ data }) => ({
onClick: () =>
data
.getNode()
.scrollIntoView({ behavior: "smooth", block: "center" }),
children: data.value,
})}
/>
</Menu.Dropdown>
</Menu>
</Box>
<div className="contents">
<section id="introduction" style={{ height: 1000 }}>
<Title order={2}>Introduction</Title>
<Title order={1}>1. Введение</Title>
</section>
<section id="features" style={{ height: 1000 }}>
<Title order={2}>features</Title>
</section>
<section id="conclusion" style={{ height: 1000 }}>
<Title order={2}>Conslusion</Title>
<section id="quick-start" style={{ height: 1000 }}>
<Title order={2}>1.1 Быстрое начало</Title>
</section>
</div>
</div>

View File

@@ -74,9 +74,9 @@ function ExperimentPage() {
</div>
</div>
{experiment.tasks_ids.length > 0 && (
<PaginationContainer>
{experiment.tasks_ids.map((task: ExperimentTask) => {
return <div>{task.data.name}</div>;
<PaginationContainer numberOfPages={1}>
{experiment.tasks_ids.map((task: number) => {
return <div>{task}</div>;
})}
</PaginationContainer>
)}
@@ -95,7 +95,7 @@ function ExperimentPage() {
<Alert color="red">
<Center>
{" "}
<Text c="contrast" size={"xl"} size="md">
<Text c="contrast" size={"xl"}>
Ошибка. Эксперимент не найден
</Text>{" "}
</Center>

View File

@@ -8,10 +8,11 @@ import ExperimentsListCard from "Components/ListCard/ExperimentsListCard";
import { useExperimentStore } from "Stores/ExperimentStore";
import type { Experiment } from "Types/Experiment/Experiment";
import CustomButton from "Components/CustomButton/CustomButton";
import { Alert } from "@mantine/core";
function ExperimentsPage() {
const [isOpen, setIsOpen] = useState(false);
const { experiments, teams, tasks } = useExperimentStore();
const { experiments, teams } = useExperimentStore();
return (
<>
@@ -32,18 +33,20 @@ function ExperimentsPage() {
marginBottom: "20px",
}}
>
<div className="experimentsButtons">
<CustomButton
color="contrast"
onClick={() => {
setIsOpen(true);
}}
icon={<IconMicroscope />}
text="Создать эксперимент"
/>
</div>
{teams.length > 0 && (
<div className="experimentsButtons">
<CustomButton
color="contrast"
onClick={() => {
setIsOpen(true);
}}
icon={<IconMicroscope />}
text="Создать эксперимент"
/>
</div>
)}
</div>
<PaginationContainer>
<PaginationContainer numberOfPages={1}>
{experiments.map((exp: Experiment) => {
return (
<ExperimentsListCard
@@ -58,6 +61,12 @@ function ExperimentsPage() {
/>
);
})}
{teams.length == 0 && (
<Alert title="Команды не найдены" color="red">
Создайте или войдите в команду чтобы начать работу с
экспериментами
</Alert>
)}
</PaginationContainer>
</div>
</>

View File

@@ -1,4 +1,6 @@
.TeamsPage {
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 10px;
}

View File

@@ -1,8 +1,14 @@
import { Helmet } from "react-helmet";
import "./TeamsPage.css";
import { PaginationContainer } from "Components/PaginationContainer/PaginationContainer";
import CustomButton from "Components/CustomButton/CustomButton";
import { IconUsersGroup } from "@tabler/icons-react";
import { useState } from "react";
import { Alert } from "@mantine/core";
function TeamsPage() {
const [, setIsOpen] = useState(false);
return (
<>
<Helmet>
@@ -13,7 +19,21 @@ function TeamsPage() {
/>
</Helmet>
<div className="TeamsPage">
<PaginationContainer />
<div className="experimentsButtons">
<CustomButton
color="contrast"
onClick={() => {
setIsOpen(true);
}}
icon={<IconUsersGroup />}
text="Создать эксперимент"
/>
</div>
<PaginationContainer numberOfPages={1}>
<Alert title="Команды не найдены" color="blue">
Создайте или войдите в команду чтобы начать работу с экспериментами
</Alert>
</PaginationContainer>
</div>
</>
);

View File

@@ -1,13 +1,12 @@
import {
Button,
Title,
Tabs,
TextInput,
SimpleGrid,
Chip,
Text,
Divider,
Switch,
LoadingOverlay,
Space,
} from "@mantine/core";
import {
IconChartCandle,
@@ -17,20 +16,98 @@ import {
IconSun,
IconMoonStars,
} from "@tabler/icons-react";
import keycloak from "Api/Keycloak/Keycloak";
import { useEffect } from "react";
import keycloak, {
SendEmailVerification,
updatePasswordWithRedirect,
updateUserData,
} from "Api/Keycloak/Keycloak";
import { useEffect, useState } from "react";
import { Helmet } from "react-helmet";
import { AuthenticationStore } from "Stores/AuthenticationStore";
import "./UserPage.css";
import { useUserPreferencesStore } from "Stores/PreferencesStore";
import CustomButton from "Components/CustomButton/CustomButton";
import { notifications } from "@mantine/notifications";
import { useSearchParams } from "react-router";
import {
GetCurrentUserInfo,
UpdateCurrentUserInfo,
} from "Api/QuantumBackend/UserManagement";
import type { UserData } from "Types/User/User";
function UserPage() {
const { profile, token } = AuthenticationStore();
const { profile, is_loading, profile_picture_path } = AuthenticationStore();
const { theme, set_theme } = useUserPreferencesStore();
const [username, set_username] = useState<string>("");
const [email, set_email] = useState<string>("");
const [pfp_path, set_pfp_path] = useState<string>("");
const [is_editing_path, set_is_editing_path] = useState<boolean>(false);
const [searchParams] = useSearchParams();
const updateData = () => {
if (
profile &&
((profile.username && profile.username != username) ||
(profile.email && profile.email != email))
) {
console.log("A");
const prof_1 = profile;
prof_1.email = email;
prof_1.username = username;
AuthenticationStore.setState({
is_loading: true,
});
updateUserData(prof_1).then((data) => {
console.log(data);
if (data) {
notifications.show({
radius: "md",
title: "Данные успешно изменены",
message: "",
icon: <IconCheck />,
style: { paddingLeft: "5px" },
});
keycloak.loadUserProfile().then((profile) => {
AuthenticationStore.setState({
is_loading: false,
profile: profile,
});
});
}
});
}
};
const update_pfp = async () => {
UpdateCurrentUserInfo(pfp_path).then(() => {
GetCurrentUserInfo().then((info: UserData | undefined) => {
if (info && info.profile_picture_path)
AuthenticationStore.setState({
profile_picture_path: info.profile_picture_path,
});
});
});
};
useEffect(() => {
console.log(token);
}, []);
if (profile) {
if (profile.username) set_username(profile.username);
if (profile.email) set_email(profile.email);
if (searchParams.get("password_updated")) {
notifications.show({
radius: "md",
title: "Пароль изменен успешно",
message: "",
icon: <IconCheck />,
style: { paddingLeft: "5px" },
});
}
}
}, [profile, searchParams]);
useEffect(() => {
if (profile_picture_path) set_pfp_path(profile_picture_path);
}, [profile_picture_path]);
return (
<>
<Helmet>
@@ -68,92 +145,223 @@ function UserPage() {
</Tabs.List>
<Tabs.Panel value="profile">
<SimpleGrid verticalSpacing="lg" cols={2}>
<Title size="lg">Имя пользователя:</Title>
<TextInput size="md" value={profile?.username} />
<Title size="lg">Почта:</Title>
<TextInput size="md" value={profile?.email} />
<CustomButton color="accent" text="Сохранить" />
<CustomButton color="error" text="Отменить" />
</SimpleGrid>
<Divider my="lg" />
<SimpleGrid verticalSpacing={"lg"} cols={2}>
<Title
size="lg"
style={{ display: "flex", alignItems: "center" }}
>
Почта верифицирована:{" "}
<Chip mx="lg" size="auto" checked={profile?.emailVerified}>
{profile?.emailVerified ? (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<IconCheck
size={25}
color={"green"}
style={{ verticalAlign: "center", margin: "5px" }}
/>
</div>
) : (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<IconCancel
size={25}
color="red"
<div
style={{ position: "relative", padding: "5px", height: "100%" }}
>
<LoadingOverlay
visible={is_loading}
zIndex={1000}
overlayProps={{ radius: "sm", blur: 2 }}
loaderProps={{ size: 50, type: "dots" }}
/>
<SimpleGrid verticalSpacing="lg" cols={2}>
<Title size="lg">Имя пользователя:</Title>
<TextInput
size="md"
value={username}
onChange={(e) => set_username(e.currentTarget.value)}
/>
<Title size="lg">Почта:</Title>
<TextInput
size="md"
value={email}
onChange={(e) => set_email(e.currentTarget.value)}
/>
<CustomButton
color="accent"
text="Сохранить"
onClick={updateData}
disabled={
!(
profile != null &&
((profile.username != undefined &&
profile.username != username) ||
(profile.email != undefined && profile.email != email))
)
}
/>
<CustomButton
color="error"
text="Отменить"
disabled={
!(
profile != null &&
((profile.username != undefined &&
profile.username != username) ||
(profile.email != undefined && profile.email != email))
)
}
/>
</SimpleGrid>
<Divider my="lg" />
<SimpleGrid verticalSpacing={"lg"} cols={2}>
<Title
size="lg"
style={{ display: "flex", alignItems: "center" }}
>
Почта верифицирована:{" "}
<div>
{profile?.emailVerified ? (
<div
style={{
verticalAlign: "center",
margin: "5px",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<IconCheck
size={25}
color={"white"}
style={{ verticalAlign: "center", margin: "5px" }}
/>
</div>
) : (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<IconCancel
size={25}
color="red"
style={{
verticalAlign: "center",
margin: "5px",
}}
/>
</div>
)}
</div>
</Title>
{!profile?.emailVerified && (
<div>
<CustomButton
style="outline"
color="contrast"
text="Подтвердить почту"
onClick={() => SendEmailVerification()}
/>
</div>
)}
{profile?.emailVerified && (
<div style={{ height: "40px", display: "flex" }}></div>
)}
<Title size="lg">Пароль:</Title>
<div>
<CustomButton
style="outline"
color="contrast"
text="Изменить пароль"
onClick={() => {
updatePasswordWithRedirect();
}}
/>
</div>
</SimpleGrid>
<Divider my="lg" />
<div style={{ display: "flex", flexDirection: "column" }}>
<Title size="lg">Фотография профиля</Title>
<Space my="sm" />
{!is_editing_path ? (
<img height={350} width={350} src={profile_picture_path} />
) : (
<TextInput
size="md"
value={pfp_path}
onChange={(e) => set_pfp_path(e.currentTarget.value)}
/>
)}
<Space my="sm" />
<div style={{ width: "15em" }}>
{!is_editing_path ? (
<CustomButton
style="outline"
color="contrast"
text="Изменить"
onClick={() => {
set_is_editing_path(true);
}}
/>
) : (
<>
<CustomButton
style="outline"
color="contrast"
text="Сохранить"
onClick={() => {
update_pfp();
set_is_editing_path(false);
}}
/>
</div>
<Space my="sm" />
<CustomButton
style="outline"
color="red"
text="Отменить"
onClick={() => {
set_is_editing_path(false);
set_pfp_path(profile_picture_path);
}}
/>
</>
)}
</Chip>
</Title>
{!profile?.emailVerified && (
<CustomButton
style="outline"
color="contrast"
text="Подтвердить почту"
/>
)}
{profile?.emailVerified && <div></div>}
<Title size="lg">Пароль:</Title>
<CustomButton
style="outline"
color="contrast"
text="Изменить пароль"
/>
</SimpleGrid>
</div>
</div>
</div>
</Tabs.Panel>
<Tabs.Panel value="preference">
<Switch
size="xl"
defaultChecked={theme == "light"}
onChange={(event) =>
set_theme(!event.currentTarget.checked ? "dark" : "light")
}
onLabel={
<IconSun
size={16}
stroke={2.5}
color="var(--mantine-color-yellow-4)"
/>
<div
style={{
display: "flex",
flexDirection: "row",
flexWrap: "nowrap",
gap: "10px",
alignContent: "center",
justifyContent: "center",
alignItems: "center",
padding: "5px",
}}
>
<IconSun
size={30}
stroke={2.5}
color="var(--mantine-color-yellow-4)"
/>
<Title size={"md"}>Светлая</Title>
</div>
}
offLabel={
<IconMoonStars
size={16}
stroke={2.5}
color="var(--mantine-color-blue-6)"
/>
<div
style={{
display: "flex",
flexDirection: "row",
flexWrap: "nowrap",
gap: "10px",
alignContent: "center",
justifyContent: "center",
alignItems: "center",
padding: "5px",
}}
>
<Title size={"md"}>Темная</Title>
<IconMoonStars
size={30}
stroke={2.5}
color="var(--mantine-color-blue-6)"
/>
</div>
}
/>
</Tabs.Panel>

View File

@@ -1,6 +1,6 @@
import { Breadcrumbs } from "@mantine/core";
import { type ReactElement } from "react";
import { Link, type UIMatch } from "react-router";
import { Link } from "react-router";
import "./Breadcrumbs.css";
import { routes } from "Routes/Routes";
import { useLocation } from "react-router";

View File

@@ -10,7 +10,7 @@ export default function AuthGuard() {
loginStarted.current = true;
keycloak.login({
redirectUri: window.location.href,
redirectUri: window.location.origin,
});
}
}, []);

View File

@@ -1,6 +1,5 @@
import { createBrowserRouter } from "react-router";
import MainPage from "Pages/MainPage/MainPage";
import { baseUrl } from "../GlobalVars";
import App from "../App";
import ErrorPage from "./ErrorPage";
import DocumentationPage from "Pages/DocumentationPage/DocumentationPage";
@@ -12,6 +11,7 @@ import UserPage from "Pages/UserPage/UserPage";
import ExperimentPage from "Pages/ExperimentsPage/ExperimentPage";
import ExperimentsPage from "Pages/ExperimentsPage/ExperimentsPage";
import AuthGuard from "./RouterAuhGuard";
import DevicesPage from "Pages/DevicesPage/DevicesPage";
export const routes: {
[id: string]: { path: string; breadcrumbs: (path: string) => ReactElement[] };
@@ -66,7 +66,7 @@ const router = createBrowserRouter(
},
{
element: <AuthGuard />, // 🔒 everything below requires auth
element: <AuthGuard />,
children: [
{
path: routes.ExperimentsPage.path,
@@ -84,6 +84,10 @@ const router = createBrowserRouter(
path: routes.TeamsPage.path,
Component: TeamsPage,
},
{
path: routes.MachinesPage.path,
Component: DevicesPage,
},
],
},
@@ -94,6 +98,6 @@ const router = createBrowserRouter(
],
},
],
{ basename: baseUrl },
{ basename: import.meta.env.VITE_BASE_PATH },
);
export default router;

View File

@@ -2,18 +2,24 @@ import type { KeycloakProfile } from "keycloak-js";
import { create } from "zustand";
interface AuthernticationStoreState {
token: string | undefined;
is_loading: boolean;
profile: KeycloakProfile | null;
profile_picture_path: string;
set_profile: (profile: KeycloakProfile | null) => void;
set_token: (token: string | undefined) => void;
set_profile_picture_path: (path: string) => void;
set_is_loading: (is_loading: boolean) => void;
}
export const AuthenticationStore = create<AuthernticationStoreState>()(
(set) => ({
token: undefined,
is_loading: true,
profile: null,
profile_picture_path: "",
set_profile: (profile: KeycloakProfile | null) =>
set(() => ({ profile: profile })),
set_token: (token: string | undefined) => set(() => ({ token: token })),
set_is_loading: (is_loading: boolean) =>
set(() => ({ is_loading: is_loading })),
set_profile_picture_path: (path: string) =>
set(() => ({ profile_picture_path: path })),
}),
);

View File

@@ -1,7 +1,3 @@
//export interface Experiment {}
import type { Team } from "Types/User/User";
export type ExperimentStatus =
| "DRAFT"
| "QUEUE"

View File

@@ -18,3 +18,11 @@ export interface Permission {
id: number;
name: string;
}
export interface UserData {
keycloak_id: string;
email: string;
username: string;
profile_picture_path: string | null;
created_at: Date;
}

View File

@@ -13,6 +13,9 @@ import {
import keycloak from "Api/Keycloak/Keycloak";
import { AuthenticationStore } from "Stores/AuthenticationStore";
import { useUserPreferencesStore } from "Stores/PreferencesStore";
import type { KeycloakProfile } from "keycloak-js";
import { GetCurrentUserInfo } from "Api/QuantumBackend/UserManagement";
import type { UserData } from "Types/User/User";
const colorSchemeManager = localStorageColorSchemeManager({
key: "my-app-color-scheme",
@@ -60,18 +63,39 @@ const theme = createTheme({
});
async function bootstrap() {
const authenticated = await keycloak.init({
onLoad: "check-sso",
pkceMethod: "S256",
silentCheckSsoRedirectUri:
"http://localhost:8001/quantum/silent-check-sso.html",
});
if (authenticated) {
const profile = await keycloak.loadUserProfile();
AuthenticationStore.setState({ token: keycloak.token, profile: profile });
}
AuthenticationStore.setState({ is_loading: true });
keycloak
.init({
onLoad: "check-sso",
pkceMethod: "S256",
silentCheckSsoRedirectUri:
window.location.origin +
"/" +
import.meta.env.VITE_BASE_PATH +
"/silent-check-sso.html",
silentCheckSsoFallback: false,
})
.then((authenticated: boolean) => {
if (authenticated) {
keycloak.loadUserProfile().then((profile: KeycloakProfile) => {
AuthenticationStore.setState({
is_loading: false,
profile: profile,
});
GetCurrentUserInfo().then((info: UserData | undefined) => {
if (info && info.profile_picture_path)
AuthenticationStore.setState({
profile_picture_path: info.profile_picture_path,
});
});
});
} else {
console.log("Keycloak authentication failed.");
AuthenticationStore.setState({
is_loading: false,
});
}
});
useUserPreferencesStore.setState({
theme: checkIsDarkSchemePreferred() ? "dark" : "light",
@@ -80,7 +104,7 @@ async function bootstrap() {
createRoot(document.getElementById("root")!).render(<AppProviders />);
}
function AppProviders() {
export function AppProviders() {
const themePreference = useUserPreferencesStore((state) => state.theme);
return (