简体   繁体   中英

How to get user informations from Firebase after page reloaded in Nuxt js project?

In my project, users can login with e-mail, google and facebook accounts. After log in, i keep token in my cookie. When user entered web site with his-her account, i can reach his-her informations easily. But when i reloaded page, i can't reach these informations again. Normally, when page reloaded, i can get my token from cookie but problem i don't know how to get user informations by using this token

    async SIGN_IN_WITH_EMAIL({commit}, form) {
        try {
            await auth.signInWithEmailAndPassword(form.email, form.password)
            const token = await auth.currentUser?.getIdToken();
            const {email, uid, refreshToken} = auth.currentUser;
            commit("SET_USER", {email, uid, refreshToken});
            this.$storage.setCookie("access_token", token)

        } catch (err) { 

            console.log("error", err.message)
        }

    },

When user logged in with email. (also i have google and facebook login similiar to the this.)

   nuxtServerInit({commit}, {req}) {
        if (process.server && process.static) return;
        if (!req.headers.cookie) return;

        const parsed = cookieParser.parse(req.headers.cookie);
        const accessTokenCookie = parsed.access_token;

        if (!accessTokenCookie) return;

        const decoded = JWTDecode(accessTokenCookie);

        if (decoded) {
            commit("SET_USER", {
                uid: decoded.user_id,
                email: decoded.email
            });
        }


    }

When page reloaded, i can get token with nuxtServerInit easily.

Imagine it's similar in Vue as it is in NodeJs. This is how I would tackle your problem.

First, on reload of the page call getUser function.

const getUser = (req: any, res: any) => {
  userData(req.user.uid)
    .then((doc) => {
      if (doc.exists) {
        const credentials = doc.data();
        return res.status(200).json({ credentials });
      } else {
        const error = { code: 'auth/rejected-credential' };
        return res.status(403).json(error);
      }
    })
    .catch((err) => {
      return res.status(500).json(err);
    });
};

Where as userData is

export const userData = (uid: string) => {
  return db.doc(`/users/${uid}`).get();
};

To get the uid pass through middleware to authenticate the user from the sessionCookie and then pass down.

export const auth = (req: any, res: any, next: () => any) => {
  const { sessionCookie } = req.headers.cookie; 
  if (sessionCookie) {
    admin
      .auth()
      .verifySessionCookie(sessionCookie, true)
      .then((decodedToken: any) => {
        req.user = decodedToken;
        return db
          .collection('users')
          .where('uid', '==', req.user.uid)
          .limit(1)
          .get();
      })
      .then((data) => {
        req.user.uid = data.docs[0].data().uid;
        return next();
      })
      .catch((err: any) => {
        return res.status(403).json(err);
      });
  } else {
    const error = { code: 'auth/rejected-credential' };
    return res.status(200).json(error);
  }
};

Again, you'll need to rewrite for use in Nuxt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM