authReducer.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { takeLatest } from "redux-saga/effects";
  2. import { loginWorker } from "../actions/actionLogin";
  3. import { logoutWorker } from "../actions/actionLogout";
  4. import { registerWorker } from "../actions/actionRegister";
  5. import { jwtDecode } from "../helpers";
  6. export function authReducer(state, { type, token }) {
  7. if (state === undefined) {
  8. if (localStorage.authToken) {
  9. token = localStorage.authToken;
  10. type = "AUTH_LOGIN";
  11. state = {};
  12. }
  13. }
  14. if (type === "AUTH_LOGIN") {
  15. if (!token || !jwtDecode(token)) return {};
  16. localStorage.authToken = token;
  17. return {
  18. ...state,
  19. token: token,
  20. payload: jwtDecode(token),
  21. };
  22. }
  23. if (type === "AUTH_LOGOUT") {
  24. localStorage.removeItem("authToken");
  25. return {};
  26. }
  27. return state || {};
  28. }
  29. export const actionAuthLogin = (token) => ({
  30. type: "AUTH_LOGIN",
  31. token: token,
  32. });
  33. export function* authWatcher() {
  34. yield takeLatest("LOGIN", loginWorker);
  35. yield takeLatest("LOGOUT", logoutWorker);
  36. yield takeLatest("REGISTER", registerWorker);
  37. }
  38. export const actionAuthLogout = () => ({ type: "AUTH_LOGOUT" });