我正在与Microsoft Graph API
一起取回用户inbox
的数据。首先,我使用simple-oauth2
和jsonwebtoken
授权用户。然后,我取回users inbox
数据。现在我有了数据,我想将其存储在mongodb
中。问题是我无法访问保存所有内容的result
变量。关于如何访问此的任何想法。我将代码放在下面。
这是我要参考的教程:https://docs.microsoft.com/en-us/outlook/rest/node-tutorial
编辑:发现我只有在重定向到Microsoft Outlook并登录后才得到accessToken
和username
,所以我希望即使登录后也能获得这两个字段。知道我正在将值存储到cookies
中,并且应该能够访问它们。我现在正试图弄清楚该怎么做?
reportSaver.js
var express = require('express');
var router = express.Router();
var authHelper = require('../helpers/auth');
var graph = require('@microsoft/microsoft-graph-client');
var db = require('../helpers/database')
// Creating report object from report.js
SERA = require('../helpers/report_Schema')
var app = express()
// Posting Email
router.post('/save', async function (req, res) {
// let parms = {
// title: 'Inbox',
// active: {
// inbox: true
// }
// };
debugger;
// get token and username from input of email
// must be able to get the accessToken and username because I am not
// seeing the value array I get back from the api
const accessToken = await authHelper.getAccessToken(req.cookies, res);
const userName = req.cookies.graph_user_name;
if (accessToken && userName) {
parms.user = userName;
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// Get the 10 newest messages from inbox
const result = await client
.api('/me/mailfolders/inbox/messages?$search= "from:@student.gsu.edu"')
//api("/me/mailfolders/inbox/messages?$filter=from/emailaddress/address eq '@student.gsu.edu'")
//api("/me/messages?$filter=from/emailaddress/address eq '@npm.js.com'")
.top(5)
.select('subject,from,receivedDateTime,isRead,sentDateTime')
// .orderby('receivedDateTime DESC')
.count(true)
.get();
const report = new SERA({
_id: req.body._id,
//result.value[0].id,
receivedDateTime: //req.body.receivedDateTime,
result.value[0].receivedDateTime,
sentDateTime: // req.body.sentDateTime
result.value[1].sentDateTime
});
// save stores into database
report.save().then(result => {
console.log(result)
})
// error checking
// promise
.catch((err) => console.log(err))
res.status(201).json({
message: "Handling post request to /api/report",
createdReport: report
});
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = {
status: `${err.code}: ${err.message}`
};
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
// If we dont have the accessToken and userName
} else {
res.send.json({
message: "There was an error",
});
}
// console.log("I have been hit")
});
module.exports = router;
auth.js
// This file is where we authenticate the token
we get back from the api
const credentials = {
client: {
// this is the app_id that we get when we register our app on microsoft
id: process.env.APP_ID,
// this is the password. stored in our .env file. Client password
secret: process.env.APP_PASSWORD,
},
auth: {
// String used to set the host to request the tokens to. Required.
tokenHost: 'https://login.microsoftonline.com',
// String path to request an authorization code
authorizePath: 'common/oauth2/v2.0/authorize',
//String path to request an access token.
tokenPath: 'common/oauth2/v2.0/token'
}
};
// here we require simple-oauth2
const oauth2 = require('simple-oauth2').create(credentials);
// require a jsonwebtoken
const jwt = require('jsonwebtoken');
// this function will get the scopes and redirect_uri
// and authorize it.
function getAuthUrl() {
const returnVal = oauth2.authorizationCode.authorizeURL({
// this is where we are redirected after authorization
redirect_uri: process.env.REDIRECT_URI,
// this is the scopes of the app
scope: process.env.APP_SCOPES
});
console.log(`Generated auth url: ${returnVal}`);
return returnVal;
}
// this function gets the token to be authorized
async function getTokenFromCode(auth_code, res) {
// gets the access token object
let result = await oauth2.authorizationCode.getToken({
code: auth_code,
redirect_uri: process.env.REDIRECT_URI,
scope: process.env.APP_SCOPES
});
// creates the access token
const token = oauth2.accessToken.create(result);
console.log('Token created: ', token.token);
saveValuesToCookie(token, res);
return token.token.access_token;
}
async function getAccessToken(cookies, res) {
// Do we have an access token cached?
let token = cookies.graph_access_token;
if (token) {
// We have a token, but is it expired?
// Expire 5 minutes early to account for clock differences
const FIVE_MINUTES = 300000;
const expiration = new Date(parseFloat(cookies.graph_token_expires - FIVE_MINUTES));
if (expiration > new Date()) {
// Token is still good, just return it
return token;
}
}
// Either no token or it's expired, do we have a
// refresh token?
// If we do, create set the refresh_token and then refresh it
// after that we save it and return it
const refresh_token = cookies.graph_refresh_token;
if (refresh_token) {
const newToken = await oauth2.accessToken.create({
refresh_token: refresh_token
}).refresh();
saveValuesToCookie(newToken, res);
return newToken.token.access_token;
}
// Nothing in the cookies that helps, return empty
return null;
}
//JSON Web Token (JWT) is a compact, URL-safe means of representing
// claims to be transferred between two parties.
function saveValuesToCookie(token, res) {
// Parse the identity token
const user = jwt.decode(token.token.id_token);
// Save the access token in a cookie
res.cookie('graph_access_token', token.token.access_token, {
maxAge: 3600000,
httpOnly: true
});
// Save the user's name in a cookie
res.cookie('graph_user_name', user.name, {
maxAge: 3600000,
httpOnly: true
});
// Save the refresh token in a cookie
res.cookie('graph_refresh_token', token.token.refresh_token, {
maxAge: 7200000,
httpOnly: true
});
// Save the token expiration tiem in a cookie
res.cookie('graph_token_expires', token.token.expires_at.getTime(), {
maxAge: 3600000,
httpOnly: true
});
}
// this function will clear the cookies for the graph variables
// When the user signs out, all of the cookies will be cleared.
function clearCookies(res) {
// Clear cookies
res.clearCookie('graph_access_token', {
maxAge: 3600000,
httpOnly: true
});
res.clearCookie('graph_user_name', {
maxAge: 3600000,
httpOnly: true
});
res.clearCookie('graph_refresh_token', {
maxAge: 7200000,
httpOnly: true
});
res.clearCookie('graph_token_expires', {
maxAge: 3600000,
httpOnly: true
});
}
exports.getAuthUrl = getAuthUrl;
exports.getTokenFromCode = getTokenFromCode;
exports.getAccessToken = getAccessToken;
exports.clearCookies = clearCookies;