2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-05-05 14:58:50 +00:00

refactor(frontend): Auth component refactor (#9121)

* https://github.com/inventree/InvenTree/pull/6293

* refactor to a shared component

* refactoring container stuff to a wrapper

* move title to wrapper

* move logoff and loader to wrapper

* mvoe functions to general auth

* seperate login and register into seperate pages

* unify auth styling

* rename component

* adapt to new look

* check if registration is enabled

* reduce diff

* reduce diff

* fix import

* add aria label to make more reliable

* make cap match

* ensure that confirm only works with valid inputs

* leave error for non-matching pwd to API

---------

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
This commit is contained in:
Matthias Mair 2025-02-24 21:04:16 +01:00 committed by GitHub
parent ce813e0c28
commit 991b578c30
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 568 additions and 648 deletions

View File

@ -1,4 +1,5 @@
import { BackgroundImage } from '@mantine/core';
import { useEffect } from 'react';
import { generateUrl } from '../functions/urls';
import { useServerApiState } from '../states/ApiState';
@ -7,10 +8,20 @@ import { useServerApiState } from '../states/ApiState';
*/
export default function SplashScreen({
children
}: {
}: Readonly<{
children: React.ReactNode;
}) {
const [server] = useServerApiState((state) => [state.server]);
}>) {
const [server, fetchServerApiState] = useServerApiState((state) => [
state.server,
state.fetchServerApiState
]);
// Fetch server data on mount if no server data is present
useEffect(() => {
if (server.server === null) {
fetchServerApiState();
}
}, [server]);
if (server.customize?.splash) {
return (

View File

@ -7,7 +7,6 @@ import {
Loader,
PasswordInput,
Stack,
Text,
TextInput
} from '@mantine/core';
import { useForm } from '@mantine/form';
@ -329,47 +328,3 @@ export function RegistrationForm() {
</>
);
}
export function ModeSelector({
loginMode,
changePage
}: Readonly<{
loginMode: boolean;
changePage: (state: string) => void;
}>) {
const [sso_registration, registration_enabled] = useServerApiState(
(state) => [state.sso_registration_enabled, state.registration_enabled]
);
const both_reg_enabled =
registration_enabled() || sso_registration() || false;
if (both_reg_enabled === false) return null;
return (
<Text ta='center' size={'xs'} mt={'md'}>
{loginMode ? (
<>
<Trans>Don&apos;t have an account?</Trans>{' '}
<Anchor
component='button'
type='button'
c='dimmed'
size='xs'
onClick={() => changePage('register')}
>
<Trans>Register</Trans>
</Anchor>
</>
) : (
<Anchor
component='button'
type='button'
c='dimmed'
size='xs'
onClick={() => changePage('login')}
>
<Trans>Go back to login</Trans>
</Anchor>
)}
</Text>
);
}

View File

@ -1,13 +1,5 @@
import { Trans, t } from '@lingui/macro';
import {
ActionIcon,
Divider,
Group,
Paper,
Select,
Table,
Text
} from '@mantine/core';
import { ActionIcon, Divider, Group, Select, Table, Text } from '@mantine/core';
import { useToggle } from '@mantine/hooks';
import {
IconApi,
@ -18,11 +10,11 @@ import {
IconServerSpark
} from '@tabler/icons-react';
import { Wrapper } from '../../pages/Auth/Layout';
import { useServerApiState } from '../../states/ApiState';
import { useLocalState } from '../../states/LocalState';
import type { HostList } from '../../states/states';
import { EditButton } from '../buttons/EditButton';
import { StylishText } from '../items/StylishText';
import { HostOptionsForm } from './HostOptionsForm';
export function InstanceOptions({
@ -54,10 +46,7 @@ export function InstanceOptions({
}
return (
<>
<Paper p='xl' withBorder>
<StylishText size='xl'>{t`Select Server`}</StylishText>
<Divider p='xs' />
<Wrapper titleText={t`Select Server`} smallPadding>
<Group gap='xs' wrap='nowrap'>
<Select
value={hostKey}
@ -92,8 +81,7 @@ export function InstanceOptions({
<ServerInfo hostList={hostList} hostKey={hostKey} />
</>
)}
</Paper>
</>
</Wrapper>
);
}

View File

@ -22,6 +22,7 @@ export function LanguageToggle() {
onClick={() => toggle.toggle()}
size='lg'
variant='transparent'
aria-label='Language toggle'
>
<IconLanguage />
</ActionIcon>

View File

@ -1,5 +1,5 @@
import { t } from '@lingui/macro';
import { notifications } from '@mantine/notifications';
import { notifications, showNotification } from '@mantine/notifications';
import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import type { Location, NavigateFunction } from 'react-router-dom';
@ -358,3 +358,172 @@ export function authApi(
// use normal api
return api(url, requestConfig);
}
export const getTotpSecret = async (setTotpQr: any) => {
await authApi(apiUrl(ApiEndpoints.auth_totp), undefined, 'get').catch(
(err) => {
if (err.status == 404 && err.response.data.meta.secret) {
setTotpQr(err.response.data.meta);
} else {
const msg = err.response.data.errors[0].message;
showNotification({
title: t`Failed to set up MFA`,
message: msg,
color: 'red'
});
}
}
);
};
export function handleVerifyTotp(
value: string,
navigate: NavigateFunction,
location: Location<any>
) {
return () => {
authApi(apiUrl(ApiEndpoints.auth_totp), undefined, 'post', {
code: value
}).then(() => {
followRedirect(navigate, location?.state);
});
};
}
export function handlePasswordReset(
key: string | null,
password: string,
navigate: NavigateFunction
) {
function success() {
notifications.show({
title: t`Password set`,
message: t`The password was set successfully. You can now login with your new password`,
color: 'green',
autoClose: false
});
navigate('/login');
}
function passwordError(values: any) {
notifications.show({
title: t`Reset failed`,
message: values?.errors.map((e: any) => e.message).join('\n'),
color: 'red'
});
}
// Set password with call to backend
api
.post(
apiUrl(ApiEndpoints.user_reset_set),
{
key: key,
password: password
},
{ headers: { Authorization: '' } }
)
.then((val) => {
if (val.status === 200) {
success();
} else {
passwordError(val.data);
}
})
.catch((err) => {
if (err.response?.status === 400) {
passwordError(err.response.data);
} else if (err.response?.status === 401) {
success();
} else {
passwordError(err.response.data);
}
});
}
export function handleVerifyEmail(
key: string | undefined,
navigate: NavigateFunction
) {
// Set password with call to backend
api
.post(apiUrl(ApiEndpoints.auth_email_verify), {
key: key
})
.then((val) => {
if (val.status === 200) {
navigate('/login');
}
});
}
export function handleChangePassword(
pwd1: string,
pwd2: string,
current: string,
navigate: NavigateFunction
) {
const { clearUserState } = useUserState.getState();
function passwordError(values: any) {
let message: any =
values?.new_password ||
values?.new_password2 ||
values?.new_password1 ||
values?.current_password ||
values?.error ||
t`Password could not be changed`;
// If message is array
if (!Array.isArray(message)) {
message = [message];
}
message.forEach((msg: string) => {
notifications.show({
title: t`Error`,
message: msg,
color: 'red'
});
});
}
// check if passwords match
if (pwd1 !== pwd2) {
passwordError({ new_password2: t`The two password fields didnt match` });
return;
}
// Set password with call to backend
api
.post(apiUrl(ApiEndpoints.auth_pwd_change), {
current_password: current,
new_password: pwd2
})
.then((val) => {
passwordError(val.data);
})
.catch((err) => {
if (err.status === 401) {
notifications.show({
title: t`Password Changed`,
message: t`The password was set successfully. You can now login with your new password`,
color: 'green',
autoClose: false
});
clearUserState();
clearCsrfCookie();
navigate('/login');
} else {
// compile errors
const errors: { [key: string]: string[] } = {};
for (const val of err.response.data.errors) {
if (!errors[val.param]) {
errors[val.param] = [];
}
errors[val.param].push(val.message);
}
passwordError(errors);
}
});
}

View File

@ -1,8 +1,6 @@
import { Trans, t } from '@lingui/macro';
import {
Button,
Center,
Container,
Divider,
Group,
Paper,
@ -11,18 +9,11 @@ import {
Text
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { useNavigate } from 'react-router-dom';
import { api } from '../../App';
import SplashScreen from '../../components/SplashScreen';
import { StylishText } from '../../components/items/StylishText';
import { ProtectedRoute } from '../../components/nav/Layout';
import { LanguageContext } from '../../contexts/LanguageContext';
import { ApiEndpoints } from '../../enums/ApiEndpoints';
import { clearCsrfCookie } from '../../functions/auth';
import { apiUrl } from '../../states/ApiState';
import { handleChangePassword } from '../../functions/auth';
import { useUserState } from '../../states/UserState';
import { Wrapper } from './Layout';
export default function Set_Password() {
const simpleForm = useForm({
@ -36,91 +27,17 @@ export default function Set_Password() {
const user = useUserState();
const navigate = useNavigate();
function passwordError(values: any) {
let message: any =
values?.new_password ||
values?.new_password2 ||
values?.new_password1 ||
values?.current_password ||
values?.error ||
t`Password could not be changed`;
// If message is array
if (!Array.isArray(message)) {
message = [message];
}
message.forEach((msg: string) => {
notifications.show({
title: t`Error`,
message: msg,
color: 'red'
});
});
}
function handleSet() {
const { clearUserState } = useUserState.getState();
// check if passwords match
if (simpleForm.values.new_password1 !== simpleForm.values.new_password2) {
passwordError({ new_password2: t`The two password fields didnt match` });
return;
}
// Set password with call to backend
api
.post(apiUrl(ApiEndpoints.auth_pwd_change), {
current_password: simpleForm.values.current_password,
new_password: simpleForm.values.new_password2
})
.then((val) => {
passwordError(val.data);
})
.catch((err) => {
if (err.status === 401) {
notifications.show({
title: t`Password Changed`,
message: t`The password was set successfully. You can now login with your new password`,
color: 'green',
autoClose: false
});
clearUserState();
clearCsrfCookie();
navigate('/login');
} else {
// compile errors
const errors: { [key: string]: string[] } = {};
for (const val of err.response.data.errors) {
if (!errors[val.param]) {
errors[val.param] = [];
}
errors[val.param].push(val.message);
}
passwordError(errors);
}
});
}
return (
<LanguageContext>
<ProtectedRoute>
<SplashScreen>
<Center mih='100vh'>
<Container w='md' miw={425}>
<Paper p='xl' withBorder>
<Stack>
<StylishText size='xl'>{t`Reset Password`}</StylishText>
<Divider />
<Wrapper titleText={t`Reset Password`}>
{user.username() && (
<Paper>
<Group>
<StylishText size='md'>{t`Username`}</StylishText>
<StylishText size='md'>{t`User`}</StylishText>
<Text>{user.username()}</Text>
</Group>
</Paper>
)}
<Divider />
<Divider p='xs' />
<Stack gap='xs'>
<PasswordInput
required
@ -144,15 +61,23 @@ export default function Set_Password() {
{...simpleForm.getInputProps('new_password2')}
/>
</Stack>
<Button type='submit' onClick={handleSet}>
<Button
type='submit'
onClick={() =>
handleChangePassword(
simpleForm.values.new_password1,
simpleForm.values.new_password2,
simpleForm.values.current_password,
navigate
)
}
disabled={
simpleForm.values.current_password === '' ||
simpleForm.values.new_password1 === ''
}
>
<Trans>Confirm</Trans>
</Button>
</Stack>
</Paper>
</Container>
</Center>
</SplashScreen>
</ProtectedRoute>
</LanguageContext>
</Wrapper>
);
}

View File

@ -0,0 +1,74 @@
import { Trans } from '@lingui/macro';
import {
Button,
Center,
Container,
Divider,
Group,
Loader,
Paper,
Stack
} from '@mantine/core';
import { Outlet, useNavigate } from 'react-router-dom';
import SplashScreen from '../../components/SplashScreen';
import { StylishText } from '../../components/items/StylishText';
import { doLogout } from '../../functions/auth';
export default function Layout() {
return (
<SplashScreen>
<Center mih='100vh'>
<div
style={{
padding: '10px',
backgroundColor: 'rgba(0,0,0,0.5)',
boxShadow: '0 0 15px 10px rgba(0,0,0,0.5)'
}}
>
<Container w='md' miw={400}>
<Outlet />
</Container>
</div>
</Center>
</SplashScreen>
);
}
export function Wrapper({
children,
titleText,
logOff = false,
loader = false,
smallPadding = false
}: Readonly<{
children?: React.ReactNode;
titleText: string;
logOff?: boolean;
loader?: boolean;
smallPadding?: boolean;
}>) {
const navigate = useNavigate();
return (
<Paper p='xl' withBorder miw={425}>
<Stack gap={smallPadding ? 0 : 'md'}>
<StylishText size='xl'>{titleText}</StylishText>
<Divider p='xs' />
{loader && (
<Group justify='center'>
<Loader />
</Group>
)}
{children}
{logOff && (
<>
<Divider p='xs' />
<Button onClick={() => doLogout(navigate)} color='red'>
<Trans>Log off</Trans>
</Button>
</>
)}
</Stack>
</Paper>
);
}

View File

@ -1,15 +1,14 @@
import { Trans } from '@lingui/macro';
import { Card, Container, Group, Loader, Stack, Text } from '@mantine/core';
import { t } from '@lingui/macro';
import { useDebouncedCallback } from '@mantine/hooks';
import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { checkLoginState } from '../../functions/auth';
import { Wrapper } from './Layout';
export default function Logged_In() {
const navigate = useNavigate();
const location = useLocation();
const checkLoginStateDebounced = useDebouncedCallback(checkLoginState, 300);
useEffect(() => {
@ -17,19 +16,6 @@ export default function Logged_In() {
}, [navigate]);
return (
<Container>
<Stack align='center'>
<Card shadow='sm' padding='lg' radius='md'>
<Stack>
<Text size='lg'>
<Trans>Checking if you are already logged in</Trans>
</Text>
<Group justify='center'>
<Loader />
</Group>
</Stack>
</Card>
</Stack>
</Container>
<Wrapper titleText={t`Checking if you are already logged in`} loader />
);
}

View File

@ -1,18 +1,12 @@
import { t } from '@lingui/macro';
import { Center, Container, Divider, Paper, Text } from '@mantine/core';
import { useDisclosure, useToggle } from '@mantine/hooks';
import { Trans, t } from '@lingui/macro';
import { Anchor, Divider, Text } from '@mantine/core';
import { useToggle } from '@mantine/hooks';
import { useEffect, useMemo } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { setApiDefaults } from '../../App';
import SplashScreen from '../../components/SplashScreen';
import { AuthFormOptions } from '../../components/forms/AuthFormOptions';
import {
AuthenticationForm,
ModeSelector,
RegistrationForm
} from '../../components/forms/AuthenticationForm';
import { AuthenticationForm } from '../../components/forms/AuthenticationForm';
import { InstanceOptions } from '../../components/forms/InstanceOptions';
import { StylishText } from '../../components/items/StylishText';
import { defaultHostKey } from '../../defaults/defaultHostList';
import {
checkLoginState,
@ -21,6 +15,7 @@ import {
} from '../../functions/auth';
import { useServerApiState } from '../../states/ApiState';
import { useLocalState } from '../../states/LocalState';
import { Wrapper } from './Layout';
export default function Login() {
const [hostKey, setHost, hostList] = useLocalState((state) => [
@ -35,22 +30,18 @@ export default function Login() {
const hostname =
hostList[hostKey] === undefined ? t`No selection` : hostList[hostKey]?.name;
const [hostEdit, setHostEdit] = useToggle([false, true] as const);
const [loginMode, setMode] = useDisclosure(true);
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
useEffect(() => {
if (location.pathname === '/register') {
setMode.close();
} else {
setMode.open();
}
}, [location]);
const [sso_registration, registration_enabled] = useServerApiState(
(state) => [state.sso_registration_enabled, state.registration_enabled]
);
const both_reg_enabled =
registration_enabled() || sso_registration() || false;
const LoginMessage = useMemo(() => {
const val = server.customize?.login_message;
if (val) {
if (val == undefined) return null;
return (
<>
<Divider my='md' />
@ -62,8 +53,6 @@ export default function Login() {
</Text>
</>
);
}
return null;
}, [server.customize]);
// Data manipulation functions
@ -94,25 +83,8 @@ export default function Login() {
}
}, []);
// Fetch server data on mount if no server data is present
useEffect(() => {
if (server.server === null) {
fetchServerApiState();
}
}, [server]);
// Main rendering block
return (
<SplashScreen>
<Center mih='100vh'>
<div
style={{
padding: '10px',
backgroundColor: 'rgba(0,0,0,0.5)',
boxShadow: '0 0 15px 10px rgba(0,0,0,0.5)'
}}
>
<Container w='md' miw={400}>
<>
{hostEdit ? (
<InstanceOptions
hostKey={hostKey}
@ -121,27 +93,27 @@ export default function Login() {
/>
) : (
<>
<Paper p='xl' withBorder>
<StylishText size='xl'>
{loginMode ? t`Login` : t`Register`}
</StylishText>
<Divider p='xs' />
{loginMode ? <AuthenticationForm /> : <RegistrationForm />}
<ModeSelector
loginMode={loginMode}
changePage={(newPage) => navigate(`/${newPage}`)}
/>
<Wrapper titleText={t`Login`} smallPadding>
<AuthenticationForm />
{both_reg_enabled === false && (
<Text ta='center' size={'xs'} mt={'md'}>
<Trans>Don&apos;t have an account?</Trans>{' '}
<Anchor
component='button'
type='button'
c='dimmed'
size='xs'
onClick={() => navigate('/register')}
>
<Trans>Register</Trans>
</Anchor>
</Text>
)}
{LoginMessage}
</Paper>
<AuthFormOptions
hostname={hostname}
toggleHostEdit={setHostEdit}
/>
</Wrapper>
<AuthFormOptions hostname={hostname} toggleHostEdit={setHostEdit} />
</>
)}
</Container>
</div>
</Center>
</SplashScreen>
</>
);
}

View File

@ -1,9 +1,8 @@
import { Trans } from '@lingui/macro';
import { Card, Container, Group, Loader, Stack, Text } from '@mantine/core';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { doLogout } from '../../functions/auth';
import { Wrapper } from './Layout';
/* Expose a route for explicit logout via URL */
export default function Logout() {
@ -13,20 +12,5 @@ export default function Logout() {
doLogout(navigate);
}, []);
return (
<Container>
<Stack align='center'>
<Card shadow='sm' padding='lg' radius='md'>
<Stack>
<Text size='lg'>
<Trans>Logging out</Trans>
</Text>
<Group justify='center'>
<Loader />
</Group>
</Stack>
</Card>
</Stack>
</Container>
);
return <Wrapper titleText='Logging out' loader />;
}

View File

@ -0,0 +1,35 @@
import { Trans, t } from '@lingui/macro';
import { Button, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';
import { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { handleMfaLogin } from '../../functions/auth';
import { Wrapper } from './Layout';
export default function Mfa() {
const simpleForm = useForm({ initialValues: { code: '' } });
const navigate = useNavigate();
const location = useLocation();
const [loginError, setLoginError] = useState<string | undefined>(undefined);
return (
<Wrapper titleText={t`Multi-Factor Login`} logOff>
<TextInput
required
label={t`TOTP Code`}
name='TOTP'
description={t`Enter your TOTP or recovery code`}
{...simpleForm.getInputProps('code')}
error={loginError}
/>
<Button
type='submit'
onClick={() =>
handleMfaLogin(navigate, location, simpleForm.values, setLoginError)
}
>
<Trans>Log in</Trans>
</Button>
</Wrapper>
);
}

View File

@ -1,63 +0,0 @@
import { Trans, t } from '@lingui/macro';
import {
Button,
Center,
Container,
Paper,
Stack,
TextInput
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { useLocation, useNavigate } from 'react-router-dom';
import { useState } from 'react';
import SplashScreen from '../../components/SplashScreen';
import { StylishText } from '../../components/items/StylishText';
import { LanguageContext } from '../../contexts/LanguageContext';
import { handleMfaLogin } from '../../functions/auth';
export default function MFALogin() {
const simpleForm = useForm({ initialValues: { code: '' } });
const navigate = useNavigate();
const location = useLocation();
const [loginError, setLoginError] = useState<string | undefined>(undefined);
return (
<LanguageContext>
<SplashScreen>
<Center mih='100vh'>
<Container w='md' miw={425}>
<Paper p='xl' withBorder>
<Stack>
<StylishText size='xl'>{t`Multi-Factor Login`}</StylishText>
<Stack>
<TextInput
required
label={t`TOTP Code`}
name='TOTP'
description={t`Enter your TOTP or recovery code`}
{...simpleForm.getInputProps('code')}
error={loginError}
/>
</Stack>
<Button
type='submit'
onClick={() =>
handleMfaLogin(
navigate,
location,
simpleForm.values,
setLoginError
)
}
>
<Trans>Log In</Trans>
</Button>
</Stack>
</Paper>
</Container>
</Center>
</SplashScreen>
</LanguageContext>
);
}

View File

@ -1,12 +1,10 @@
import { Trans, t } from '@lingui/macro';
import { Button, Center, Container, Stack, Title } from '@mantine/core';
import { showNotification } from '@mantine/notifications';
import { getTotpSecret, handleVerifyTotp } from '../../functions/auth';
import { Wrapper } from './Layout';
import { Button } from '@mantine/core';
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { LanguageContext } from '../../contexts/LanguageContext';
import { ApiEndpoints } from '../../enums/ApiEndpoints';
import { authApi, doLogout, followRedirect } from '../../functions/auth';
import { apiUrl } from '../../states/ApiState';
import { QrRegistrationForm } from '../Index/Settings/AccountSettings/QrRegistrationForm';
export default function MFASetup() {
@ -16,37 +14,12 @@ export default function MFASetup() {
const [totpQr, setTotpQr] = useState<{ totp_url: string; secret: string }>();
const [value, setValue] = useState('');
const registerTotp = async () => {
await authApi(apiUrl(ApiEndpoints.auth_totp), undefined, 'get').catch(
(err) => {
if (err.status == 404 && err.response.data.meta.secret) {
setTotpQr(err.response.data.meta);
} else {
const msg = err.response.data.errors[0].message;
showNotification({
title: t`Failed to set up MFA`,
message: msg,
color: 'red'
});
}
}
);
};
useEffect(() => {
if (!totpQr) {
registerTotp();
}
}, [totpQr]);
getTotpSecret(setTotpQr);
}, []);
return (
<LanguageContext>
<Center mih='100vh'>
<Container w='md' miw={425}>
<Stack>
<Title>
<Trans>MFA Setup Required</Trans>
</Title>
<Wrapper titleText={t`MFA Setup Required`} logOff>
<QrRegistrationForm
url={totpQr?.totp_url ?? ''}
secret={totpQr?.secret ?? ''}
@ -55,22 +28,10 @@ export default function MFASetup() {
/>
<Button
disabled={!value}
onClick={() => {
authApi(apiUrl(ApiEndpoints.auth_totp), undefined, 'post', {
code: value
}).then(() => {
followRedirect(navigate, location?.state);
});
}}
onClick={handleVerifyTotp(value, navigate, location)}
>
<Trans>Add TOTP</Trans>
</Button>
<Button onClick={() => doLogout(navigate)} color='red'>
<Trans>Log off</Trans>
</Button>
</Stack>
</Container>
</Center>
</LanguageContext>
</Wrapper>
);
}

View File

@ -0,0 +1,27 @@
import { Trans, t } from '@lingui/macro';
import { Anchor, Text } from '@mantine/core';
import { useNavigate } from 'react-router-dom';
import { RegistrationForm } from '../../components/forms/AuthenticationForm';
import {} from '../../functions/auth';
import { Wrapper } from './Layout';
export default function Register() {
const navigate = useNavigate();
return (
<Wrapper titleText={t`Register`} smallPadding>
<RegistrationForm />
<Text ta='center' size={'xs'} mt={'md'}>
<Anchor
component='button'
type='button'
c='dimmed'
size='xs'
onClick={() => navigate('/login')}
>
<Trans>Go back to login</Trans>
</Anchor>
</Text>
</Wrapper>
);
}

View File

@ -1,31 +1,16 @@
import { Trans, t } from '@lingui/macro';
import {
Button,
Center,
Container,
Stack,
TextInput,
Title
} from '@mantine/core';
import { Button, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';
import { useNavigate } from 'react-router-dom';
import { LanguageContext } from '../../contexts/LanguageContext';
import { handleReset } from '../../functions/auth';
import { Wrapper } from './Layout';
export default function Reset() {
const simpleForm = useForm({ initialValues: { email: '' } });
const navigate = useNavigate();
return (
<LanguageContext>
<Center mih='100vh'>
<Container w='md' miw={425}>
<Stack>
<Title>
<Trans>Reset password</Trans>
</Title>
<Stack>
<Wrapper titleText={t`Reset Password`}>
<TextInput
required
label={t`Email`}
@ -33,16 +18,12 @@ export default function Reset() {
placeholder='email@example.org'
{...simpleForm.getInputProps('email')}
/>
</Stack>
<Button
type='submit'
onClick={() => handleReset(navigate, simpleForm.values)}
>
<Trans>Send Email</Trans>
</Button>
</Stack>
</Container>
</Center>
</LanguageContext>
</Wrapper>
);
}

View File

@ -1,114 +1,47 @@
import { Trans, t } from '@lingui/macro';
import {
Button,
Center,
Container,
PasswordInput,
Stack,
Title
} from '@mantine/core';
import { Button, PasswordInput } from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { api } from '../../App';
import { LanguageContext } from '../../contexts/LanguageContext';
import { ApiEndpoints } from '../../enums/ApiEndpoints';
import { apiUrl } from '../../states/ApiState';
import { handlePasswordReset } from '../../functions/auth';
import { Wrapper } from './Layout';
export default function ResetPassword() {
const simpleForm = useForm({ initialValues: { password: '' } });
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const key = searchParams.get('key');
function invalidKey() {
// make sure we have a key
useEffect(() => {
if (!key) {
notifications.show({
title: t`Key invalid`,
message: t`You need to provide a valid key to set a new password. Check your inbox for a reset link.`,
color: 'red'
});
navigate('/login');
}
function success() {
notifications.show({
title: t`Password set`,
message: t`The password was set successfully. You can now login with your new password`,
color: 'green',
color: 'red',
autoClose: false
});
navigate('/login');
}
function passwordError(values: any) {
notifications.show({
title: t`Reset failed`,
message: values?.errors.map((e: any) => e.message).join('\n'),
color: 'red'
});
}
useEffect(() => {
// make sure we have a key
if (!key) {
invalidKey();
}
}, [key]);
function handleSet() {
// Set password with call to backend
api
.post(
apiUrl(ApiEndpoints.user_reset_set),
{
key: key,
password: simpleForm.values.password
},
{ headers: { Authorization: '' } }
)
.then((val) => {
if (val.status === 200) {
success();
} else {
passwordError(val.data);
}
})
.catch((err) => {
if (err.response?.status === 400) {
passwordError(err.response.data);
} else if (err.response?.status === 401) {
success();
} else {
passwordError(err.response.data);
}
});
}
return (
<LanguageContext>
<Center mih='100vh'>
<Container w='md' miw={425}>
<Stack>
<Title>
<Trans>Set new password</Trans>
</Title>
<Stack>
<Wrapper titleText={t`Set new password`}>
<PasswordInput
required
label={t`Password`}
description={t`The desired new password`}
{...simpleForm.getInputProps('password')}
/>
</Stack>
<Button type='submit' onClick={handleSet}>
<Button
type='submit'
onClick={() =>
handlePasswordReset(key, simpleForm.values.password, navigate)
}
>
<Trans>Send Password</Trans>
</Button>
</Stack>
</Container>
</Center>
</LanguageContext>
</Wrapper>
);
}

View File

@ -1,19 +1,19 @@
import { Trans, t } from '@lingui/macro';
import { Button, Center, Container, Stack, Title } from '@mantine/core';
import { Button } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { api } from '../../App';
import { LanguageContext } from '../../contexts/LanguageContext';
import { ApiEndpoints } from '../../enums/ApiEndpoints';
import { apiUrl } from '../../states/ApiState';
import { handleVerifyEmail } from '../../functions/auth';
import { Wrapper } from './Layout';
export default function VerifyEmail() {
const { key } = useParams();
const navigate = useNavigate();
function invalidKey() {
// make sure we have a key
useEffect(() => {
if (!key) {
notifications.show({
title: t`Key invalid`,
message: t`You need to provide a valid key.`,
@ -21,41 +21,13 @@ export default function VerifyEmail() {
});
navigate('/login');
}
useEffect(() => {
// make sure we have a key
if (!key) {
invalidKey();
}
}, [key]);
function handleSet() {
// Set password with call to backend
api
.post(apiUrl(ApiEndpoints.auth_email_verify), {
key: key
})
.then((val) => {
if (val.status === 200) {
navigate('/login');
}
});
}
return (
<LanguageContext>
<Center mih='100vh'>
<Container w='md' miw={425}>
<Stack>
<Title>
<Trans>Verify Email</Trans>
</Title>
<Button type='submit' onClick={handleSet}>
<Wrapper titleText={t`Verify Email`}>
<Button type='submit' onClick={() => handleVerifyEmail(key, navigate)}>
<Trans>Verify</Trans>
</Button>
</Stack>
</Container>
</Center>
</LanguageContext>
</Wrapper>
);
}

View File

@ -107,7 +107,6 @@ function EmailSection() {
queryFn: () =>
authApi(apiUrl(ApiEndpoints.auth_email)).then((res) => res.data.data)
});
const emailAvailable = useMemo(() => {
return data == undefined || data.length == 0;
}, [data]);

View File

@ -7,6 +7,10 @@ import { Loadable } from './functions/loading';
export const LayoutComponent = Loadable(
lazy(() => import('./components/nav/Layout'))
);
export const LoginLayoutComponent = Loadable(
lazy(() => import('./pages/Auth/Layout'))
);
export const Home = Loadable(lazy(() => import('./pages/Index/Home')));
export const CompanyDetail = Loadable(
@ -103,17 +107,19 @@ export const AdminCenter = Loadable(
export const NotFound = Loadable(
lazy(() => import('./components/errors/NotFound'))
);
// Auth
export const Login = Loadable(lazy(() => import('./pages/Auth/Login')));
export const MFALogin = Loadable(lazy(() => import('./pages/Auth/MFALogin')));
export const MFASetup = Loadable(lazy(() => import('./pages/Auth/MFASetup')));
export const LoggedIn = Loadable(lazy(() => import('./pages/Auth/LoggedIn')));
export const Logout = Loadable(lazy(() => import('./pages/Auth/Logout')));
export const Logged_In = Loadable(lazy(() => import('./pages/Auth/Logged-In')));
export const Reset = Loadable(lazy(() => import('./pages/Auth/Reset')));
export const Register = Loadable(lazy(() => import('./pages/Auth/Register')));
export const Mfa = Loadable(lazy(() => import('./pages/Auth/MFA')));
export const MfaSetup = Loadable(lazy(() => import('./pages/Auth/MFASetup')));
export const ChangePassword = Loadable(
lazy(() => import('./pages/Auth/ChangePassword'))
);
export const Reset = Loadable(lazy(() => import('./pages/Auth/Reset')));
export const ResetPassword = Loadable(
lazy(() => import('./pages/Auth/ResetPassword'))
);
@ -173,16 +179,20 @@ export const routes = (
<Route path='customer/:id/*' element={<CustomerDetail />} />
</Route>
</Route>
<Route path='/' errorElement={<ErrorPage />}>
<Route
path='/'
element={<LoginLayoutComponent />}
errorElement={<ErrorPage />}
>
<Route path='/login' element={<Login />} />,
<Route path='/register' element={<Login />} />,
<Route path='/mfa' element={<MFALogin />} />,
<Route path='/mfa-setup' element={<MFASetup />} />,
<Route path='/logged-in' element={<LoggedIn />} />
<Route path='/logout' element={<Logout />} />,
<Route path='/logged-in' element={<Logged_In />} />
<Route path='/register' element={<Register />} />,
<Route path='/mfa' element={<Mfa />} />,
<Route path='/mfa-setup' element={<MfaSetup />} />,
<Route path='/change-password' element={<ChangePassword />} />
<Route path='/reset-password' element={<Reset />} />
<Route path='/set-password' element={<ResetPassword />} />
<Route path='/change-password' element={<ChangePassword />} />
<Route path='/verify-email/:key' element={<VerifyEmail />} />
</Route>
</Routes>

View File

@ -13,7 +13,7 @@ test('Settings - Language / Color', async ({ page }) => {
await page.getByRole('button', { name: 'Ally Access' }).click();
await page.getByRole('menuitem', { name: 'Logout' }).click();
await page.getByRole('button', { name: 'Send me an email' }).click();
await page.getByRole('button').nth(3).click();
await page.getByLabel('Language toggle').click();
await page.getByLabel('Select language').first().click();
await page.getByRole('option', { name: 'German' }).click();
await page.waitForTimeout(200);