Admin Sign & Access Token

 avatar
Anis
plain_text
7 months ago
2.5 kB
2
Indexable
Never
// Admin signIn
const signIn = async (adminInfo) => {
  try {
    const { email, password } = adminInfo;
    const existingAdmin = await Admin.findOne({ email });

    if (existingAdmin) {
      const validPassword = await validatePassword(
        password,
        existingAdmin.password,
        existingAdmin.salt
      );

      if (validPassword) {
        const accessToken = await generateSignature(
          {
            email: existingAdmin.email,
            role: existingAdmin.role,
          },
          60 * 60 * 24 // 1 Day
        );

        const refreshToken = await generateSignature(
          {
            email: existingAdmin.email,
            role: existingAdmin.role,
          },
          60 * 60 * 24 * 7 // 7 Days
        );

        const admin = exclude(existingAdmin.toObject(), [
          "_id",
          "__v",
          "verify_code",
          "password",
          "salt",
          "forget_code",
          "createdAt",
          "updatedAt",
        ]);

        return {
          status: true,
          message: "Admin Login Successfully!",
          data: {
            accessToken,
            refreshToken,
            expiresIn: new Date().setTime(new Date().getTime() + EXPIRE_TIME),
            ...admin,
            role: "admin",
          },
        };
      } else {
        return {
          status: false,
          message: "Your credentials are incorrect!",
        };
      }
    } else {
      return {
        status: false,
        message: "Your credentials are incorrect!",
      };
    }
  } catch (error) {
    console.error("Error in Sign In:", error);
    throw new Error("Failed to Sign In admin");
  }
};

// Get Access Token
const getAccessToken = async (adminInfo) => {
  try {
    const accessToken = await generateSignature(
      {
        email: adminInfo.email,
        role: adminInfo.role,
      },
      60 * 60 * 24 // 1 Day
    );

    const refreshToken = await generateSignature(
      {
        email: adminInfo.email,
        role: adminInfo.role,
      },
      60 * 60 * 24 * 7 // 7 Days
    );

    return {
      status: true,
      message: "Access Token refresh successfully!",
      data: {
        accessToken,
        refreshToken,
        expiresIn: new Date().setTime(new Date().getTime() + EXPIRE_TIME),
      },
    };
  } catch (error) {
    console.error("Error in Sign In:", error);
    throw new Error("Failed to Sign In user");
  }
};
Leave a Comment