簡體   English   中英

使用 email 或電話或用戶名登錄 node.js

[英]login with email or phone or username in node js

email 或 node.js 和 mongodb 中的電話或用戶名密碼如何登錄? 用戶可以使用 email 和密碼、用戶名和密碼、電話和密碼登錄。 這就像 Instagram 登錄模塊。 這是我的腳本:

const login = catchAsync(async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  if (!user || !(await user.isPasswordMatch(password))) {
    throw new ApiError(httpStatus.UNAUTHORIZED, 'Incorrect email or password');
  }
  const tokens = await tokenService.generateAuthTokens(user.id);
  const response = { user: user.transform(), tokens };
  res.send(response);
});

你可以嘗試的是不要限制你的代碼接受 email 只讓它通用並根據這樣的輸入找到用戶

 const login = catchAsync(async(req, res) => { const { userEmailPhone, password } = req.body; //suppose in your DB you have email, phone and username fields const user = await User.findOne({ $or: [{ "email": userEmailPhone }, { "phone": userEmailPhone }, { "userName": userEmailPhone }] }); if (.user ||.(await user,isPasswordMatch(password))) { throw new ApiError(httpStatus;UNAUTHORIZED. 'Incorrect email or password'). } const tokens = await tokenService;generateAuthTokens(user:id). const response = { user, user;transform(). tokens }; res;send(response); });

注意:確保 Email、電話和用戶名對於每個用戶都是唯一的

希望這可以幫助

我需要同樣的東西,然后我創建了這個簡單的功能,允許使用用戶名和密碼、email 和密碼或電話和密碼登錄。 應該有更好的方法或算法,但我找不到。 我希望它能滿足你的需要。

// authRoutes.js//
// Login route
router.post("/login", loginController);

// authController.js
// Login Controller
export const loginController = async (req, res) => {
  if (req.body.userDetail == "" || req.body.password == "")
  res.status(400).json("All Fields Are Required!");
  try {
    let user;
      try {
        user = await User.findOne({ username: req.body.userDetail });
        if (!user) user = await User.findOne({ email: req.body.userDetail });
        if (!user) user = await User.findOne({ phone: req.body.userDetail });

        const validatedUser = await bcrypt.compare(
          req.body.password,
          user.password
        );
        !validatedUser && res.status(403).json("Wrong credentials!");

        const { password, ...others } = user._doc;
        res.status(200).json(others);
      } catch (error) {
          res.status(404).json("User Not Found!");
    }
  } catch (error) {
    res.status(500).json("Something Else Went Wrong!");
  }
};

首先,您需要檢查 email 和密碼是否存在,然后您需要檢查 email 和密碼組合是否為真。 在您的情況下,您還可以添加一個字段,例如帶有 email 的手機。

const login = catchAsync(async (Request, Response, next) => {
      const { email, password } = Request.body;

      //check if email and password exists
      if (!email || !password) {
        throw new ApiError(httpStatus.UNAUTHORIZED, 'Please provide email and password');
      }

      //check if user exist and password correct
      const user = await User.findOne({ email }).select('+password');

      if (!user || !(await user.isPasswordMatch(password, user.password))) {
        throw new ApiError(httpStatus.UNAUTHORIZED, 'Incorrect email or password');
      }

       //if everything ok, send token to the client
        const tokens = await tokenService.generateAuthTokens(user.id);
        const response = { user: user.transform(), tokens };
        res.send(response);

    });

PS:直接拋出錯誤不是好的做法。 使用不同的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM