Guest User

Untitled

a guest
Jul 18th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. import LoginActions from '../LoginRedux'
  2. import {startsWith} from 'lodash'
  3.  
  4. let buffer = []
  5.  
  6. const authMiddleware = store => next => action => {
  7. const state = store.getState()
  8. let isTokenExpired = false
  9.  
  10. // On sort le plus tôt possible
  11. if (action.type === 'REFRESH_TOKEN_REQUEST') {
  12. return next(action)
  13. }
  14. // Lors du succès du refresh on dispatch toutes les actions
  15. // stockées dans le buffer
  16. if (action.type === 'REFRESH_TOKEN_SUCCESS') {
  17. next(action)
  18.  
  19. if (buffer.length > 0) {
  20. buffer.forEach(action => store.dispatch(action))
  21. buffer = []
  22. }
  23. }
  24. // pour toute autre action ne commençant pas par REFRESH_TOKEN
  25. if (!startsWith(action.type, 'REFRESH_TOKEN')) {
  26. // si on est sur le bon écran
  27. if (state && isValidScreen()) {
  28. isTokenExpired = isExpired(state.login.token)
  29. // si le token est expiré
  30. if (state.login.token && isTokenExpired) {
  31. // si le token n'est pas en cours de refresh
  32. // et si le buffer est bien vide
  33. if (!state.login.refreshingToken && buffer.length <= 0) {
  34. store.dispatch(LoginActions.refreshTokenRequest(state.login.refreshToken))
  35. }
  36. // sinon on sauvegarde l'action pour la "dispatcher" plus tard
  37. buffer.push(action)
  38. }
  39. }
  40. }
  41. // on retourne l'action au prochain reducer
  42. if (!isTokenExpired && action.type !== 'REFRESH_TOKEN_SUCCESS') {
  43. return next(action)
  44. }
  45. }
  46.  
  47. export default authMiddleware
Add Comment
Please, Sign In to add comment