Skip to content

Instantly share code, notes, and snippets.

@polluterofminds
Last active January 13, 2021 17:59
Show Gist options
  • Save polluterofminds/b26d5b5f8058b770c3e56ce5d3e7235c to your computer and use it in GitHub Desktop.
Save polluterofminds/b26d5b5f8058b770c3e56ce5d3e7235c to your computer and use it in GitHub Desktop.
subscribe to posts
import axios from "axios";
import jwt from "jsonwebtoken";
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey("SENDGRID API KEY");
const SECRET = "MY SUPER SECRET SIGNING KEY";
const config = {
headers: {
Authorization:
"Bearer PINATA JWT",
"Content-Type": "application/json",
},
};
export const checkSubscriptions = async (email) => {
try {
const query = { value: email, op: "eq" };
const res = await axios.get(
`https://api.pinata.cloud/data/pinList?status=pinned&metadata[keyvalues][email]=${JSON.stringify(
query
)}`,
config
);
if (res.data.count !== 0) {
return true;
}
return false;
} catch (error) {
throw error;
}
};
const createNewSubscription = async (email) => {
const data = {
subscriptionaDate: new Date().toISOString(),
};
const body = {
pinataMetadata: {
name: email,
keyvalues: {
email,
},
},
pinataContent: data,
};
await axios.post(
`https://api.pinata.cloud/pinning/pinJSONToIPFS`,
JSON.stringify(body),
config
);
return;
}
export const createJWT = async (email) => {
try {
const data = {
email,
}
const token = await jwt.sign(
{
data,
},
SECRET,
{ expiresIn: "48h" }
);
return token;
} catch (error) {
throw error;
}
};
export const sendEmail = async (email, token) => {
try {
const msg = {
to: email,
from: 'justin.edward.hunter@gmail.com',
subject: 'Log Into Pinnie For Your Thoughts',
text: `To log into Pinnie For Your Thoughts, click this link or paste it in your browser: http://localhost:3000/verify?token=${token}`,
html: `<p>To log into Pinnie For Your Thoughts, click this link or paste it in your browser: <a href="http://localhost:3000/verify?token=${token}">Log in link</a></p>`,
};
await sgMail.send(msg);
} catch (error) {
throw error;
}
}
export default async (req, res) => {
try {
// Check for existing subscription
const existingSubscription = await checkSubscriptions(req.body.email);
if (existingSubscription) {
return res.status(400).send("Subscription exists for this email");
}
// Create a new subscription
await createNewSubscription(req.body.email);
// Create the JWT
const token = await createJWT(req.body.email);
// send email
await sendEmail(req.body.email, token);
res.status(200).send("Success");
} catch (error) {
console.log(error);
res.status(500).send("Server error");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment