-
Notifications
You must be signed in to change notification settings - Fork 12
feat: ms graph api mail service #1507
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gnyiri
wants to merge
30
commits into
develop
Choose a base branch
from
feat_ms_graph_api_mail_service
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
aca5ac1
Implement MS Graph Mail service
8e3f0c9
feat: complete ms graph api mail service
cac9762
fix: package files
6c6a63f
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 177cb99
fix: lazy creation of client
fc33512
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
0382853
feat: simplify ms graph mail service
4e27cf5
feat: simplify ms graph api mail service
326b54d
Merge branch 'develop' into feat_ms_graph_api_mail_service
5474a49
fix: add further logs
d927198
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 21fdb8d
Merge branch 'develop' of https://github.com/UserOfficeProject/user-o…
64464eb
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
0b7b056
feat: delete ms graph api test
700a505
fix: remove password log output
d609c8a
fix: make createAttachments abstract and fix ms graph implementation
ef96cb2
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 035f0b6
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri b225a12
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 722da5d
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 9258e20
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 6a85d85
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri e328c69
Merge from develop
3d27b24
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
9be23b7
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri f14e5ac
fix: review findings
ca40134
Merge branch 'develop' into feat_ms_graph_api_mail_service
gnyiri 670a5ff
Merge branch 'develop' into feat_ms_graph_api_mail_service
e6ce663
Merge branch 'develop' into feat_ms_graph_api_mail_service
a2ae146
Merge branch 'feat_ms_graph_api_mail_service' of https://github.com/U…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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 file contains hidden or 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
196 changes: 196 additions & 0 deletions
196
apps/backend/src/eventHandlers/MailService/MSGraph/MSGraphMailService.ts
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| import { existsSync, readFileSync } from 'node:fs'; | ||
|
|
||
| import * as msal from '@azure/msal-node'; | ||
| import { logger } from '@user-office-software/duo-logger'; | ||
| import { NodeMailerTransportOptions } from 'email-templates'; | ||
| import * as nodemailer from 'nodemailer'; | ||
| import { SentMessageInfo, Transport } from 'nodemailer'; | ||
| import MailMessage from 'nodemailer/lib/mailer/mail-message'; | ||
|
|
||
| import { TemplateMailService } from '../TemplateMailService'; | ||
|
|
||
| class MSGraphTransport implements Transport<SentMessageInfo> { | ||
| name: string; | ||
| version: string; | ||
|
|
||
| private apiUrl: string; | ||
| private authToken: msal.AuthenticationResult | null = null; | ||
| private msalClient: msal.ConfidentialClientApplication; | ||
| private tokenPromise: Promise<any> | null = null; | ||
|
|
||
| constructor() { | ||
| this.name = 'MSGraphTransport'; | ||
| this.version = '1.0.0'; | ||
| this.apiUrl = process.env.MS_GRAPH_API_URL || ''; | ||
|
|
||
| this.msalClient = new msal.ConfidentialClientApplication({ | ||
| auth: { | ||
| clientId: process.env.MS_GRAPH_API_CLIENT_ID!, | ||
| clientSecret: process.env.MS_GRAPH_API_CLIENT_SECRET!, | ||
| authority: `${process.env.MS_GRAPH_API_AUTHORITY}/${process.env.MS_GRAPH_API_TENANT_ID}`, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| protected isTokenExpired(): boolean { | ||
| if (!this.authToken?.expiresOn) { | ||
| throw new Error('Invalid token: Missing expiresOn property'); | ||
| } | ||
|
|
||
| return Date.now() >= this.authToken.expiresOn.getTime(); | ||
| } | ||
|
|
||
| private async getAuthToken(): Promise<msal.AuthenticationResult> { | ||
| // if we already have a valid token, return it | ||
| if (this.authToken && !this.isTokenExpired()) { | ||
| return this.authToken; | ||
| } | ||
|
|
||
| // cache the promise to prevent multiple simultaneous token requests | ||
| if (!this.tokenPromise) { | ||
| this.tokenPromise = (async () => { | ||
| try { | ||
| this.authToken = await this.msalClient.acquireTokenByClientCredential( | ||
| { | ||
| scopes: [`${this.apiUrl}/.default`], | ||
| } | ||
| ); | ||
|
|
||
| logger.logInfo('Acquired new access token for Microsoft Graph API', { | ||
| expiresOn: this.authToken?.expiresOn, | ||
| }); | ||
| } finally { | ||
| this.tokenPromise = null; | ||
| } | ||
| })(); | ||
| } | ||
|
|
||
| return this.tokenPromise; | ||
| } | ||
|
|
||
| public async send( | ||
| message: MailMessage<SentMessageInfo>, | ||
| callback: (err: Error | null, info: unknown) => void | ||
| ) { | ||
| try { | ||
| const token = await this.getAuthToken(); | ||
|
|
||
| if (!token?.accessToken) { | ||
| throw new Error( | ||
| 'Failed to acquire access token for Microsoft Graph API' | ||
| ); | ||
| } | ||
|
|
||
| const { | ||
| subject, | ||
| to, | ||
| from, | ||
| html, | ||
| bcc, | ||
| attachments = [], | ||
| } = message.data || {}; | ||
|
|
||
| const payload = { | ||
| message: { | ||
| subject: subject || '', | ||
| body: { | ||
| contentType: 'HTML', | ||
| content: html || '', | ||
| }, | ||
| toRecipients: [ | ||
| { | ||
| emailAddress: { | ||
| address: to, | ||
| }, | ||
| }, | ||
| ], | ||
| bccRecipients: bcc | ||
| ? [ | ||
| { | ||
| emailAddress: { | ||
| address: bcc, | ||
| }, | ||
| }, | ||
| ] | ||
| : undefined, | ||
| attachments: attachments, | ||
| }, | ||
| saveToSentItems: true, | ||
| }; | ||
|
|
||
| const response = await fetch( | ||
| `${this.apiUrl}/v1.0/users/${from}/sendMail`, | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${token.accessToken}`, | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify(payload), | ||
| } | ||
| ); | ||
|
|
||
| if (!response.ok) { | ||
| logger.logError('Unable to send email to user', { | ||
| error: response.statusText + ' : ' + response.status, | ||
| }); | ||
|
|
||
| throw new Error( | ||
| `Failed to send email. Status: ${response.status} - ${response.statusText}` | ||
| ); | ||
| } | ||
|
|
||
| const responseData = await response.text(); | ||
| callback(null, { | ||
| envelope: { | ||
| from: from, | ||
| to: [to], | ||
| }, | ||
| messageId: '', | ||
| accepted: [], | ||
| rejected: [], | ||
| pending: [], | ||
| response: responseData, | ||
| }); | ||
| } catch (error: any) { | ||
| logger.logError('Unable to send email to user', { | ||
| error: error, | ||
| }); | ||
|
|
||
| callback(error, null); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export class MSGraphMailService extends TemplateMailService { | ||
| constructor() { | ||
| super(); | ||
| } | ||
|
|
||
| protected createTransport(): NodeMailerTransportOptions { | ||
| return nodemailer.createTransport(new MSGraphTransport()); | ||
| } | ||
|
|
||
| protected createAttachments() { | ||
| const attachments = []; | ||
|
|
||
| if (process.env.EMAIL_FOOTER_IMAGE_PATH !== undefined) { | ||
| if (existsSync(process.env.EMAIL_FOOTER_IMAGE_PATH)) { | ||
| attachments.push({ | ||
| '@odata.type': '#microsoft.graph.fileAttachment', | ||
| name: 'logo.png', | ||
| contentType: 'image/png', | ||
| contentBytes: readFileSync( | ||
| process.env.EMAIL_FOOTER_IMAGE_PATH | ||
| ).toString('base64'), | ||
| }); | ||
| } else { | ||
| logger.logWarn('Email footer image path does not exist', { | ||
| path: process.env.EMAIL_FOOTER_IMAGE_PATH, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return attachments; | ||
| } | ||
| } | ||
2 changes: 1 addition & 1 deletion
2
apps/backend/src/eventHandlers/MailService/SMTP/SMTPMailService.spec.ts
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
bug (maybe): I think this should return 'true'? If the field is missing then intuitively the token should be considered as expired... or?