233 lines
6.9 KiB
TypeScript
233 lines
6.9 KiB
TypeScript
import redis from "../connection/redis";
|
|
import tokenModel from "../model/tokenModel";
|
|
import nodemailer from "nodemailer";
|
|
import userModel from "../model/userModel";
|
|
import { hashGenerate, hashValidator } from "../utils/hashing";
|
|
import { tokenGenerator, tokenRefreshGenerator } from "../utils/token";
|
|
import userDataModel from "../model/userDataModel";
|
|
|
|
interface Iresponse {
|
|
status: string;
|
|
data?: any;
|
|
}
|
|
interface Isignup {
|
|
userName: string;
|
|
email: string;
|
|
password: string;
|
|
confirmPassword: string;
|
|
}
|
|
interface Isignin {
|
|
email: string;
|
|
password: string;
|
|
}
|
|
interface IforGotPassword {
|
|
email: string;
|
|
}
|
|
|
|
export async function existingUserData(email: string, organization: string) {
|
|
const existingData = await userModel(organization).findOne({
|
|
email: email,
|
|
isArchive: false,
|
|
});
|
|
return existingData;
|
|
}
|
|
export const signupService = async (data: Isignup): Promise<Iresponse> => {
|
|
const { userName, email, password, confirmPassword } = data;
|
|
try {
|
|
const mailCaseChange = email.toLocaleLowerCase();
|
|
const organization = email.split("@")[1].split(".")[0];
|
|
const mailExistance = await existingUserData(mailCaseChange, organization);
|
|
if (mailExistance !== null) return { status: "User Already exists" };
|
|
if (password !== confirmPassword) {
|
|
return { status: "Passwords do not match" };
|
|
}
|
|
let role;
|
|
const passwordHashed = await hashGenerate(password);
|
|
const userCount = await userModel(organization).countDocuments({});
|
|
role = userCount === 0 ? "Admin" : "Viewer";
|
|
const newUser = await userModel(organization).create({
|
|
userName,
|
|
email: mailCaseChange,
|
|
password: passwordHashed,
|
|
role,
|
|
});
|
|
if (!newUser) return { status: "Signup unsuccessfull" };
|
|
return { status: "Success" };
|
|
} catch (error: unknown) {
|
|
if (error instanceof Error) {
|
|
return {
|
|
status: error.message,
|
|
};
|
|
} else {
|
|
return {
|
|
status: "An unexpected error occurred",
|
|
};
|
|
}
|
|
}
|
|
};
|
|
|
|
export const signinService = async (data: Isignin): Promise<Iresponse> => {
|
|
const { email, password } = data;
|
|
try {
|
|
const mailCaseChange = email.toLocaleLowerCase();
|
|
const organization = email.split("@")[1].split(".")[0];
|
|
const mailExistance = await existingUserData(mailCaseChange, organization);
|
|
if (mailExistance == null)
|
|
return { status: "User not found!!! Kindly Signup" };
|
|
const comparePassword = await hashValidator(
|
|
password,
|
|
mailExistance.password
|
|
);
|
|
if (!comparePassword)
|
|
return { status: "Password is invalid...Check the credentials" };
|
|
const userDataExistence = await userDataModel(organization).findOne({
|
|
userId: mailExistance._id,
|
|
isArchive: false,
|
|
});
|
|
if (!userDataExistence) {
|
|
const userDatacreation = await userDataModel(organization).create({
|
|
userId: mailExistance._id,
|
|
});
|
|
}
|
|
const tokenValidation = tokenGenerator(
|
|
mailExistance.email,
|
|
mailExistance.role,
|
|
mailExistance._id,
|
|
organization
|
|
);
|
|
const refreshTokenvalidation = tokenRefreshGenerator(
|
|
mailExistance.email,
|
|
mailExistance.role,
|
|
mailExistance._id,
|
|
organization
|
|
);
|
|
const existingToken = await tokenModel(organization).findOne({
|
|
userId: mailExistance._id,
|
|
isArchive: false,
|
|
});
|
|
let finalResult;
|
|
if (!existingToken) {
|
|
const tokenSave = await tokenModel(organization).create({
|
|
userId: mailExistance._id,
|
|
isArchive: false,
|
|
refreshToken: refreshTokenvalidation,
|
|
});
|
|
// await redis.setex(
|
|
// `user:${mailExistance.Email}`,
|
|
// 3600,
|
|
// JSON.stringify(tokenSave)
|
|
// );
|
|
finalResult = {
|
|
message: "login successfull",
|
|
email: mailExistance.email,
|
|
name: mailExistance.userName,
|
|
userId: mailExistance._id,
|
|
token: tokenValidation,
|
|
refreshToken: refreshTokenvalidation,
|
|
};
|
|
} else {
|
|
finalResult = {
|
|
message: "login successfull",
|
|
email: mailExistance.email,
|
|
name: mailExistance.userName,
|
|
userId: mailExistance._id,
|
|
token: tokenValidation,
|
|
refreshToken: existingToken.refreshToken,
|
|
};
|
|
}
|
|
return { status: "Success", data: finalResult };
|
|
} catch (error: unknown) {
|
|
if (error instanceof Error) {
|
|
return {
|
|
status: error.message,
|
|
};
|
|
} else {
|
|
return {
|
|
status: "An unexpected error occurred",
|
|
};
|
|
}
|
|
}
|
|
};
|
|
|
|
export const forgetPassword = async ({
|
|
email,
|
|
}: IforGotPassword): Promise<{ status: string }> => {
|
|
try {
|
|
const mailCaseChange = email.toLocaleLowerCase();
|
|
const organization = email.split("@")[1].split(".")[0];
|
|
const Existing_User = await existingUserData(mailCaseChange, organization);
|
|
if (Existing_User) {
|
|
// if (Existing_User.lastPasswordReset) {
|
|
// console.log("if2");
|
|
// const lastPasswordReset = Existing_User.lastPasswordReset;
|
|
// const now = Date.now();
|
|
// const timeDiff = now - lastPasswordReset;
|
|
// const diffInHours = Math.floor(timeDiff / (1000 * 60 * 60));
|
|
// if (diffInHours < 24)
|
|
// return {
|
|
// status: "You can only reset your password once every 24 hours.",
|
|
// };
|
|
// }
|
|
const transport = nodemailer.createTransport({
|
|
service: "gmail",
|
|
secure: true,
|
|
auth: {
|
|
user: process.env.EMAIL_USER,
|
|
pass: process.env.EMAIL_PASS,
|
|
},
|
|
});
|
|
// const resetToken = tokenGenerator(
|
|
// email,
|
|
// Existing_User.Role as string,
|
|
// Existing_User._id as string,
|
|
// organization
|
|
// );
|
|
// const userTokenData = await tokenModel(organization).findOne({
|
|
// userId: Existing_User._id,
|
|
// isArchive: false,
|
|
// });
|
|
// if (!userTokenData) {
|
|
// await tokenModel(organization).create({
|
|
// // Email: Existing_User.Email,
|
|
// userId: Existing_User._id,
|
|
// resetToken: resetToken,
|
|
// resetTokenExpiry: Date.now(),
|
|
// });
|
|
// } else {
|
|
// userTokenData.resetToken = resetToken;
|
|
// userTokenData.resetTokenExpiry = new Date();
|
|
// await userTokenData.save();
|
|
// }
|
|
const Receiver = {
|
|
from: process.env.EMAIL_USER,
|
|
to: email,
|
|
subject: "Password Reset Request",
|
|
// text: "test mail",
|
|
text: `Click the below link to generate the new password \n ${
|
|
process.env.CLIENT_URL
|
|
}/reset-password/${tokenGenerator(
|
|
email,
|
|
Existing_User.Role as string,
|
|
Existing_User._id as string,
|
|
organization
|
|
)}`,
|
|
};
|
|
await transport.sendMail(Receiver);
|
|
|
|
return { status: "Success" };
|
|
} else {
|
|
return { status: "Email not found" };
|
|
}
|
|
} catch (error: unknown) {
|
|
if (error instanceof Error) {
|
|
return {
|
|
status: error.message,
|
|
};
|
|
} else {
|
|
return {
|
|
status: "An unexpected error occurred",
|
|
};
|
|
}
|
|
}
|
|
};
|