You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

microsoftCalendar.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. // @flow
  2. import { Client } from '@microsoft/microsoft-graph-client';
  3. import rs from 'jsrsasign';
  4. import type { Dispatch } from 'redux';
  5. import { createDeferred } from '../../../../modules/util/helpers';
  6. import { parseStandardURIString, parseURLParams } from '../../base/util';
  7. import { getShareInfoText } from '../../invite';
  8. import { setCalendarAPIAuthState } from '../actions';
  9. import { findWindows } from 'windows-iana';
  10. /**
  11. * Constants used for interacting with the Microsoft API.
  12. *
  13. * @private
  14. * @type {object}
  15. */
  16. const MS_API_CONFIGURATION = {
  17. /**
  18. * The URL to use when authenticating using Microsoft API.
  19. * @type {string}
  20. */
  21. AUTH_ENDPOINT:
  22. 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?',
  23. CALENDAR_ENDPOINT: '/me/calendars',
  24. /**
  25. * The Microsoft API scopes to request access for calendar.
  26. *
  27. * @type {string}
  28. */
  29. MS_API_SCOPES: 'openid profile Calendars.ReadWrite',
  30. /**
  31. * See https://docs.microsoft.com/en-us/azure/active-directory/develop/
  32. * v2-oauth2-implicit-grant-flow#send-the-sign-in-request. This value is
  33. * needed for passing in the proper domain_hint value when trying to refresh
  34. * a token silently.
  35. *
  36. *
  37. * @type {string}
  38. */
  39. MS_CONSUMER_TENANT: '9188040d-6c67-4c5b-b112-36a304b66dad',
  40. /**
  41. * The redirect URL to be used by the Microsoft API on successful
  42. * authentication.
  43. *
  44. * @type {string}
  45. */
  46. REDIRECT_URI: `${window.location.origin}/static/msredirect.html`
  47. };
  48. /**
  49. * Store the window from an auth request. That way it can be reused if a new
  50. * request comes in and it can be used to indicate a request is in progress.
  51. *
  52. * @private
  53. * @type {Object|null}
  54. */
  55. let popupAuthWindow = null;
  56. /**
  57. * A stateless collection of action creators that implements the expected
  58. * interface for interacting with the Microsoft API in order to get calendar
  59. * data.
  60. *
  61. * @type {Object}
  62. */
  63. export const microsoftCalendarApi = {
  64. /**
  65. * Retrieves the current calendar events.
  66. *
  67. * @param {number} fetchStartDays - The number of days to go back
  68. * when fetching.
  69. * @param {number} fetchEndDays - The number of days to fetch.
  70. * @returns {function(Dispatch<any>, Function): Promise<CalendarEntries>}
  71. */
  72. getCalendarEntries(fetchStartDays: ?number, fetchEndDays: ?number) {
  73. return (dispatch: Dispatch<any>, getState: Function): Promise<*> => {
  74. const state = getState()['features/calendar-sync'] || {};
  75. const token = state.msAuthState && state.msAuthState.accessToken;
  76. if (!token) {
  77. return Promise.reject('Not authorized, please sign in!');
  78. }
  79. const client = Client.init({
  80. authProvider: done => done(null, token)
  81. });
  82. return client
  83. .api(MS_API_CONFIGURATION.CALENDAR_ENDPOINT)
  84. .get()
  85. .then(response => {
  86. const calendarIds = response.value.map(en => en.id);
  87. const getEventsPromises = calendarIds.map(id =>
  88. requestCalendarEvents(
  89. client, id, fetchStartDays, fetchEndDays));
  90. return Promise.all(getEventsPromises);
  91. })
  92. // get .value of every element from the array of results,
  93. // which is an array of events and flatten it to one array
  94. // of events
  95. .then(result => [].concat(...result))
  96. .then(entries => entries.map(e => formatCalendarEntry(e)));
  97. };
  98. },
  99. /**
  100. * Returns the email address for the currently logged in user.
  101. *
  102. * @returns {function(Dispatch<*, Function>): Promise<string>}
  103. */
  104. getCurrentEmail(): Function {
  105. return (dispatch: Dispatch<any>, getState: Function) => {
  106. const { msAuthState = {} }
  107. = getState()['features/calendar-sync'] || {};
  108. const email = msAuthState.userSigninName || '';
  109. return Promise.resolve(email);
  110. };
  111. },
  112. /**
  113. * Sets the application ID to use for interacting with the Microsoft API.
  114. *
  115. * @returns {function(): Promise<void>}
  116. */
  117. load(): Function {
  118. return () => Promise.resolve();
  119. },
  120. /**
  121. * Prompts the participant to sign in to the Microsoft API Client Library.
  122. *
  123. * @returns {function(Dispatch<any>, Function): Promise<void>}
  124. */
  125. signIn(): Function {
  126. return (dispatch: Dispatch<any>, getState: Function) => {
  127. // Ensure only one popup window at a time.
  128. if (popupAuthWindow) {
  129. popupAuthWindow.focus();
  130. return Promise.reject('Sign in already in progress.');
  131. }
  132. const signInDeferred = createDeferred();
  133. const guids = {
  134. authState: generateGuid(),
  135. authNonce: generateGuid()
  136. };
  137. dispatch(setCalendarAPIAuthState(guids));
  138. const { microsoftApiApplicationClientID }
  139. = getState()['features/base/config'];
  140. const authUrl = getAuthUrl(
  141. microsoftApiApplicationClientID,
  142. guids.authState,
  143. guids.authNonce);
  144. const h = 600;
  145. const w = 480;
  146. popupAuthWindow = window.open(
  147. authUrl,
  148. 'Auth M$',
  149. `width=${w}, height=${h}, top=${
  150. (screen.height / 2) - (h / 2)}, left=${
  151. (screen.width / 2) - (w / 2)}`);
  152. const windowCloseCheck = setInterval(() => {
  153. if (popupAuthWindow && popupAuthWindow.closed) {
  154. signInDeferred.reject(
  155. 'Popup closed before completing auth.');
  156. popupAuthWindow = null;
  157. window.removeEventListener('message', handleAuth);
  158. clearInterval(windowCloseCheck);
  159. } else if (!popupAuthWindow) {
  160. // This case probably happened because the user completed
  161. // auth.
  162. clearInterval(windowCloseCheck);
  163. }
  164. }, 500);
  165. /**
  166. * Callback with scope access to other variables that are part of
  167. * the sign in request.
  168. *
  169. * @param {Object} event - The event from the post message.
  170. * @private
  171. * @returns {void}
  172. */
  173. function handleAuth({ data }) {
  174. if (!data || data.type !== 'ms-login') {
  175. return;
  176. }
  177. window.removeEventListener('message', handleAuth);
  178. popupAuthWindow && popupAuthWindow.close();
  179. popupAuthWindow = null;
  180. const params = getParamsFromHash(data.url);
  181. const tokenParts = getValidatedTokenParts(
  182. params, guids, microsoftApiApplicationClientID);
  183. if (!tokenParts) {
  184. signInDeferred.reject('Invalid token received');
  185. return;
  186. }
  187. dispatch(setCalendarAPIAuthState({
  188. authState: undefined,
  189. accessToken: tokenParts.accessToken,
  190. idToken: tokenParts.idToken,
  191. tokenExpires: params.tokenExpires,
  192. userDomainType: tokenParts.userDomainType,
  193. userSigninName: tokenParts.userSigninName
  194. }));
  195. signInDeferred.resolve();
  196. }
  197. window.addEventListener('message', handleAuth);
  198. return signInDeferred.promise;
  199. };
  200. },
  201. /**
  202. * Returns whether or not the user is currently signed in.
  203. *
  204. * @returns {function(Dispatch<any>, Function): Promise<boolean>}
  205. */
  206. _isSignedIn(): Function {
  207. return (dispatch: Dispatch<any>, getState: Function) => {
  208. const now = new Date().getTime();
  209. const state
  210. = getState()['features/calendar-sync'].msAuthState || {};
  211. const tokenExpires = parseInt(state.tokenExpires, 10);
  212. const isExpired = now > tokenExpires && !isNaN(tokenExpires);
  213. if (state.accessToken && isExpired) {
  214. // token expired, let's refresh it
  215. return dispatch(refreshAuthToken())
  216. .then(() => true)
  217. .catch(() => false);
  218. }
  219. return Promise.resolve(state.accessToken && !isExpired);
  220. };
  221. },
  222. /**
  223. * Updates calendar event by generating new invite URL and editing the event
  224. * adding some descriptive text and location.
  225. *
  226. * @param {string} id - The event id.
  227. * @param {string} calendarId - The id of the calendar to use.
  228. * @param {string} location - The location to save to the event.
  229. * @returns {function(Dispatch<any>): Promise<string|never>}
  230. */
  231. updateCalendarEvent(id: string, calendarId: string, location: string) {
  232. return (dispatch: Dispatch<any>, getState: Function): Promise<*> => {
  233. const state = getState()['features/calendar-sync'] || {};
  234. const token = state.msAuthState && state.msAuthState.accessToken;
  235. if (!token) {
  236. return Promise.reject('Not authorized, please sign in!');
  237. }
  238. return getShareInfoText(getState(), location, true/* use html */)
  239. .then(text => {
  240. const client = Client.init({
  241. authProvider: done => done(null, token)
  242. });
  243. return client
  244. .api(`/me/events/${id}`)
  245. .get()
  246. .then(description => {
  247. const body = description.body;
  248. if (description.bodyPreview) {
  249. body.content
  250. = `${description.bodyPreview}<br><br>`;
  251. }
  252. // replace all new lines from the text with html
  253. // <br> to make it pretty
  254. body.content += text.split('\n').join('<br>');
  255. return client
  256. .api(`/me/calendar/events/${id}`)
  257. .patch({
  258. body,
  259. location: {
  260. 'displayName': location
  261. }
  262. });
  263. });
  264. });
  265. };
  266. }
  267. };
  268. /**
  269. * Parses the Microsoft calendar entries to a known format.
  270. *
  271. * @param {Object} entry - The Microsoft calendar entry.
  272. * @private
  273. * @returns {{
  274. * calendarId: string,
  275. * description: string,
  276. * endDate: string,
  277. * id: string,
  278. * location: string,
  279. * startDate: string,
  280. * title: string
  281. * }}
  282. */
  283. function formatCalendarEntry(entry) {
  284. return {
  285. calendarId: entry.calendarId,
  286. description: entry.body.content,
  287. endDate: entry.end.dateTime,
  288. id: entry.id,
  289. location: entry.location.displayName,
  290. startDate: entry.start.dateTime,
  291. title: entry.subject
  292. };
  293. }
  294. /**
  295. * Generate a guid to be used for verifying token validity.
  296. *
  297. * @private
  298. * @returns {string} The generated string.
  299. */
  300. function generateGuid() {
  301. const buf = new Uint16Array(8);
  302. window.crypto.getRandomValues(buf);
  303. return `${s4(buf[0])}${s4(buf[1])}-${s4(buf[2])}-${s4(buf[3])}-${
  304. s4(buf[4])}-${s4(buf[5])}${s4(buf[6])}${s4(buf[7])}`;
  305. }
  306. /**
  307. * Constructs and returns the URL to use for renewing an auth token.
  308. *
  309. * @param {string} appId - The Microsoft application id to log into.
  310. * @param {string} userDomainType - The domain type of the application as
  311. * provided by Microsoft.
  312. * @param {string} userSigninName - The email of the user signed into the
  313. * integration with Microsoft.
  314. * @private
  315. * @returns {string} - The auth URL.
  316. */
  317. function getAuthRefreshUrl(appId, userDomainType, userSigninName) {
  318. return [
  319. getAuthUrl(appId, 'undefined', 'undefined'),
  320. 'prompt=none',
  321. `domain_hint=${userDomainType}`,
  322. `login_hint=${userSigninName}`
  323. ].join('&');
  324. }
  325. /**
  326. * Constructs and returns the auth URL to use for login.
  327. *
  328. * @param {string} appId - The Microsoft application id to log into.
  329. * @param {string} authState - The authState guid to use.
  330. * @param {string} authNonce - The authNonce guid to use.
  331. * @private
  332. * @returns {string} - The auth URL.
  333. */
  334. function getAuthUrl(appId, authState, authNonce) {
  335. const authParams = [
  336. 'response_type=id_token+token',
  337. `client_id=${appId}`,
  338. `redirect_uri=${MS_API_CONFIGURATION.REDIRECT_URI}`,
  339. `scope=${MS_API_CONFIGURATION.MS_API_SCOPES}`,
  340. `state=${authState}`,
  341. `nonce=${authNonce}`,
  342. 'response_mode=fragment'
  343. ].join('&');
  344. return `${MS_API_CONFIGURATION.AUTH_ENDPOINT}${authParams}`;
  345. }
  346. /**
  347. * Converts a url from an auth redirect into an object of parameters passed
  348. * into the url.
  349. *
  350. * @param {string} url - The string to parse.
  351. * @private
  352. * @returns {Object}
  353. */
  354. function getParamsFromHash(url) {
  355. const params = parseURLParams(parseStandardURIString(url), true, 'hash');
  356. // Get the number of seconds the token is valid for, subtract 5 minutes
  357. // to account for differences in clock settings and convert to ms.
  358. const expiresIn = (parseInt(params.expires_in, 10) - 300) * 1000;
  359. const now = new Date();
  360. const expireDate = new Date(now.getTime() + expiresIn);
  361. params.tokenExpires = expireDate.getTime().toString();
  362. return params;
  363. }
  364. /**
  365. * Converts the parameters from a Microsoft auth redirect into an object of
  366. * token parts. The value "null" will be returned if the params do not produce
  367. * a valid token.
  368. *
  369. * @param {Object} tokenInfo - The token object.
  370. * @param {Object} guids - The guids for authState and authNonce that should
  371. * match in the token.
  372. * @param {Object} appId - The Microsoft application this token is for.
  373. * @private
  374. * @returns {Object|null}
  375. */
  376. function getValidatedTokenParts(tokenInfo, guids, appId) {
  377. // Make sure the token matches the request source by matching the GUID.
  378. if (tokenInfo.state !== guids.authState) {
  379. return null;
  380. }
  381. const idToken = tokenInfo.id_token;
  382. // A token must exist to be valid.
  383. if (!idToken) {
  384. return null;
  385. }
  386. const tokenParts = idToken.split('.');
  387. if (tokenParts.length !== 3) {
  388. return null;
  389. }
  390. const payload
  391. = rs.KJUR.jws.JWS.readSafeJSONString(rs.b64utoutf8(tokenParts[1]));
  392. if (payload.nonce !== guids.authNonce
  393. || payload.aud !== appId
  394. || payload.iss
  395. !== `https://login.microsoftonline.com/${payload.tid}/v2.0`) {
  396. return null;
  397. }
  398. const now = new Date();
  399. // Adjust by 5 minutes to allow for inconsistencies in system clocks.
  400. const notBefore = new Date((payload.nbf - 300) * 1000);
  401. const expires = new Date((payload.exp + 300) * 1000);
  402. if (now < notBefore || now > expires) {
  403. return null;
  404. }
  405. return {
  406. accessToken: tokenInfo.access_token,
  407. idToken,
  408. userDisplayName: payload.name,
  409. userDomainType:
  410. payload.tid === MS_API_CONFIGURATION.MS_CONSUMER_TENANT
  411. ? 'consumers' : 'organizations',
  412. userSigninName: payload.preferred_username
  413. };
  414. }
  415. /**
  416. * Renews an existing auth token so it can continue to be used.
  417. *
  418. * @private
  419. * @returns {function(Dispatch<any>, Function): Promise<void>}
  420. */
  421. function refreshAuthToken(): Function {
  422. return (dispatch: Dispatch<any>, getState: Function) => {
  423. const { microsoftApiApplicationClientID }
  424. = getState()['features/base/config'];
  425. const { msAuthState = {} }
  426. = getState()['features/calendar-sync'] || {};
  427. const refreshAuthUrl = getAuthRefreshUrl(
  428. microsoftApiApplicationClientID,
  429. msAuthState.userDomainType,
  430. msAuthState.userSigninName);
  431. const iframe = document.createElement('iframe');
  432. iframe.setAttribute('id', 'auth-iframe');
  433. iframe.setAttribute('name', 'auth-iframe');
  434. iframe.setAttribute('style', 'display: none');
  435. iframe.setAttribute('src', refreshAuthUrl);
  436. const signInPromise = new Promise(resolve => {
  437. iframe.onload = () => {
  438. resolve(iframe.contentWindow.location.hash);
  439. };
  440. });
  441. // The check for body existence is done for flow, which also runs
  442. // against native where document.body may not be defined.
  443. if (!document.body) {
  444. return Promise.reject(
  445. 'Cannot refresh auth token in this environment');
  446. }
  447. document.body.appendChild(iframe);
  448. return signInPromise.then(hash => {
  449. const params = getParamsFromHash(hash);
  450. dispatch(setCalendarAPIAuthState({
  451. accessToken: params.access_token,
  452. idToken: params.id_token,
  453. tokenExpires: params.tokenExpires
  454. }));
  455. });
  456. };
  457. }
  458. /**
  459. * Retrieves calendar entries from a specific calendar.
  460. *
  461. * @param {Object} client - The Microsoft-graph-client initialized.
  462. * @param {string} calendarId - The calendar ID to use.
  463. * @param {number} fetchStartDays - The number of days to go back
  464. * when fetching.
  465. * @param {number} fetchEndDays - The number of days to fetch.
  466. * @returns {Promise<any> | Promise}
  467. * @private
  468. */
  469. function requestCalendarEvents( // eslint-disable-line max-params
  470. client,
  471. calendarId,
  472. fetchStartDays,
  473. fetchEndDays): Promise<*> {
  474. const startDate = new Date();
  475. const endDate = new Date();
  476. startDate.setDate(startDate.getDate() + fetchStartDays);
  477. endDate.setDate(endDate.getDate() + fetchEndDays);
  478. const filter = `Start/DateTime ge '${
  479. startDate.toISOString()}' and End/DateTime lt '${
  480. endDate.toISOString()}'`;
  481. const ianaTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
  482. const windowsTimeZone = findWindows(ianaTimeZone);
  483. return client
  484. .api(`/me/calendars/${calendarId}/events`)
  485. .filter(filter)
  486. .header('Prefer', `outlook.timezone="${windowsTimeZone}"`)
  487. .select('id,subject,start,end,location,body')
  488. .orderby('createdDateTime DESC')
  489. .get()
  490. .then(result => result.value.map(item => {
  491. return {
  492. ...item,
  493. calendarId
  494. };
  495. }));
  496. }
  497. /**
  498. * Converts the passed in number to a string and ensure it is at least 4
  499. * characters in length, prepending 0's as needed.
  500. *
  501. * @param {number} num - The number to pad and convert to a string.
  502. * @private
  503. * @returns {string} - The number converted to a string.
  504. */
  505. function s4(num) {
  506. let ret = num.toString(16);
  507. while (ret.length < 4) {
  508. ret = `0${ret}`;
  509. }
  510. return ret;
  511. }