Skip to content

Commit

Permalink
Added scripts for API to be deployed by cloudflare
Browse files Browse the repository at this point in the history
  • Loading branch information
jiaming committed Mar 19, 2019
1 parent 59e76eb commit db18073
Show file tree
Hide file tree
Showing 4 changed files with 223 additions and 0 deletions.
74 changes: 74 additions & 0 deletions api/src/cloudflare/mailGetHtml.sample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
})

/**
* Making a curl request that looks like
* curl -X POST --data 'key=world' example.com
* or
* curl -X POST --form 'key=world' example.com
*/
async function fetchAndApply(request) {
const myURL = new URL(request.url);
let mailKey = myURL.searchParams.get('mailKey')
if (mailKey == null || mailKey === ""){
return new Response('Missing parameter - `mailKey`',
{ status: 400, statusText: 'No `mailKey` param found' });
}

// Setup the authentication option object
let authenticationKey = this.btoa("api:${MAILGUN_API_KEY}");

let _authOption = {
headers: {
"Authorization" : "BASIC "+authenticationKey
}
};

try {
let [prefix, key, ...remainder] = mailKey.split("-")
// slice the mailgunApi to include the region
let apiUrl = "https://api.mailgun.net/v3"
apiUrl = apiUrl.replace("://", "://"+prefix+".")
let urlWithParams = apiUrl+"/domains/${MAILGUN_EMAIL_DOMAIN}/messages/"+key;
const response = await fetchGet(urlWithParams, _authOption);

let body = response["body-html"] || response["body-plain"]
if( body === undefined || body == null) {
body = 'The kittens found no messages :('
}

// Add JS injection to force all links to open as a new tab
// instead of opening inside the iframe
body += '<script>' +
'let linkArray = document.getElementsByTagName("a");' +
'for (let i=0; i<linkArray.length; ++i) { linkArray[i].target="_blank"; }' +
// eslint-disable-next-line
'<\/script>'

let responseInit = {
headers: {
"Content-Type": "application/json"
}
}
return new Response(body, responseInit)
} catch (err) {
return new Response(err)
}
}


/**
* Simple fetch get, with response data
* @param {String} urlWithParams
* @param {Object} options
*/
var fetchGet = function(urlWithParams, options){
return new Promise(function(resolve, reject){
fetch(urlWithParams, options).then(response => {
resolve(response.json())
}).catch(e => {
reject(e)
})
})
}
83 changes: 83 additions & 0 deletions api/src/cloudflare/mailGetKey.sample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
})

/**
* Making a curl request that looks like
* curl -X POST --data 'key=world' example.com
* or
* curl -X POST --form 'key=world' example.com
*/
async function fetchAndApply(request) {
const myURL = new URL(request.url);
let mailKey = myURL.searchParams.get('mailKey')
if (mailKey == null || mailKey === ""){
return new Response('Missing parameter - `mailKey`',
{ status: 400, statusText: 'No `mailKey` param found' });
}

// Setup the authentication option object
let authenticationKey = this.btoa("api:${MAILGUN_API_KEY}");

let _authOption = {
headers: {
"Authorization" : "BASIC "+authenticationKey
}
};

try {
let [prefix, key, ...remainder] = mailKey.split("-")
// slice the mailgunApi to include the region
let apiUrl = "https://api.mailgun.net/v3"
apiUrl = apiUrl.replace("://", "://"+prefix+".")
let urlWithParams = apiUrl+"/domains/${MAILGUN_EMAIL_DOMAIN}/messages/"+key;
const response = await fetchGet(urlWithParams, _authOption);

let emailDetails = {}

// Format and extract the name of the user
let [name, ...rest] = formatName(response.from)
emailDetails.name = name

// Extract the rest of the email domain after splitting
if (rest[0].length > 0) {
emailDetails.emailAddress = ' <' + rest
}

// Extract the subject of the response
emailDetails.subject = response.subject

// Extract the recipients
emailDetails.recipients = response.recipients

let responseInit = {
headers: {
"Content-Type": "application/json"
}
}
return new Response(JSON.stringify(emailDetails), responseInit)
} catch (err) {
return new Response(err)
}
}


/**
* Simple fetch get, with response data
* @param {String} urlWithParams
* @param {Object} options
*/
var fetchGet = function(urlWithParams, options){
return new Promise(function(resolve, reject){
fetch(urlWithParams, options).then(response => {
resolve(response.json())
}).catch(e => {
reject(e)
})
})
}

function formatName (sender) {
let [name, ...rest] = sender.split(' <')
return [name, rest]
}
61 changes: 61 additions & 0 deletions api/src/cloudflare/mailList.sample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
})

/**
* Making a curl request that looks like
* curl -X POST --data 'key=world' example.com
* or
* curl -X POST --form 'key=world' example.com
*/
async function fetchAndApply(request) {
const myURL = new URL(request.url);
let recipient = myURL.searchParams.get('recipient')

if (recipient == null){
return new Response('Missing parameter - `recipient`',
{ status: 400, statusText: 'No `recipient` param found' });
}

// strip off all @domain if there is any
if(recipient.indexOf("@") >= 0){
recipient = recipient.substring(0, recipient.indexOf("@"))
}

// Setup the authentication option object
let authenticationKey = this.btoa("api:${MAILGUN_API_KEY}");

let _authOption = {
headers: {
"Authorization" : "BASIC "+authenticationKey
}
};

try {
const postData = await fetchGet("https://api.mailgun.net/v3/${MAILGUN_EMAIL_DOMAIN}/events?recipient="+recipient+"@${MAILGUN_EMAIL_DOMAIN}", _authOption);
let responseInit = {
headers: {
"Content-Type": "application/json"
}
}
return new Response(JSON.stringify(postData.items), responseInit)
} catch (err) {
return new Response(err)
}
}


/**
* Simple fetch get, with response data
* @param {String} urlWithParams
* @param {Object} options
*/
var fetchGet = function(urlWithParams, options){
return new Promise(function(resolve, reject){
fetch(urlWithParams, options).then(response => {
resolve(response.json())
}).catch(e => {
reject(e)
})
})
}
5 changes: 5 additions & 0 deletions config.sh
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,8 @@ export WEBSITE_DOMAIN="$WEBSITE_DOMAIN"
echo ">> Applying config settings"
cat "$projectDir/api/config/mailgunConfig.sample.js" | envsubst > "$projectDir/api/config/mailgunConfig.js"
cat "$projectDir/ui/config/apiconfig.sample.js" | envsubst > "$projectDir/ui/config/apiconfig.js"

echo ">> Applying to cloudflare scripts"
cat "$projectDir/api/src/cloudflare/mailList.sample.js" | envsubst > "$projectDir/api/src/cloudflare/mailList.js"
cat "$projectDir/api/src/cloudflare/mailGetKey.sample.js" | envsubst > "$projectDir/api/src/cloudflare/mailGetKey.js"
cat "$projectDir/api/src/cloudflare/mailGetHtml.sample.js" | envsubst > "$projectDir/api/src/cloudflare/mailGetHtml.js"

0 comments on commit db18073

Please sign in to comment.