Skip to content
Snippets Groups Projects
useAuth.ts 1.25 KiB
Newer Older
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> => {
      await axios.get(`${_apiUrl}OAuth2Login`, { withCredentials: true })
    } 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)
        history.push('/editing')
  return { loginUser, error, logoutUser }