Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collection Pre Request Not Working #3837

Open
2 tasks done
mark-reverman opened this issue Jan 17, 2025 · 1 comment
Open
2 tasks done

Collection Pre Request Not Working #3837

mark-reverman opened this issue Jan 17, 2025 · 1 comment
Labels
bug Something isn't working

Comments

@mark-reverman
Copy link

I have checked the following:

  • I use the newest version of bruno.
  • I've searched existing issues and found nothing related to my issue.

Describe the bug

Running into an issue where the pre-request at the Collection level is not running before the intended request within the collection. Trying to setup a bearer token and use it across all requests within the collection. The pre-script works however the header bearer token is always null because the request is completed prior to the collection pre-request running.

.bru file to reproduce the bug

// Define variables
const axios = require('axios');

const accessToken = bru.getEnvVar("ACCESS_TOKEN");
const refreshToken = bru.getEnvVar("REFRESH_TOKEN");
const product_access_id = bru.getEnvVar("PRODUCT_ACCESS_ID");
const base_url = bru.getEnvVar("baseUrl");
const username = bru.getEnvVar('USERNAME');
const password = bru.getEnvVar('PASSWORD');

const urlAuthentication = `${base_url}/session/auth/password`;
const urlUserInfo = `${base_url}/session/userinfo`;

async function myPasswordAuthentication() {
  try {
    const response = await axios.post(urlAuthentication, {
      userName: username,
      password: password,
    }, {
      headers: {
      "Content-Type": "application/json",
      },
    });

    const responseData = response.data;

    if (responseData.auth_token && responseData.token_type) {
      bru.setEnvVar("AUTH_TOKEN", responseData.auth_token);
      bru.setEnvVar("TOKEN_TYPE", responseData.token_type);
      return "Authentication successful.";
    } else {
      throw new Error("Password Authentication failed: Missing auth token or token type in response.");
    }
  } catch (error) {
    console.error("Password Authentication failed:", error);
    throw error;
  }
}

async function myGetUserInfo() {
  try {
    const response = await axios.get(urlUserInfo, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${bru.getEnvVar("AUTH_TOKEN")}`,
      },
    }); 
    const responseData = response.data;
    //console.log('myGetUserInfo --> response', responseData);
    const appId = responseData.apps.find(app => app.appId === "economy" && app.access.length > 0);
    //console.log('-------> economyApp', economyApp);
    if (appId) {
      bru.setEnvVar("ACCOUNT_ID", appId.access[0].accountId);
      bru.setEnvVar("PRODUCT_ACCESS_ID", appId.access[0].entries[0].productAccessId);
      bru.setEnvVar("USER_ID", responseData.userId);
      return "Get user information successful.";
    } else {
      throw new Error("App not found or user has no access to it.");
    }
  } catch (error) {
    console.error("Get User Information failed:", error);
    throw error;
  }
}

async function myRefreshToken() {
  try {
    const urlRefreshToken = `${base_url}/session/token?product_access_id=${bru.getEnvVar("PRODUCT_ACCESS_ID")}`;
    //console.log('----> urlRefreshToken', urlRefreshToken)
    const response = await axios.get(urlRefreshToken, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${bru.getEnvVar("AUTH_TOKEN")}`,
      },
    });
    const responseData = response.data;
//     console.log("myRefreshToken() --> response ", responseData);
    if (responseData.refresh_token && responseData.access_token) {
      bru.setEnvVar("REFRESH_TOKEN", responseData.refresh_token);
      bru.setEnvVar("ACCESS_TOKEN", responseData.access_token);
      bru.setVar('token',responseData.access_token)
      const token = bru.getVar('token')
      console.log('--->', bru.getVar('token'))
      req.setHeader('Authentication', `Bearer ${token}`);

//       req.setHeader("Authorization", `Bearer ${token}`);
      return "Token refreshed successfully";
    }
    console.error("Failed to refresh token no access_token or refresh_token:", error);
    throw error;
  } catch (error) {
    console.error("Failed to refresh token:", error);
    throw error;
  }
}

async function processAuthentication() {
  if (!username || !password) {
    console.error("{USERNAME} and {PASSWORD} environment variables are required.")
    throw new Error("{USERNAME} and {PASSWORD} environment variables are required.");
  }
//   console.log('processAuthentication() --> accessToken', accessToken);
  if (accessToken) {
    try {
        await myRefreshToken();
        console.log("Token refreshed successfully.");
    } catch (refreshError) {
        console.warn("Token refresh failed:", refreshError);
        console.log("Retrying Auth, user info retrieval & token refresh");   
        await authenticate();         
    }
  } else {
    try {
      await authenticate();
    } catch (error) {
      console.error("An error occurred during re-authentication:", error);
      throw new Error("Authentication process failed.");
    }
  }
}

// Function to handle full authentication flow
async function authenticate() {
  try {
    await myPasswordAuthentication();
    console.log("Password authentication completed.");
        
    await myGetUserInfo();
    console.log("User info retrieval completed.");
        
    await myRefreshToken();
    console.log("Token refreshed successfully after re-authentication.");
  } catch (error) {
    console.error("An error occurred during the authentication flow:", error);
    throw new Error("Authentication process failed.");
  }
}

// Trigger the process
processAuthentication()
  .then(() => {
  const accessToken = bru.getEnvVar("ACCESS_TOKEN");
  const refreshToken = bru.getEnvVar("REFRESH_TOKEN");
  const product_access_id = bru.getEnvVar("PRODUCT_ACCESS_ID");
  const base_url = bru.getEnvVar("baseUrl");
  const username = bru.getEnvVar('USERNAME');
  const password = bru.getEnvVar('PASSWORD');  
  const tokenType = bru.getEnvVar('TOKEN_TYPE');  
  req.setHeader("Authorization", `Bearer ${accessToken}`);
  console.log("Process completed successfully.");
}).catch((error) => {
  console.error("Final process error:", error);
});


### Screenshots/Live demo link

<img width="417" alt="Image" src="https://github.com/user-attachments/assets/4d5b6b04-e35a-4903-9f6b-369bfdfb3164" />
@mark-reverman mark-reverman added the bug Something isn't working label Jan 17, 2025
@mark-reverman
Copy link
Author

Image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant