pub async fn sso_login<T: Client + TokenClient + CacheClient>(
    options: &LoginOptions<'_, T>,
) -> Result<Token, Error> {
    let LoginOptions {
        api_client,
        color_config,
        login_url: login_url_configuration,
        login_server,
        sso_team,
        existing_token,
        force,
    } = *options;

    let sso_team = sso_team.ok_or(Error::EmptySSOTeam)?;
    // I created a closure that gives back a closure since the `is_valid` checks do
    // a call to get the user, so instead of doing that multiple times we have
    // `is_valid` give back the user email.
    //
    // In the future I want to make the Token have some non-skewable information and
    // be able to get rid of this, but it works for now.
    let valid_token_callback = |message: &str, color_config: &ColorConfig| {
        let message = message.to_string();
        let color_config = *color_config;
        move |user_email: &str| {
            println!("{}", color_config.apply(BOLD.apply_to(message)));
            ui::print_cli_authorized(user_email, &color_config);
        }
    };

    // Check if token exists first. Must be there for the user and contain the
    // sso_team passed into this function.
    if !force {
        if let Some(token) = existing_token {
            let token = Token::existing(token.into());
            if token
                .is_valid_sso(
                    api_client,
                    sso_team,
                    Some(valid_token_callback("Existing token found!", color_config)),
                )
                .await?
            {
                return Ok(token);
            }
        // No existing turbo token found. If the user is logging into Vercel,
        // check for an existing `vc` token with correct scope.
        } else if login_url_configuration.contains("vercel.com") {
            if let Ok(Some(token)) = extract_vercel_token() {
                let token = Token::existing(token);
                if token
                    .is_valid_sso(
                        api_client,
                        sso_team,
                        Some(valid_token_callback(
                            &format!("Existing Vercel token for {sso_team} found!"),
                            color_config,
                        )),
                    )
                    .await?
                {
                    return Ok(token);
                }
            }
        }
    }

    let redirect_url = format!("http://{DEFAULT_HOST_NAME}:{DEFAULT_PORT}");
    let mut login_url = Url::parse(login_url_configuration)?;

    login_url
        .path_segments_mut()
        .map_err(|_: ()| error::Error::LoginUrlCannotBeABase {
            value: login_url_configuration.to_string(),
        })?
        .extend(["api", "auth", "sso"]);

    login_url
        .query_pairs_mut()
        .append_pair("teamId", sso_team)
        .append_pair("mode", "login")
        .append_pair("next", &redirect_url);

    println!(">>> Opening browser to {login_url}");
    let spinner = start_spinner("Waiting for your authorization...");
    let url = login_url.as_str();

    // Don't open the browser in tests.
    if !cfg!(test) && webbrowser::open(url).is_err() {
        warn!("Failed to open browser. Please visit {url} in your browser.");
    }

    let token_cell = Arc::new(OnceCell::new());
    login_server
        .run(DEFAULT_PORT, crate::LoginType::SSO, token_cell.clone())
        .await?;
    spinner.finish_and_clear();

    let token = token_cell.get().ok_or(Error::FailedToGetToken)?;

    let token_name = make_token_name()?;

    let verified_user = api_client
        .verify_sso_token(token, &token_name)
        .await
        .map_err(Error::FailedToValidateSSOToken)?;

    let user_response = api_client
        .get_user(&verified_user.token)
        .await
        .map_err(Error::FailedToFetchUser)?;

    ui::print_cli_authorized(&user_response.user.email, color_config);

    Ok(Token::New(verified_user.token))
}
Perform an SSO login flow. If an existing token is present, and the token
has access to the provided `sso_team`, we do not overwrite it and instead
log that we found an existing token.
crates/turborepo-auth/src/auth/sso.rs