简体   繁体   中英

How can get email from current user logged in react-admin?

I am working in admin website using react-admin framework.

https://marmelab.com/react-admin/Readme.html

I need to show current user email that is logged. How can I get this functionality?

Regards

I have implemented a custom verb in the authProvier similarly to the Dwadelfri 's answer. It gets pretty handy because you can access it through the built in hook useAuthProvider

inside authProvider.js

import decodeJwt from 'jwt-decode';

const getCurrentUser = () => {
    // the place where you saved user's data on login
    const user = JSON.parse(localStorage.getItem("user"));
    const decodedToken = decodeJwt(user.token);

    return { 
        ...user,
        ...decodedToken,
    };
}

export default {
    login: loginHandler,
    logout: logoutHandler,
    checkAuth: checkAuthHandler,
    checkError: checkErrorHandler,
    getPermissions: getPermissionsHandler,
    //custom verbs
    signUp: signUpHandler,
    getCurrentUser: getCurrentUser,
};

Then the code looks pretty neat when you decide to call it:

const authProvider = useAuthProvider();
const user = authProvider.getCurrentUser();

I only found this kinda hacky way, I'm looking for better alternative but for right now I'm using this to get the user id which could be used to get other stuff via the dataProvider.

import decodeJwt from 'jwt-decode';

const getUserId = () => {
  return decodeJwt(localStorage.getItem("token")).sub;
}

this asumes you use jwt and your token includes the user id

const token = jwt.sign({ sub: user.id}, config.secret);

the solution that I got is the following:

Inside your Data page (posts.js for instance)

  1. First import the following Firebase package

import firebase from 'firebase/app';

  1. Then get the connected user straight from the firebase context as the following:

const email = firebase.auth().currentUser.email;

  1. The filter part would be the following:
   <List
   {...props}
   filter={{ createdby: email }}>```

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