All files / app/src/entities/viewer/lib use-sign-in.ts

7.69% Statements 2/26
100% Branches 0/0
0% Functions 0/1
7.69% Lines 2/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371x                 1x                                                      
import { useEffect } from 'react'
import { signin } from '@/entities/viewer'
import { captureException, withScope } from '@sentry/core'
import { getSigninUrl } from '@/shared/lib'
import { useAtomValue } from 'jotai'
import { queryClientAtom } from '@/shared/lib'
import { parseCookies } from 'nookies'
import { useRouter } from 'next/router'
 
export const useSignIn = () => {
  const router = useRouter()
 
  const queryClient = useAtomValue(queryClientAtom)
  const { access_token, refresh_token } = parseCookies()
 
  const isTokenExist = access_token || refresh_token
  useEffect(() => {
    const { code, state } = window.location.href.match(/\??&?code=(?<code>\w+)&state=(?<state>\w+)/)?.groups || {}
    if (code && state) {
      signin(code, state, queryClient)
        .then(() => router.replace(router.asPath.replace(/\??&?(code|state)=\w+/g, '')))
        .catch(error => {
          withScope(scope => {
            scope.setLevel('fatal')
            scope.addBreadcrumb({
              category: 'Auth',
              message: 'Ошибка авторизации',
            })
            captureException(error)
          })
        })
    } else if (!isTokenExist && navigator.onLine) {
      router.push(getSigninUrl(window.location.origin))
    }
  }, [isTokenExist])
}