335 lines
9.4 KiB
JavaScript
335 lines
9.4 KiB
JavaScript
const path = require("path");
|
|
require("dotenv").config({
|
|
path: path.resolve(process.cwd(), `.env.${process.env.NODE_ENV || "development"}`)
|
|
});
|
|
|
|
const admin = require("firebase-admin");
|
|
const logger = require("../utils/logger");
|
|
//const { sendProManagerWelcomeEmail } = require("../email/sendemail");
|
|
const client = require("../graphql-client/graphql-client").client;
|
|
const serviceAccount = require(process.env.FIREBASE_ADMINSDK_JSON);
|
|
//const generateEmailTemplate = require("../email/generateTemplate");
|
|
|
|
admin.initializeApp({
|
|
credential: admin.credential.cert(serviceAccount),
|
|
databaseURL: process.env.FIREBASE_DATABASE_URL
|
|
});
|
|
|
|
const createUser = async (req, res) => {
|
|
logger.log("admin-create-user", "debug", req.user.email, null, {
|
|
request: req.body,
|
|
ioadmin: true
|
|
});
|
|
|
|
const { email, displayName, password, shopid, authlevel, validemail } = req.body;
|
|
|
|
try {
|
|
const userRecord = await admin.auth().createUser({ email, displayName, password });
|
|
|
|
// See the UserRecord reference doc for the contents of userRecord.
|
|
|
|
const result = await client.request(
|
|
`
|
|
mutation INSERT_USER($user: users_insert_input!) {
|
|
insert_users_one(object: $user) {
|
|
email
|
|
}
|
|
}
|
|
`,
|
|
{
|
|
user: {
|
|
email: email.toLowerCase(),
|
|
authid: userRecord.uid,
|
|
validemail,
|
|
associations: {
|
|
data: [{ shopid, authlevel, active: true }]
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
res.json({ userRecord, result });
|
|
} catch (error) {
|
|
logger.log("admin-update-user-error", "ERROR", req.user.email, null, {
|
|
error
|
|
});
|
|
res.status(500).json(error);
|
|
}
|
|
};
|
|
|
|
// const sendPromanagerWelcomeEmail = (req, res) => {
|
|
// const { authid, email } = req.body;
|
|
|
|
// // Fetch user from Firebase
|
|
// admin
|
|
// .auth()
|
|
// .getUser(authid)
|
|
// .then((userRecord) => {
|
|
// if (!userRecord) {
|
|
// return Promise.reject({ status: 404, message: "User not found in Firebase." });
|
|
// }
|
|
|
|
// // Fetch user data from the database using GraphQL
|
|
// return client.request(
|
|
// `
|
|
// query GET_USER_BY_EMAIL($email: String!) {
|
|
// users(where: { email: { _eq: $email } }) {
|
|
// email
|
|
// validemail
|
|
// associations {
|
|
// id
|
|
// shopid
|
|
// bodyshop {
|
|
// id
|
|
// convenient_company
|
|
// }
|
|
// }
|
|
// }
|
|
// }`,
|
|
// { email: email.toLowerCase() }
|
|
// );
|
|
// })
|
|
// .then((dbUserResult) => {
|
|
// const dbUser = dbUserResult?.users?.[0];
|
|
// if (!dbUser) {
|
|
// return Promise.reject({ status: 404, message: "User not found in database." });
|
|
// }
|
|
|
|
// // Validate email before proceeding
|
|
// if (!dbUser.validemail) {
|
|
// logger.log("admin-send-welcome-email-skip", "debug", req.user.email, null, {
|
|
// message: "User email is not valid, skipping email.",
|
|
// email
|
|
// });
|
|
// return res.status(200).json({ message: "User email is not valid, email not sent." });
|
|
// }
|
|
|
|
// // Check if the user's company is ProManager
|
|
// const convenientCompany = dbUser.associations?.[0]?.bodyshop?.convenient_company;
|
|
// if (convenientCompany !== "promanager") {
|
|
// logger.log("admin-send-welcome-email-skip", "debug", req.user.email, null, {
|
|
// message: 'convenient_company is not "promanager", skipping email.',
|
|
// convenientCompany
|
|
// });
|
|
// return res.status(200).json({ message: `convenient_company is not "promanager", email not sent.` });
|
|
// }
|
|
|
|
// // Generate password reset link
|
|
// return admin
|
|
// .auth()
|
|
// .generatePasswordResetLink(dbUser.email)
|
|
// .then((resetLink) => ({ dbUser, resetLink }));
|
|
// })
|
|
// .then(({ dbUser, resetLink }) => {
|
|
// // Send welcome email (replace with your actual email-sending service)
|
|
// return sendProManagerWelcomeEmail({
|
|
// to: dbUser.email,
|
|
// subject: "Welcome to the ProManager platform.",
|
|
// html: generateEmailTemplate({
|
|
// header: "",
|
|
// subHeader: "",
|
|
// body: `
|
|
// <p>Welcome to the ProManager platform. Please click the link below to reset your password:</p>
|
|
// <p><a href="${resetLink}">Reset your password</a></p>
|
|
// <p>User Details:</p>
|
|
// <ul>
|
|
// <li>Email: ${dbUser.email}</li>
|
|
// </ul>
|
|
// `
|
|
// })
|
|
// });
|
|
// })
|
|
// .then(() => {
|
|
// // Log success and return response
|
|
// logger.log("admin-send-welcome-email", "debug", req.user.email, null, {
|
|
// request: req.body,
|
|
// ioadmin: true,
|
|
// emailSentTo: email
|
|
// });
|
|
// res.status(200).json({ message: "Welcome email sent successfully." });
|
|
// })
|
|
// .catch((error) => {
|
|
// logger.log("admin-send-welcome-email-error", "ERROR", req.user.email, null, { error });
|
|
|
|
// if (!res.headersSent) {
|
|
// res.status(error.status || 500).json({
|
|
// message: error.message || "Error sending welcome email.",
|
|
// error
|
|
// });
|
|
// }
|
|
// });
|
|
// };
|
|
|
|
const updateUser = (req, res) => {
|
|
logger.log("admin-update-user", "debug", req.user.email, null, {
|
|
request: req.body,
|
|
ioadmin: true
|
|
});
|
|
|
|
admin
|
|
.auth()
|
|
.updateUser(
|
|
req.body.uid,
|
|
req.body.user
|
|
// {
|
|
// email: "modifiedUser@example.com",
|
|
// phoneNumber: "+11234567890",
|
|
// emailVerified: true,
|
|
// password: "newPassword",
|
|
// displayName: "Jane Doe",
|
|
// photoURL: "http://www.example.com/12345678/photo.png",
|
|
// disabled: true,
|
|
// }
|
|
)
|
|
.then((userRecord) => {
|
|
// See the UserRecord reference doc for the contents of userRecord.
|
|
|
|
logger.log("admin-update-user-success", "debug", req.user.email, null, {
|
|
userRecord,
|
|
ioadmin: true
|
|
});
|
|
res.json(userRecord);
|
|
})
|
|
.catch((error) => {
|
|
logger.log("admin-update-user-error", "ERROR", req.user.email, null, {
|
|
error
|
|
});
|
|
res.status(500).json(error);
|
|
});
|
|
};
|
|
|
|
const getUser = (req, res) => {
|
|
logger.log("admin-get-user", "debug", req.user.email, null, {
|
|
request: req.body,
|
|
ioadmin: true
|
|
});
|
|
|
|
admin
|
|
.auth()
|
|
.getUser(req.body.uid)
|
|
.then((userRecord) => {
|
|
return client
|
|
.request(
|
|
`
|
|
query GET_USER_BY_AUTHID($authid: String!) {
|
|
users(where: { authid: { _eq: $authid } }) {
|
|
email
|
|
validemail
|
|
associations {
|
|
id
|
|
shopid
|
|
bodyshop {
|
|
id
|
|
convenient_company
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`,
|
|
{ authid: req.body.uid }
|
|
)
|
|
.then((dbUserResult) => {
|
|
res.json({
|
|
...userRecord,
|
|
db: {
|
|
validemail: dbUserResult?.users?.[0]?.validemail,
|
|
company: dbUserResult?.users?.[0]?.associations?.[0]?.bodyshop?.convenient_company
|
|
}
|
|
});
|
|
});
|
|
})
|
|
.catch((error) => {
|
|
logger.log("admin-get-user-error", "ERROR", req.user.email, null, {
|
|
error
|
|
});
|
|
res.status(500).json(error);
|
|
});
|
|
};
|
|
|
|
const sendNotification = async (req, res) => {
|
|
setTimeout(() => {
|
|
// Send a message to the device corresponding to the provided
|
|
// registration token.
|
|
admin
|
|
.messaging()
|
|
.send({
|
|
topic: "PRD_PATRICK-messaging",
|
|
notification: {
|
|
title: `ImEX Online Message - `,
|
|
body: "Test Noti."
|
|
//imageUrl: "https://thinkimex.com/img/io-fcm.png",
|
|
},
|
|
data: {
|
|
type: "messaging-inbound",
|
|
conversationid: "e0eb17c3-3a78-4e3f-b932-55ef35aa2297",
|
|
text: "Hello. ",
|
|
image_path: "",
|
|
phone_num: "+16049992002"
|
|
}
|
|
})
|
|
.then((response) => {
|
|
// Response is a message ID string.
|
|
logger.log("Successfully sent message:", "debug", req?.user?.email, null, {
|
|
response
|
|
});
|
|
})
|
|
.catch((error) => {
|
|
logger.log("Successfully sent message:", "error", req?.user?.email, null, {
|
|
error
|
|
});
|
|
});
|
|
|
|
res.sendStatus(200);
|
|
}, 500);
|
|
};
|
|
|
|
const subscribe = async (req, res) => {
|
|
const result = await admin
|
|
.messaging()
|
|
.subscribeToTopic(req.body.fcm_tokens, `${req.body.imexshopid}-${req.body.type}`);
|
|
|
|
res.json(result);
|
|
};
|
|
|
|
const unsubscribe = async (req, res) => {
|
|
try {
|
|
const result = await admin
|
|
.messaging()
|
|
.unsubscribeFromTopic(req.body.fcm_tokens, `${req.body.imexshopid}-${req.body.type}`);
|
|
|
|
res.json(result);
|
|
} catch (error) {
|
|
logger.log("admin-unsubscribe-error", "ERROR", req.user.email, null, { error: error.message });
|
|
res.sendStatus(500);
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
admin,
|
|
createUser,
|
|
updateUser,
|
|
getUser,
|
|
//sendPromanagerWelcomeEmail,
|
|
sendNotification,
|
|
subscribe,
|
|
unsubscribe
|
|
};
|
|
|
|
//Admin claims code.
|
|
// const uid = "JEqqYlsadwPEXIiyRBR55fflfko1";
|
|
|
|
// admin
|
|
// .auth()
|
|
// .getUser(uid)
|
|
// .then((user) => {
|
|
// console.log(user);
|
|
// admin.auth().setCustomUserClaims(uid, {
|
|
// ioadmin: true,
|
|
// "https://hasura.io/jwt/claims": {
|
|
// "x-hasura-default-role": "debug",
|
|
// "x-hasura-allowed-roles": ["admin"],
|
|
// "x-hasura-user-id": uid,
|
|
// },
|
|
// });
|
|
// });
|