Last active
November 22, 2015 16:10
-
-
Save TheHanna/963acf01b69c8e9ba02b to your computer and use it in GitHub Desktop.
Google Drive API credential generation/token refreshing in MEAN.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is valid for MEAN.js 0.4.0 | |
// Requires a couple of changes to work: | |
// Add Drive scope to users Express route | |
// Modify the Passport.js google strategy to put a token expiration date into the database | |
// User middleware function below to auth API calls | |
exports.requiresOAuth2Token = function (req, res, next) { | |
var OAuth2 = google.auth.OAuth2; | |
var client = new OAuth2(config.google.clientID, config.google.clientSecret, config.google.callbackURL); | |
client.setCredentials({ | |
access_token: req.user.providerData.accessToken, | |
refresh_token: req.user.providerData.refreshToken | |
}); | |
if (req.user.providerData.tokenExpires < Math.floor((Date.now() / 1000)) - 120) { | |
console.log('Token needs to be refreshed'); | |
client.refreshAccessToken(function(err, tokens) { | |
if (err) { | |
return res.status(400).send({ | |
message: errorHandler.getErrorMessage(err) | |
}); | |
} else { | |
var query = {_id: req.user._id}; | |
var update = {providerData: | |
_.extend(req.user.providerData, { | |
accessToken: tokens.access_token, | |
tokenExpires: Math.floor(tokens.expiry_date / 1000) | |
} | |
)}; | |
var opts = {}; | |
User.update(query, update, opts, function(err, num) { | |
if(err) { | |
console.log(err); | |
} else { | |
console.log(num + ' record(s) updated'); | |
req.user.client = client; | |
next(); | |
} | |
}); | |
} | |
}); | |
} else { | |
console.log('Current token still valid'); | |
req.user.client = client; | |
next(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment