client/web: move auth session creation out of /api/auth

Splits auth session creation into two new endpoints:

/api/auth/session/new - to request a new auth session

/api/auth/session/wait - to block until user has completed auth url

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
This commit is contained in:
Sonia Appasamy
2023-11-03 13:38:01 -04:00
committed by Sonia Appasamy
parent 658971d7c0
commit e5dcf7bdde
5 changed files with 176 additions and 97 deletions

View File

@ -8,20 +8,23 @@ export enum AuthType {
export type AuthResponse = {
ok: boolean
authUrl?: string
authNeeded?: AuthType
}
export type SessionsCallbacks = {
new: () => Promise<string> // creates new auth session and returns authURL
wait: () => Promise<void> // blocks until auth is completed
}
// useAuth reports and refreshes Tailscale auth status
// for the web client.
export default function useAuth() {
const [data, setData] = useState<AuthResponse>()
const [loading, setLoading] = useState<boolean>(true)
const loadAuth = useCallback((wait?: boolean) => {
const url = wait ? "/auth?wait=true" : "/auth"
const loadAuth = useCallback(() => {
setLoading(true)
return apiFetch(url, "GET")
return apiFetch("/auth", "GET")
.then((r) => r.json())
.then((d) => {
setData(d)
@ -44,11 +47,33 @@ export default function useAuth() {
})
}, [])
const newSession = useCallback(() => {
return apiFetch("/auth/session/new", "GET")
.then((r) => r.json())
.then((d) => d.authUrl)
.catch((error) => {
console.error(error)
})
}, [])
const waitForSessionCompletion = useCallback(() => {
return apiFetch("/auth/session/wait", "GET")
.then(() => loadAuth()) // refresh auth data
.catch((error) => {
console.error(error)
})
}, [])
useEffect(() => {
loadAuth()
}, [])
const waitOnAuth = useCallback(() => loadAuth(true), [])
return { data, loading, waitOnAuth }
return {
data,
loading,
sessions: {
new: newSession,
wait: waitForSessionCompletion,
},
}
}