Skip to content
Snippets Groups Projects
useAuth.ts 1.35 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { useContext, useState } from 'react'
    
    import axios from 'axios'
    
    import { UserContext } from './userContext'
    import { useHistory } from 'react-router-dom'
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    const _apiUrl: string = 'https://localhost:443/'
    
    
    export interface Auth {
    
      loginUser: () => Promise<void>
    
      error: null
    
      logoutUser: () => void
    
    }
    export const useAuth = (): Auth => {
      const [error, setError] = useState(null)
    
      const { setUser } = useContext(UserContext)
      const history = useHistory()
    
      //login user
    
      const loginUser = async (): Promise<void> => {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
          const tmp = await axios.get(`${_apiUrl}OAuth2Login`, { withCredentials: true })
          console.log('lAAAAAA')
          console.log(tmp)
    
        } catch (e) {
          setError(e)
        }
      }
    
      const logoutUser = async (): Promise<void> => {
        try {
          if (setUser) setUser(null)
          await axios.get(`${_apiUrl}Logout`)
        } catch (e) {
          setError(e)
        }
    
      //set user in context and push them home
      const setUserContext = async (): Promise<void> => {
        try {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
          const { data } = await axios.get(`${_apiUrl}api/common/WhoAmI`, {
            withCredentials: true,
          })
    
          if (data && setUser) {
            setUser(data)
            console.log('usertoContext', data)
            history.push('/editing')
    
      return { loginUser, error, logoutUser }