authReducer.js 712 B

123456789101112131415161718192021222324252627282930
  1. const jwtDecode = token => {
  2. try{
  3. return JSON.parse(atob(token.split('.')[1]));
  4. }
  5. catch(e){
  6. console.log(e.name, e.message);
  7. }
  8. }
  9. export function authReducer(state, {type, token}){
  10. if (state === undefined){
  11. if(localStorage.authToken){
  12. type = 'AUTH_LOGIN';
  13. token = localStorage.authToken
  14. }
  15. }
  16. if(type === 'AUTH_LOGIN'){
  17. let payload = jwtDecode(token);
  18. if (payload){
  19. localStorage.authToken = token
  20. return {token, payload}
  21. }
  22. }
  23. if(type === 'AUTH_LOGOUT'){
  24. localStorage.removeItem("authToken")
  25. return {}
  26. }
  27. return state || {}
  28. }