Skip to content

Commit

Permalink
[245] Improve the reusability of the code
Browse files Browse the repository at this point in the history
Bug: #245
Signed-off-by: Stéphane Bégaudeau <[email protected]>
  • Loading branch information
sbegaudeau committed Sep 8, 2023
1 parent a2e728e commit cd71ba8
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 32 deletions.
24 changes: 4 additions & 20 deletions frontend/svalyn-studio-app/src/login/LoginWithCredentials.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,9 @@ import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { getCookie } from '../cookies/getCookie';
import { hasMinLength, useForm } from '../forms/useForm';
import { LoginWithCredentialsFormData } from './LoginWithCredentials.types';

const { VITE_BACKEND_URL } = import.meta.env;
import { useAuthentication } from './useAuthentication';

export const LoginWithCredentials = () => {
const { data, isFormValid, getTextFieldProps } = useForm<LoginWithCredentialsFormData>({
Expand All @@ -43,27 +41,13 @@ export const LoginWithCredentials = () => {
});

const { enqueueSnackbar } = useSnackbar();

const navigate = useNavigate();
const { login } = useAuthentication();

const handleLogin: React.FormEventHandler<HTMLFormElement> = (event) => {
event.preventDefault();

const body = new FormData();
body.append('username', data.username);
body.append('password', data.password);
body.append('remember-me', 'true');

const csrfToken = getCookie('XSRF-TOKEN');

fetch(`${VITE_BACKEND_URL}/api/login`, {
body,
mode: 'cors',
credentials: 'include',
method: 'POST',
headers: {
'X-XSRF-TOKEN': csrfToken,
},
}).then((response) => {
login(data.username, data.password).then((response) => {
if (response.ok) {
navigate('/');
} else {
Expand Down
62 changes: 62 additions & 0 deletions frontend/svalyn-studio-app/src/login/useAuthentication.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2023 Stéphane Bégaudeau.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { getCookie } from '../cookies/getCookie';
import { UseAuthenticationValue } from './useAuthentication.types';

const { VITE_BACKEND_URL } = import.meta.env;

export const useAuthentication = (): UseAuthenticationValue => {
const login = (username: string, password: string) => {
const body = new FormData();
body.append('username', username);
body.append('password', password);
body.append('remember-me', 'true');

const csrfToken = getCookie('XSRF-TOKEN');

return fetch(`${VITE_BACKEND_URL}/api/login`, {
body,
mode: 'cors',
credentials: 'include',
method: 'POST',
headers: {
'X-XSRF-TOKEN': csrfToken,
},
});
};

const logout = () => {
const csrfToken = getCookie('XSRF-TOKEN');

return fetch(`${VITE_BACKEND_URL}/api/logout`, {
method: 'POST',
credentials: 'include',
mode: 'cors',
headers: {
'X-XSRF-TOKEN': csrfToken,
},
});
};

return {
login,
logout,
};
};
23 changes: 23 additions & 0 deletions frontend/svalyn-studio-app/src/login/useAuthentication.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright (c) 2023 Stéphane Bégaudeau.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

export interface UseAuthenticationValue {
login(username: string, password: string): Promise<Response>;
logout(): Promise<Response>;
}
15 changes: 3 additions & 12 deletions frontend/svalyn-studio-app/src/navbars/UserMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import { useState } from 'react';
import { Navigate, Link as RouterLink } from 'react-router-dom';
import { getCookie } from '../cookies/getCookie';
import { useAuthentication } from '../login/useAuthentication';
import { UserMenuProps, UserMenuState } from './UserMenu.types';
const { VITE_BACKEND_URL } = import.meta.env;

export const UserMenu = ({ viewer, onClose, ...props }: UserMenuProps) => {
const [state, setState] = useState<UserMenuState>({
Expand All @@ -47,17 +46,9 @@ export const UserMenu = ({ viewer, onClose, ...props }: UserMenuProps) => {
}
};

const { logout } = useAuthentication();
const handleLogout: React.MouseEventHandler<HTMLLIElement> = () => {
const csrfToken = getCookie('XSRF-TOKEN');

fetch(`${VITE_BACKEND_URL}/api/logout`, {
method: 'POST',
credentials: 'include',
mode: 'cors',
headers: {
'X-XSRF-TOKEN': csrfToken,
},
}).then(() => {
logout().then(() => {
setState((prevState) => ({ ...prevState, redirectToLogin: true }));
});
};
Expand Down

0 comments on commit cd71ba8

Please sign in to comment.