googleapis / googleapis/google-api-nodejs-client
Refresh Access Token Inside Routes?
- Dominant language
- TypeScript
- Stars
- 12.2k
- Forks
- 2k
- Avg merge
- 1d 9h
- Merged PRs (30d)
- 24
Description
Do access_tokens automatically refresh when called inside of routes? My current implementation in React and Nodejs having followed [this](https://www.youtube.com/watch?v=-yH1ZnZBWyU&t=) tutorial. I'm not sure how to refresh the access token and update in postgres seeing as this route sequence will only trigger when the user first authorizes.
Is there a better workflow I should use?
This GET route passes the url back to React. React then opens up the url in a new window.
```
router.get("/api/create/:userId", async function (req, res) {
currentUserId = req.params.userId;
const oauth2Client = new google.auth.OAuth2(
CLIENT ID, CLIENT SECRET, REDIRECT_LINK
);
const scopes = [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/userinfo.profile",
];
const url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes,
state: JSON.stringify(currentUserId)
});
axios
.get(url).then(function (response) {
res.send({ url });
}).catch(function (error) {
console.log(error);
});
});
```
When the user successfully authorizes, they are sent to the redirect URI and this route triggers. The access token and refresh token are then saved to postgres:
```
router.get("/api/testgoogleapi", async function (req, res) {
const queryUrl = new urlParse(req.url);
const code = queryParse.parse(queryUrl.query).code;
const oauth2Client = new google.auth.OAuth2(
CLIENT ID, CLIENT SECRET, REDIRECT_LINK
);
const tokens = await oauth2Client.getToken(code);
oauth2Client.setCredentials({ access_token: tokens.tokens.access_token, refresh_token: tokens.tokens.refresh_token });
let access_token = tokens.tokens.access_token;
let refresh_token = tokens.tokens.refresh_token;
var oauth2 = google.oauth2({
auth: oauth2Client,
version: "v2",
});
let { data } = await oauth2.userinfo.get(); // get user info
try {
const updateUser = await pool.query(
`UPDATE org_user SET google_api_id = '${data.id}', google_api_refresh_token = '${refresh_token}', google_api_access_token = '${access_token}' WHERE id = '${currentUserId}'`
);
} catch (err) {
console.log(err);
}
});
```
Contributor guide
Assessment
This issue has not been assessed yet.