Skip to content

Instantly share code, notes, and snippets.

@blehr
Last active July 10, 2017 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blehr/3514d1066338550115f1205acd570134 to your computer and use it in GitHub Desktop.
Save blehr/3514d1066338550115f1205acd570134 to your computer and use it in GitHub Desktop.
const User = require("../models/users.js");
const google = require("googleapis");
const OAuth2 = google.auth.OAuth2;
const auth = require("./auth");
const moment = require("moment");
// create auth client
const oauth2Client = new OAuth2(
auth.googleAuth.clientID,
auth.googleAuth.clientSecret,
auth.googleAuth.callbackURL
);
exports.checkToken = (req, res, next) => {
// check for user
if (!req.user) {
return next();
}
// subtract current time from stored expiry_date and see if less than 5 minutes (300s) remain
if (moment().subtract(req.user.google.expiry_date, "s").format("X") > -300) {
// set the current users access and refresh token
oauth2Client.setCredentials({
access_token: req.user.google.token,
refresh_token: req.user.google.refreshToken
});
// request a new token
oauth2Client.refreshAccessToken(function(err, tokens) {
if (err) return next(err);
//save the new token and expiry_date
User.findOneAndUpdate(
{ "google.id": req.user.google.id },
{
"google.token": tokens.access_token,
"google.expiry_date": tokens.expiry_date
},
{
new: true,
runValidators: true
},
function(err, doc) {
if (err) return next(err);
next();
}
);
});
}
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment