| 2 | import axios from "axios" |
| 3 | |
| 4 | export default function useAuth(code) { |
| 5 | const [accessToken, setAccessToken] = useState() |
| 6 | const [refreshToken, setRefreshToken] = useState() |
| 7 | const [expiresIn, setExpiresIn] = useState() |
| 8 | |
| 9 | useEffect(() => { |
| 10 | axios |
| 11 | .post("http://localhost:3001/login", { |
| 12 | code, |
| 13 | }) |
| 14 | .then(res => { |
| 15 | setAccessToken(res.data.accessToken) |
| 16 | setRefreshToken(res.data.refreshToken) |
| 17 | setExpiresIn(res.data.expiresIn) |
| 18 | window.history.pushState({}, null, "/") |
| 19 | }) |
| 20 | .catch(() => { |
| 21 | window.location = "/" |
| 22 | }) |
| 23 | }, [code]) |
| 24 | |
| 25 | useEffect(() => { |
| 26 | if (!refreshToken || !expiresIn) return |
| 27 | const interval = setInterval(() => { |
| 28 | axios |
| 29 | .post("http://localhost:3001/refresh", { |
| 30 | refreshToken, |
| 31 | }) |
| 32 | .then(res => { |
| 33 | setAccessToken(res.data.accessToken) |
| 34 | setExpiresIn(res.data.expiresIn) |
| 35 | }) |
| 36 | .catch(() => { |
| 37 | window.location = "/" |
| 38 | }) |
| 39 | }, (expiresIn - 60) * 1000) |
| 40 | |
| 41 | return () => clearInterval(interval) |
| 42 | }, [refreshToken, expiresIn]) |
| 43 | |
| 44 | return accessToken |
| 45 | } |