utils.js
1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { PrismaClient } from "@prisma/client";
import { nouns, adjectives } from "./words";
import jwt from "jsonwebtoken";
import nodemailer from "nodemailer";
import sgTransport from "nodemailer-sendgrid-transport";
export const prisma = new PrismaClient();
export const getUserId = (context) => {
const Authorization = context.request.get("Authorization");
if (Authorization) {
const token = Authorization.replace("Bearer ", "");
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
return userId;
}
throw new Error("There is no vaild user");
};
export const generateSecret = () => {
const randomNumber = Math.floor(Math.random() * adjectives.length);
return `${adjectives[randomNumber]} ${nouns[randomNumber]}`;
};
const sendEmail = (email) => {
const options = {
auth: {
api_user: process.env.SENDGRID_USERNAME,
api_password: process.env.SENDGRID_PASSWORD,
},
};
const client = nodemailer.createTransport(sgTransport(options));
return client.sendMail(email);
};
export const sendSecretMail = (address, emailSecret, value) => {
const email = {
from: "vel1024@khu.ac.kr",
to: address,
subject: `Authentication key for forgotten ${value}`,
html: `Hello, This is khuchat, authentication key is <b>${emailSecret}</b>, copy and paste it, Thanks.`,
};
return sendEmail(email);
};
export const generateToken = (id) => jwt.sign({ id }, process.env.JWT_SECRET);