Refactor login and register code

1. Abandoned try catch statement and use axios promise chains for handling the errors.
Avoided duplicated error handling logic for the same action
2. Removed unneeded useEffect in the input components
3. Refactor some code in the input components for better readability

Change-Id: I420ce4025a00cb842c743cb001983338d0359f46
diff --git a/client/src/components/Input.tsx b/client/src/components/Input.tsx
index 12b468b..ddc09af 100644
--- a/client/src/components/Input.tsx
+++ b/client/src/components/Input.tsx
@@ -19,7 +19,7 @@
 import Warning from '@mui/icons-material/Warning';
 import { IconButtonProps, Stack, TextField, TextFieldProps } from '@mui/material';
 import { styled } from '@mui/material/styles';
-import { ChangeEvent, ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
+import { ChangeEvent, useCallback, useEffect, useMemo, useState } from 'react';
 import { useTranslation } from 'react-i18next';
 
 import { StrengthValueCode } from '../utils/auth';
@@ -41,51 +41,37 @@
 const StyledPersonIconLight = styled(PersonIcon)({ height: iconsHeight, color: '#03B9E9' });
 const StyledLockIcon = styled(LockIcon)({ height: iconsHeight, color: '#03B9E9' });
 
-export type NameStatus = 'default' | 'success' | 'taken' | 'invalid' | 'registration_failed';
+export type NameStatus = 'default' | 'success' | 'taken' | 'valid' | 'invalid' | 'registration_failed';
 export type PasswordStatus = StrengthValueCode | 'registration_failed';
 
 export type InputProps<StatusType extends NameStatus | PasswordStatus> = TextFieldProps & {
   status?: StatusType;
   infoButtonProps?: IconButtonProps;
-  success?: boolean;
   tooltipTitle: string;
 };
 
 export const UsernameInput = ({
   infoButtonProps,
-  onChange: _onChange,
-  success,
   status = 'default',
   tooltipTitle,
   ...props
 }: InputProps<NameStatus>) => {
   const { t } = useTranslation();
   const [isSelected, setIsSelected] = useState(false);
-  const [input, setInput] = useState(props.defaultValue);
-  const [startAdornment, setStartAdornment] = useState<ReactElement | undefined>();
   const dialogHandler = useDialogHandler();
 
-  const onChange = useCallback(
-    (event: ChangeEvent<HTMLInputElement>) => {
-      setInput(event.target.value);
-      _onChange?.(event);
-    },
-    [_onChange]
-  );
+  const usernameError = status === 'taken' || status === 'invalid' || status === 'registration_failed';
+  const usernameSuccess = status === 'success';
 
-  useEffect(() => {
-    /* Handle startAdornment */
-    let Icon = StyledPersonIconLight;
-    let visibility = 'visible';
-    if (props.error) {
-      Icon = StyledRoundSaltireIconError;
-    } else if (success) {
-      Icon = StyledCheckedIconSuccess;
-    } else if (!isSelected && !input) {
-      visibility = 'hidden'; // keep icon's space so text does not move
-    }
-    setStartAdornment(<Icon sx={{ visibility }} />);
-  }, [props.error, success, isSelected, input]);
+  let StartAdornmentIcon = StyledPersonIconLight;
+  let visibility = 'visible';
+  if (usernameError) {
+    StartAdornmentIcon = StyledRoundSaltireIconError;
+  } else if (usernameSuccess) {
+    StartAdornmentIcon = StyledCheckedIconSuccess;
+  } else if (!isSelected && !props.value) {
+    visibility = 'hidden'; // keep icon's space so text does not move
+  }
 
   /*
   t('username_input_helper_text_success')
@@ -99,20 +85,20 @@
     <>
       <InfosDialog {...dialogHandler.props} title={t('username_rules_dialog_title')} content={<UsernameRules />} />
       <TextField
-        color={inputColor(props.error, success)}
+        required
+        error={usernameError}
         label={t('username_input_label')}
         variant="standard"
         helperText={status !== 'default' ? helperText : ''}
-        onChange={onChange}
         onFocus={() => setIsSelected(true)}
         onBlur={() => setIsSelected(false)}
         {...props}
         InputLabelProps={{
-          shrink: !!(isSelected || input),
+          shrink: !!(isSelected || props.value),
           ...props.InputLabelProps,
         }}
         InputProps={{
-          startAdornment,
+          startAdornment: <StartAdornmentIcon sx={{ visibility }} />,
           endAdornment: (
             <InfoButton
               tabIndex={-1}
@@ -130,44 +116,31 @@
 
 export const PasswordInput = ({
   infoButtonProps,
-  onChange: _onChange,
-  success,
-  tooltipTitle,
   status = 'default',
+  tooltipTitle,
   ...props
 }: InputProps<PasswordStatus>) => {
   const { t } = useTranslation();
   const [showPassword, setShowPassword] = useState(false);
   const [isSelected, setIsSelected] = useState(false);
-  const [input, setInput] = useState(props.defaultValue);
-  const [startAdornment, setStartAdornment] = useState<ReactElement | undefined>();
   const dialogHandler = useDialogHandler();
 
+  const passwordError = status !== 'strong' && status !== 'default';
+  const passwordSuccess = status === 'strong';
+
   const toggleShowPassword = () => {
     setShowPassword((showPassword) => !showPassword);
   };
 
-  const onChange = useCallback(
-    (event: ChangeEvent<HTMLInputElement>) => {
-      setInput(event.target.value);
-      _onChange?.(event);
-    },
-    [_onChange]
-  );
-
-  useEffect(() => {
-    /* Handle startAdornment */
-    let Icon = StyledLockIcon;
-    let visibility = 'visible';
-    if (props.error) {
-      Icon = StyledRoundSaltireIconError;
-    } else if (success) {
-      Icon = StyledCheckedIconSuccess;
-    } else if (!isSelected && !input) {
-      visibility = 'hidden'; // keep icon's space so text does not move
-    }
-    setStartAdornment(<Icon sx={{ visibility }} />);
-  }, [props.error, success, isSelected, input]);
+  let StartAdornmentIcon = StyledLockIcon;
+  let StartAdornmentIconVisibility = 'visible';
+  if (passwordError) {
+    StartAdornmentIcon = StyledRoundSaltireIconError;
+  } else if (passwordSuccess) {
+    StartAdornmentIcon = StyledCheckedIconSuccess;
+  } else if (!isSelected && !props.value) {
+    StartAdornmentIconVisibility = 'hidden'; // keep icon's space so text does not move
+  }
 
   /*
   t('password_input_helper_text_too_weak')
@@ -182,19 +155,18 @@
     <>
       <InfosDialog {...dialogHandler.props} title={t('password_rules_dialog_title')} content={<PasswordRules />} />
       <TextField
-        color={inputColor(props.error, success)}
+        required
         label={t('password_input_label')}
         type={showPassword ? 'text' : 'password'}
         variant="standard"
         autoComplete="current-password"
         helperText={status !== 'default' ? helperText : ''}
-        onChange={onChange}
         onFocus={() => setIsSelected(true)}
         onBlur={() => setIsSelected(false)}
         {...props}
-        InputLabelProps={{ shrink: !!(isSelected || input), ...props.InputLabelProps }}
+        InputLabelProps={{ shrink: !!(isSelected || props.value), ...props.InputLabelProps }}
         InputProps={{
-          startAdornment,
+          startAdornment: <StartAdornmentIcon sx={{ visibility: StartAdornmentIconVisibility }} />,
           endAdornment: (
             <Stack direction="row" spacing="14px" alignItems="center">
               <InfoButton tooltipTitle={tooltipTitle} {...infoButtonProps} onClick={dialogHandler.openDialog} />
@@ -208,6 +180,7 @@
   );
 };
 
+//this component is not used anywhere
 export const NickNameInput = ({ onChange: _onChange, ...props }: TextFieldProps) => {
   const [isSelected, setIsSelected] = useState(false);
   const [input, setInput] = useState(props.defaultValue);
@@ -241,6 +214,7 @@
   );
 };
 
+//this component is not used anywhere
 export const RegularInput = ({ onChange: _onChange, ...props }: TextFieldProps) => {
   const [isSelected, setIsSelected] = useState(false);
   const [input, setInput] = useState(props.defaultValue);
@@ -276,12 +250,13 @@
   );
 };
 
-function inputColor(
-  error?: boolean,
-  success?: boolean
-): 'success' | 'error' | 'primary' | 'secondary' | 'info' | 'warning' | undefined {
-  return error ? 'error' : success ? 'success' : 'primary';
-}
+//this was used for altering the color of input fields, but somehow it didn't work at all. Only the `error` prop of the input is taking effect
+// function inputColor(
+//   error?: boolean,
+//   success?: boolean
+// ): 'success' | 'error' | 'primary' | 'secondary' | 'info' | 'warning' | undefined {
+//   return error ? 'error' : success ? 'success' : 'primary';
+// }
 
 const PasswordRules = () => {
   const { t } = useTranslation();
diff --git a/client/src/pages/Login.tsx b/client/src/pages/Login.tsx
index 193497b..f0cd005 100644
--- a/client/src/pages/Login.tsx
+++ b/client/src/pages/Login.tsx
@@ -27,6 +27,7 @@
   useMediaQuery,
 } from '@mui/material';
 import { Theme, useTheme } from '@mui/material/styles';
+import { HttpStatusCode } from 'jami-web-common';
 import { ChangeEvent, FormEvent, ReactNode, useState } from 'react';
 import { useTranslation } from 'react-i18next';
 import { Form, Link, useNavigate } from 'react-router-dom';
@@ -37,8 +38,6 @@
 import withAuthUI from '../components/WithAuthUI';
 import { loginUser, setAccessToken } from '../utils/auth';
 import { inputWidth } from '../utils/constants';
-import { InvalidPassword, UsernameNotFound } from '../utils/errors';
-
 function LoginForm() {
   const theme: Theme = useTheme();
   const navigate = useNavigate();
@@ -47,8 +46,9 @@
   const [username, setUsername] = useState<string>('');
   const [password, setPassword] = useState<string>('');
   const [isJams, setIsJams] = useState<boolean>(false);
-  const [isLoggingInUser, setIsLoggingInUser] = useState<boolean>(false);
+  const [loading, setLoading] = useState<boolean>(false);
   const [errorAlertContent, setErrorAlertContent] = useState<ReactNode>(undefined);
+  const isMobile: boolean = useMediaQuery(theme.breakpoints.only('xs'));
 
   const handleUsername = (event: ChangeEvent<HTMLInputElement>) => {
     setUsername(event.target.value);
@@ -62,33 +62,49 @@
     setIsJams(event.target.value === 'true');
   };
 
-  const authenticateUser = async (event: FormEvent) => {
+  const login = async (event: FormEvent) => {
     event.preventDefault();
-    if (username.length > 0 && password.length > 0) {
-      setIsLoggingInUser(true);
 
-      try {
-        const accessToken = await loginUser(username, password, isJams);
-        setAccessToken(accessToken);
-        navigate('/conversation', { replace: true });
-      } catch (e) {
-        setIsLoggingInUser(false);
-        if (e instanceof UsernameNotFound) {
-          setErrorAlertContent(t('login_username_not_found'));
-        } else if (e instanceof InvalidPassword) {
+    if (!(username.length > 0) || !(password.length > 0)) {
+      //TODO: set alert message
+      console.log('Empty Credentials');
+      return;
+    }
+
+    setLoading(true);
+
+    loginUser(username, password, isJams)
+      .then((response) => {
+        if (response.status === HttpStatusCode.Ok) {
+          setAccessToken(response.data.accessToken);
+          navigate('/conversation', { replace: true });
+        }
+      })
+      .catch((e) => {
+        console.log(e);
+        const { status } = e.response;
+        if (status === HttpStatusCode.BadRequest) {
+          //TODO: the only bad request response defined in the server is missing credentials. add the response message to the locale.
+          console.log(e.response.data);
+          // setErrorAlertContent(t('unknown_error_alert'));
+        } else if (status === HttpStatusCode.NotFound) {
+          //TODO: there are two different not found responses that could be returned by the server, use message to differentiate them?
+          console.log(e.response.data);
+          // setErrorAlertContent(t('login_username_not_found'));
+        } else if (status === HttpStatusCode.Unauthorized) {
           setErrorAlertContent(t('login_invalid_password'));
         } else {
           setErrorAlertContent(t('unknown_error_alert'));
         }
-      }
-    }
+      })
+      .finally(() => {
+        setLoading(false);
+      });
   };
 
-  const isMobile: boolean = useMediaQuery(theme.breakpoints.only('xs'));
-
   return (
     <>
-      <ProcessingRequest open={isLoggingInUser} />
+      <ProcessingRequest open={loading} />
 
       <AlertSnackbar severity={'error'} open={!!errorAlertContent} onClose={() => setErrorAlertContent(undefined)}>
         {errorAlertContent}
@@ -111,6 +127,7 @@
         <Form method="post" id="login-form">
           <div>
             <UsernameInput
+              value={username}
               onChange={handleUsername}
               tooltipTitle={t('login_form_username_tooltip')}
               sx={{ width: theme.typography.pxToRem(inputWidth) }}
@@ -118,6 +135,7 @@
           </div>
           <div>
             <PasswordInput
+              value={password}
               onChange={handlePassword}
               tooltipTitle={t('login_form_password_tooltip')}
               sx={{ width: theme.typography.pxToRem(inputWidth) }}
@@ -141,7 +159,7 @@
           <Button
             variant="contained"
             type="submit"
-            onClick={authenticateUser}
+            onClick={login}
             sx={{ width: theme.typography.pxToRem(inputWidth), mt: theme.typography.pxToRem(20) }}
           >
             {t('login_form_submit_button')}
diff --git a/client/src/pages/Registration.tsx b/client/src/pages/Registration.tsx
index 50686f5..e85136a 100644
--- a/client/src/pages/Registration.tsx
+++ b/client/src/pages/Registration.tsx
@@ -27,6 +27,7 @@
   useMediaQuery,
 } from '@mui/material';
 import { Theme, useTheme } from '@mui/material/styles';
+import { HttpStatusCode } from 'jami-web-common';
 import { ChangeEvent, FormEvent, ReactNode, useEffect, useState } from 'react';
 import { useTranslation } from 'react-i18next';
 import { Form, Link, useNavigate } from 'react-router-dom';
@@ -35,20 +36,24 @@
 import { NameStatus, PasswordInput, PasswordStatus, UsernameInput } from '../components/Input';
 import ProcessingRequest from '../components/ProcessingRequest';
 import withAuthUI from '../components/WithAuthUI';
-import { checkPasswordStrength, isNameRegistered, loginUser, registerUser, setAccessToken } from '../utils/auth';
+import {
+  checkIfUserameIsRegistered,
+  checkPasswordStrength,
+  loginUser,
+  registerUser,
+  setAccessToken,
+} from '../utils/auth';
 import { inputWidth, jamiUsernamePattern } from '../utils/constants';
-import { InvalidCredentials, InvalidPassword, UsernameNotFound } from '../utils/errors';
-
 function RegistrationForm() {
   const theme: Theme = useTheme();
   const navigate = useNavigate();
   const { t } = useTranslation();
 
-  const [isCreatingUser, setIsCreatingUser] = useState(false);
+  const [loading, setLoading] = useState(false);
 
-  const [username, setUsername] = useState('');
-  const [password, setPassword] = useState('');
-  const [isJams, setIsJams] = useState(false);
+  const [username, setUsername] = useState<string>('');
+  const [password, setPassword] = useState<string>('');
+  const [isJams, setIsJams] = useState<boolean>(false);
 
   const [usernameStatus, setUsernameStatus] = useState<NameStatus>('default');
   const [passwordStatus, setPasswordStatus] = useState<PasswordStatus>('default');
@@ -56,72 +61,120 @@
   const [errorAlertContent, setErrorAlertContent] = useState<ReactNode>(undefined);
   const [successAlertContent, setSuccessAlertContent] = useState<ReactNode>(undefined);
 
-  const usernameError = usernameStatus !== 'success' && usernameStatus !== 'default';
-  const usernameSuccess = usernameStatus === 'success';
-  const passwordError = passwordStatus !== 'strong' && passwordStatus !== 'default';
-  const passwordSuccess = passwordStatus === 'strong';
+  const isMobile: boolean = useMediaQuery(theme.breakpoints.only('xs'));
 
   useEffect(() => {
-    // To prevent lookup if field is empty, in error state or lookup already done
-    if (username.length > 0 && usernameStatus === 'default') {
-      const validateUsername = async () => {
-        if (await isNameRegistered(username)) {
-          setUsernameStatus('taken');
-        } else {
-          setUsernameStatus('success');
+    let timetoutId: ReturnType<typeof setTimeout>;
+    if (usernameStatus === 'valid') {
+      timetoutId = setTimeout(() => {
+        // useCheckIfUsernameIsRegisteredMutation.mutate(username);
+        checkIfUserameIsRegistered(username)
+          .then((response) => {
+            //server responds 200 if name IS found
+            if (response.status === HttpStatusCode.Ok) {
+              setUsernameStatus('taken');
+            }
+          })
+          .catch((e) => {
+            // console.log(e.response.data);
+            const { status } = e.response;
+            if (status === HttpStatusCode.BadRequest) {
+              //TODO: server sends invalid username as the message, add it to the locale
+              // console.log(e.response.data);
+              setUsernameStatus('invalid');
+            } else if (status === HttpStatusCode.NotFound) {
+              //TODO: server didn't find this username, therefore it can be registered, add the message to the locale
+              // console.log(e.response.data);
+              setUsernameStatus('success');
+            } else {
+              setErrorAlertContent(t('unknown_error_alert'));
+            }
+          });
+      }, 1000);
+    }
+
+    return () => {
+      clearTimeout(timetoutId);
+    };
+  }, [t, username, usernameStatus]);
+
+  const login = async () => {
+    setLoading(true);
+    loginUser(username, password, isJams)
+      .then((response) => {
+        if (response.status === HttpStatusCode.Ok) {
+          setAccessToken(response.data.accessToken);
+          navigate('/conversation', { replace: true });
         }
-      };
-      const timeout = setTimeout(validateUsername, 1000);
-
-      return () => clearTimeout(timeout);
-    }
-  }, [username, usernameStatus]);
-
-  const firstUserLogin = async () => {
-    try {
-      const accessToken = await loginUser(username, password, isJams);
-      setAccessToken(accessToken);
-      navigate('/conversation', { replace: true });
-    } catch (e) {
-      setIsCreatingUser(false);
-      if (e instanceof UsernameNotFound) {
-        setErrorAlertContent(t('login_username_not_found'));
-      } else if (e instanceof InvalidPassword) {
-        setErrorAlertContent(t('login_invalid_password'));
-      } else {
-        setErrorAlertContent(t('unknown_error_alert'));
-      }
-    }
+      })
+      .catch((e) => {
+        console.log(e);
+        const { status } = e.response;
+        if (status === HttpStatusCode.BadRequest) {
+          //TODO: the only bad request response defined in the server is missing credentials. add the response message to the locale.
+          console.log(e.response.data);
+          setErrorAlertContent(t('unknown_error_alert'));
+        } else if (status === HttpStatusCode.NotFound) {
+          //TODO: there are two different not found responses that could be returned by the server, use message to differentiate them?
+          console.log(e.response.data);
+          // setErrorAlertContent(t('login_username_not_found'));
+        } else if (status === HttpStatusCode.Unauthorized) {
+          setErrorAlertContent(t('login_invalid_password'));
+        } else {
+          setErrorAlertContent(t('unknown_error_alert'));
+        }
+      })
+      .finally(() => {
+        setLoading(false);
+      });
   };
 
-  const createAccount = async () => {
-    try {
-      await registerUser(username, password, isJams);
-      setSuccessAlertContent(t('registration_success'));
-      await firstUserLogin();
-    } catch (e) {
-      setIsCreatingUser(false);
-      if (e instanceof UsernameNotFound) {
-        setErrorAlertContent(t('login_username_not_found'));
-      } else if (e instanceof InvalidPassword) {
-        setErrorAlertContent(t('login_invalid_password'));
-      } else if (e instanceof InvalidCredentials) {
-        setErrorAlertContent(t('login_invalid_credentials'));
-      } else {
-        setErrorAlertContent(t('unknown_error_alert'));
-      }
-    }
+  const createAccount = () => {
+    setLoading(true);
+    registerUser(username, password, isJams)
+      .then((response) => {
+        if (response.status === HttpStatusCode.Created) {
+          setSuccessAlertContent(t('registration_success'));
+          login();
+        }
+      })
+      .catch((e) => {
+        console.log(e);
+        const { status } = e.response;
+        if (status === HttpStatusCode.BadRequest) {
+          //TODO: more than one bad request response defined in the server is missing credentials. add the response message to the locale.
+          console.log(e.response.data);
+          // setErrorAlertContent(t('unknown_error_alert'));
+        } else if (status === HttpStatusCode.Conflict) {
+          //TODO: there are two different conflict responses that could be returned by the server, use message to differentiate them?
+          console.log(e.response.data);
+          // setErrorAlertContent(t('login_username_not_found'));
+        } else if (status === HttpStatusCode.Unauthorized) {
+          //TODO: this is a response for JAMS, add message to the locale
+        } else {
+          setErrorAlertContent(t('unknown_error_alert'));
+        }
+      })
+      .finally(() => {
+        setLoading(false);
+      });
   };
 
   const handleUsername = async (event: ChangeEvent<HTMLInputElement>) => {
     const usernameValue: string = event.target.value;
     setUsername(usernameValue);
 
-    if (usernameValue.length > 0 && !jamiUsernamePattern.test(usernameValue)) {
-      setUsernameStatus('invalid');
-    } else {
+    if (usernameValue === '') {
       setUsernameStatus('default');
+      return;
     }
+
+    if (!jamiUsernamePattern.test(usernameValue)) {
+      setUsernameStatus('invalid');
+      return;
+    }
+    //The valid state is when the username passes the Regex test and is ready for availability check.
+    setUsernameStatus('valid');
   };
 
   const handlePassword = (event: ChangeEvent<HTMLInputElement>) => {
@@ -137,31 +190,31 @@
   };
 
   const handleIsJams = (event: ChangeEvent<HTMLInputElement>) => {
-    setIsJams(event.target.value === 'true');
+    setIsJams(event.target.value === 'jams');
   };
 
   const handleSubmit = async (event: FormEvent) => {
     event.preventDefault();
-    const canCreate = usernameSuccess && passwordSuccess;
+    const usernameOk = usernameStatus === 'success';
+    const passwordOk = passwordStatus === 'strong';
+
+    const canCreate = usernameOk && passwordOk;
 
     if (canCreate) {
-      setIsCreatingUser(true);
-      await createAccount();
+      createAccount();
     } else {
-      if (usernameError || username.length === 0) {
+      if (!usernameOk) {
         setUsernameStatus('registration_failed');
       }
-      if (!passwordSuccess) {
+      if (!passwordOk) {
         setPasswordStatus('registration_failed');
       }
     }
   };
 
-  const isMobile: boolean = useMediaQuery(theme.breakpoints.only('xs'));
-
   return (
     <>
-      <ProcessingRequest open={isCreatingUser} />
+      <ProcessingRequest open={loading} />
 
       <AlertSnackbar
         severity={'success'}
@@ -194,22 +247,18 @@
             <UsernameInput
               value={username}
               onChange={handleUsername}
-              error={usernameError}
-              success={usernameSuccess}
               status={usernameStatus}
-              sx={{ width: theme.typography.pxToRem(inputWidth) }}
               tooltipTitle={t('registration_form_username_tooltip')}
+              sx={{ width: theme.typography.pxToRem(inputWidth) }}
             />
           </div>
           <div>
             <PasswordInput
               value={password}
               onChange={handlePassword}
-              error={passwordError}
-              success={passwordSuccess}
               status={passwordStatus}
-              sx={{ width: theme.typography.pxToRem(inputWidth) }}
               tooltipTitle={t('registration_form_password_tooltip')}
+              sx={{ width: theme.typography.pxToRem(inputWidth) }}
             />
           </div>
           <div>
@@ -220,9 +269,9 @@
                 justifyContent: 'space-between',
               }}
             >
-              <RadioGroup row onChange={handleIsJams} value={isJams}>
-                <FormControlLabel value="false" control={<Radio />} label={t('jami')} />
-                <FormControlLabel value="true" control={<Radio />} label={t('jams')} />
+              <RadioGroup row onChange={handleIsJams} defaultValue="jami">
+                <FormControlLabel value="jami" control={<Radio />} label={t('jami')} />
+                <FormControlLabel value="jams" control={<Radio />} label={t('jams')} />
               </RadioGroup>
             </FormControl>
           </div>
diff --git a/client/src/utils/auth.ts b/client/src/utils/auth.ts
index 07797a4..9adde32 100644
--- a/client/src/utils/auth.ts
+++ b/client/src/utils/auth.ts
@@ -17,11 +17,10 @@
  */
 import axios from 'axios';
 import { passwordStrength } from 'check-password-strength';
-import { AccessToken, HttpStatusCode } from 'jami-web-common';
+import { AccessToken } from 'jami-web-common';
 
 import { PasswordStrength } from '../enums/passwordStrength';
 import { apiUrl } from './constants';
-import { InvalidCredentials, InvalidPassword, UsernameNotFound } from './errors';
 
 interface PasswordStrengthResult {
   id: number;
@@ -40,16 +39,8 @@
 
 const idToStrengthValueCode: StrengthValueCode[] = ['too_weak', 'weak', 'medium', 'strong'];
 
-export async function isNameRegistered(name: string): Promise<boolean> {
-  try {
-    await axios.get(`/ns/username/${name}`, { baseURL: apiUrl });
-    return true;
-  } catch (e: any) {
-    if (e.response?.status !== HttpStatusCode.NotFound) {
-      throw e;
-    }
-    return false;
-  }
+export function checkIfUserameIsRegistered(username: string) {
+  return axios.get(`/ns/username/${username}`, { baseURL: apiUrl });
 }
 
 export function checkPasswordStrength(password: string): PasswordCheckResult {
@@ -61,32 +52,12 @@
   };
 }
 
-export async function registerUser(username: string, password: string, isJams: boolean): Promise<void> {
-  try {
-    await axios.post('/auth/new-account', { username, password, isJams }, { baseURL: apiUrl });
-  } catch (e: any) {
-    if (e.response?.status === HttpStatusCode.Unauthorized) {
-      throw new InvalidCredentials();
-    } else {
-      throw e;
-    }
-  }
+export async function registerUser(username: string, password: string, isJams: boolean) {
+  return axios.post('/auth/new-account', { username, password, isJams }, { baseURL: apiUrl });
 }
 
-export async function loginUser(username: string, password: string, isJams: boolean): Promise<string> {
-  try {
-    const { data } = await axios.post<AccessToken>('/auth/login', { username, password, isJams }, { baseURL: apiUrl });
-    return data.accessToken;
-  } catch (e: any) {
-    switch (e.response?.status) {
-      case HttpStatusCode.NotFound:
-        throw new UsernameNotFound();
-      case HttpStatusCode.Unauthorized:
-        throw new InvalidPassword();
-      default:
-        throw e;
-    }
-  }
+export async function loginUser(username: string, password: string, isJams: boolean) {
+  return axios.post<AccessToken>('/auth/login', { username, password, isJams }, { baseURL: apiUrl });
 }
 
 export function getAccessToken(): string | undefined {
diff --git a/server/src/routers/auth-router.ts b/server/src/routers/auth-router.ts
index 74fc1f5..736bfc2 100644
--- a/server/src/routers/auth-router.ts
+++ b/server/src/routers/auth-router.ts
@@ -104,7 +104,7 @@
       return;
     }
 
-    // Check if the account is stored stored on this daemon instance
+    // Check if the account is stored on this daemon instance
     const accountId = jamid.getAccountIdFromUsername(username);
     if (accountId === undefined) {
       res.status(HttpStatusCode.NotFound).send('Username not found');
@@ -126,6 +126,6 @@
     }
 
     const jwt = await signJwt(accountId);
-    res.send({ accessToken: jwt });
+    res.status(HttpStatusCode.Ok).send({ accessToken: jwt });
   })
 );
diff --git a/server/src/routers/nameserver-router.ts b/server/src/routers/nameserver-router.ts
index 415c2d1..e0f27e9 100644
--- a/server/src/routers/nameserver-router.ts
+++ b/server/src/routers/nameserver-router.ts
@@ -35,7 +35,7 @@
     const result = await jamid.lookupUsername(req.params.username, res.locals.accountId);
     switch (result.state) {
       case RegisteredNameFoundState.Found:
-        res.send(result);
+        res.status(HttpStatusCode.Ok).send(result);
         break;
       case RegisteredNameFoundState.InvalidResponse:
         res.status(HttpStatusCode.BadRequest).send('Invalid username');