Add email integration to be able to broadcast emails to all users.

Resolves #388
This commit is contained in:
Kurt Hutten
2021-06-29 06:37:04 +10:00
parent 7ef8d8d1ff
commit 0da15443cb
13 changed files with 173 additions and 5 deletions

View File

@@ -1,4 +1,4 @@
import { createUserInsecure } from 'src/services/users/users.js'
import { createUserInsecure } from 'src/services/users/users'
import { db } from 'src/lib/db'
import { sentryWrapper } from 'src/lib/sentry'
import { enforceAlphaNumeric, generateUniqueString } from 'src/services/helpers'

View File

@@ -0,0 +1,22 @@
export const schema = gql`
type Envelope {
from: String
to: [String!]!
}
type EmailResponse {
accepted: [String!]!
rejected: [String!]!
messageId: String!
envelope: Envelope
}
input Email {
subject: String!
body: String!
}
type Mutation {
sendAllUsersEmail(input: Email!): EmailResponse!
}
`

View File

@@ -121,7 +121,8 @@ export const getCurrentUser = async (decoded, { _token, _type }) => {
* requireAuth({ role: ['editor', 'author'] })
* requireAuth({ role: ['publisher'] })
*/
export const requireAuth = ({ role } = {}) => {
export const requireAuth = ({ role }: {role?: string | string[]} = {}) => {
console.log(context.currentUser)
if (!context.currentUser) {
throw new AuthenticationError("You don't have permission to do that.")
}

View File

@@ -0,0 +1,56 @@
import nodemailer, {SendMailOptions} from 'nodemailer'
interface Args {
to: SendMailOptions['to']
from: SendMailOptions['from']
subject: string
text: string
}
interface SuccessResult {
accepted: string[]
rejected: string[]
envelopeTime: number
messageTime: number
messageSize: number
response: string
envelope: {
from: string | false,
to: string[]
},
messageId: string
}
export function sendMail({to, from, subject, text}: Args): Promise<SuccessResult> {
let transporter = nodemailer.createTransport({
host: 'smtp.mailgun.org',
port: 587,
secure: false,
tls: {
ciphers:'SSLv3'
},
auth: {
user: 'postmaster@mail.cadhub.xyz',
pass: process.env.EMAIL_PASSWORD
}
});
console.log({to, from, subject, text});
const emailPromise = new Promise((resolve, reject) => {
transporter.sendMail({
from,
to,
subject,
text,
}, (error, info) => {
if (error) {
reject(error);
} else {
resolve(info);
}
});
}) as any as Promise<SuccessResult>
return emailPromise
}

View File

@@ -0,0 +1,18 @@
import { requireAuth } from 'src/lib/auth'
import {sendMail} from 'src/lib/sendmail'
import {users} from 'src/services/users/users'
export const sendAllUsersEmail = async ({input: {body, subject}}) => {
requireAuth({ role: 'admin' })
const recipients = (await users()).map(({email}) => email)
const from = {
address:'news@mail.cadhub.xyz',
name: 'CadHub',
}
return sendMail({
to: recipients,
from,
subject,
text: body,
})
}