go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/frontend/ui/src/api/auth_state.ts (about)

     1  // Copyright 2022 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  let authState : AuthState | null = null;
    16  
    17  // eslint-disable-next-line valid-jsdoc
    18  /**
    19   * obtainAuthState obtains a current auth state, for interacting
    20   * with pRPC APIs.
    21   * @return the current auth state.
    22   */
    23  export async function obtainAuthState(): Promise<AuthState> {
    24    if (authState != null &&
    25              authState.accessTokenExpiry * 1000 > (Date.now() + 5000) &&
    26              authState.idTokenExpiry * 1000 > (Date.now() + 5000)) {
    27      // Auth state is still has >=5 seconds of validity for
    28      // both tokens.
    29      return authState;
    30    }
    31  
    32    // Refresh the auth state.
    33    const response = await queryAuthState();
    34    authState = response;
    35    return authState;
    36  }
    37  
    38  export interface AuthState {
    39      identity: string;
    40      email: string;
    41      picture: string;
    42      accessToken: string;
    43      idToken: string;
    44      // Expiration time (unix timestamp) of the access token.
    45      // If zero/undefined, the access token does not expire.
    46      accessTokenExpiry: number;
    47      idTokenExpiry: number;
    48  }
    49  
    50  export async function queryAuthState(): Promise<AuthState> {
    51    const res = await fetch('/auth/openid/state');
    52    if (!res.ok) {
    53      throw new Error('failed to get authState:\n' + (await res.text()));
    54    }
    55    return res.json();
    56  }