()
| 22 | } |
| 23 | |
| 24 | const useAuth = () => { |
| 25 | const { t } = useTranslation() |
| 26 | const [error, setError] = useState<string | null>(null) |
| 27 | const navigate = useNavigate() |
| 28 | const queryClient = useQueryClient() |
| 29 | const { isGuest, isLoggedIn, logout } = useAuthContext() |
| 30 | const { data: user, isLoading } = useQuery<UserPublic | null, Error>({ |
| 31 | queryKey: ['currentUser'], |
| 32 | queryFn: UsersService.readUserMe, |
| 33 | enabled: isLoggedIn && !isGuest, |
| 34 | }) |
| 35 | |
| 36 | const signUpMutation = useMutation({ |
| 37 | mutationFn: (data: UserRegister) => UsersService.registerUser({ requestBody: data }), |
| 38 | |
| 39 | onSuccess: () => { |
| 40 | navigate({ to: '/login' }) |
| 41 | toaster.create({ |
| 42 | title: t('hooks.auth.accountCreated'), |
| 43 | description: t('hooks.auth.accountCreatedDescription'), |
| 44 | type: 'success', |
| 45 | }) |
| 46 | }, |
| 47 | onError: (err: Error | AxiosError | ErrorResponse) => { |
| 48 | const errDetail = |
| 49 | err instanceof AxiosError |
| 50 | ? err.message |
| 51 | : 'body' in err && typeof err.body === 'object' && err.body |
| 52 | ? String(err.body.detail) || t('general.errors.somethingWentWrong') |
| 53 | : t('general.errors.somethingWentWrong') |
| 54 | toaster.create({ |
| 55 | title: t('general.errors.errorCreatingAccount'), |
| 56 | description: errDetail, |
| 57 | type: 'error', |
| 58 | }) |
| 59 | const status = (err as AxiosError).status ?? (err as ErrorResponse).status |
| 60 | if (status === 409) { |
| 61 | setError(t('general.errors.emailAlreadyInUse') || t('general.errors.somethingWentWrong')) |
| 62 | } else { |
| 63 | setError(errDetail) |
| 64 | } |
| 65 | }, |
| 66 | onSettled: () => { |
| 67 | queryClient.invalidateQueries({ queryKey: ['users'] }) |
| 68 | }, |
| 69 | }) |
| 70 | |
| 71 | const login = async (data: AccessToken) => { |
| 72 | const response = await LoginService.loginAccessToken({ |
| 73 | formData: data, |
| 74 | }) |
| 75 | localStorage.setItem('access_token', response.access_token) |
| 76 | } |
| 77 | |
| 78 | const loginMutation = useMutation({ |
| 79 | mutationFn: login, |
| 80 | onSuccess: () => { |
| 81 | navigate({ to: '/collections' }) |
no test coverage detected