skip to Main Content

I’ve building an api backend for a mobile app built with react-native. And mobile developer has provided a json data file by mobile developer with the following data format.

{
  "firstName": "John",
  "imageURL": "https:link-to-image.com/file.jpg",
  "lastName": "Joe",
  "linkURL": null,
  "middleName": null,
  "name": "John Doe",
  "userID": "1234567890"
}

He’s using react native fbsdk next in react-native to get user information from facebook.

I have the following routes setup:

auth.js

router.post(
  "/facebook/signup",
  [
    body("facebookUserId")
      .not()
      .isEmpty()
      .withMessage("Facebook user id is required"),
    body("name").not().isEmpty().withMessage("Name is required"),
  ],
  controller.userRegisterWithFacebook
);

router.post(
  "/facebook/login",
  [
    body("facebookUserId")
      .not()
      .isEmpty()
      .withMessage("Facebook user id is required"),
  ],
  controller.loginWithFacebook
);

And my controller:

exports.userRegisterWithFacebook = async (req, res, next) => {
  const { facebookUserId, name } = req.body;
  try {
    validateRequest(req);
    const user = await User.findOne({ facebookUserId: facebookUserId });
    if (user) {
      res
        .status(422)
        .json({ message: "User already registered. Please login." });
    }
    const newUser = new User({
      name: name,
      facebookUserId: facebookUserId,
    });

     await newUser.save();

    res.status(200).json({
      message: "User registered successfully with facebook."
    });
  } catch (err) {
    if (!err.statusCode) {
      err.statusCode = 500;
    }
    next(err);
  }
};

exports.loginWithFacebook = async (req, res, next) => {
  const { facebookUserId } = req.body;
  try {
    validateRequest(req);
    const user = await User.findOne({ facebookUserId: facebookUserId });
    if (!user) {
      res.status(422).json({ message: "User not found" });
    }
    const token = await jwt.sign(
      {
        facebookUserId: user.facebookUserId,
        userId: user._id.toString(),
      },
      process.env.SECRET_KEY,
      {
        expiresIn: "1h",
      }
    );

    res.status(200).json({
      message: "Logged in success",
      token: token,
      userData: {
        ...user._doc,
        password: null,
        _id: user._id.toString(),
      },
    });
  } catch (err) {
    if (!err.statusCode) {
      err.statusCode = 500;
    }
    next(err);
  }
};

But I’m not quite sure if this is the correct way of implementing facebook login in Node.js api for mobile apps.

If anyone figure outs the route and required parameters it can be exploited fake data.
What is the best way to implement facebook login for mobile apps with Node.js backend ?

2

Answers


  1. Chosen as BEST ANSWER

    For anyone who are having similar issue, this is how I got it working:

    1. react native fbsdk next react-native package will get get facebookUserId and authToken from facebook application

    2. Pass received data facebookUserId and authToken to backend

    3. Validate authToken and facebookUserId from facebook graph api and get required data and save in db

      exports.userRegisterWithFacebook = async (req, res, next) => {
        const { facebookUserId, authToken } = req.body;
        try {
          validateRequest(req);
          const user = await User.findOne({ facebookUserId: facebookUserId });
          if (user) {
            res
              .status(422)
              .json({ message: "User already registered. Please login." });
          }
          let response = await axios.get(
            `https://graph.facebook.com/${facebookUserId}? 
                  fields=id,name,email,picture&access_token=${authToken}`
          );
          if (response.status !== 200) {
                res.status(422).json({ message: "Invalid facebook user id or token" });
          }
          const newUser = new User({
            facebookUserId: response.data.id,
            name: response.data.name,
            email: response.data.email,
            profileImg: response.data.picture.data.url,
          });
      
      await newUser.save();
      
      res.status(200).json({
        message: "User registered successfully with facebook.",
      });
        } catch (err) {
          if (!err.statusCode) {
            err.statusCode = 500;
          }
         next(err);
        }
      };
      

  2. But I’m not quite sure if this is the correct way of implementing
    facebook login in nodejs api for mobile apps.

    Yes, this is not a correct way of login using FB. You can use OAuth to do it. There are several packages out there to implement it.

    What you are doing is local authentication using Facebook id only. It is not facebook login. You need to follow some simple steps to achieve it.

    You should follow this link, it has step-by-step way to implement it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search