All files / Rindu/utils getAuth.ts

94.73% Statements 18/19
88.88% Branches 8/9
100% Functions 1/1
94.73% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 3444x   44x 44x   7x     5x 5x 5x   5x 3x 3x 3x       3x   3x 2x     1x   2x 1x     1x    
import { ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE } from "./constants";
import { ServerApiContext } from "types/serverContext";
import { takeCookie } from "utils";
import { getMe, refreshAccessToken } from "utils/spotifyCalls";
 
export async function getAuth(
  context: ServerApiContext
): Promise<{ user: SpotifyApi.UserObjectPrivate; accessToken: string } | null> {
  const refreshToken = takeCookie(REFRESH_TOKEN_COOKIE, context);
  const accessTokenFromCookie = takeCookie(ACCESS_TOKEN_COOKIE, context);
  const user = await getMe(context);
 
  if (refreshToken && !user) {
    await refreshAccessToken(context);
    const access_token = takeCookie(ACCESS_TOKEN_COOKIE, context);
    Iif (!access_token) {
      return null;
    }
 
    const userFromRefreshedToken = await getMe(context);
 
    if (!userFromRefreshedToken) {
      return null;
    }
 
    return { user: userFromRefreshedToken, accessToken: access_token };
  }
  if (!user || !accessTokenFromCookie || !refreshToken) {
    return null;
  }
 
  return { user, accessToken: accessTokenFromCookie };
}