Guest User

Untitled

a guest
Jul 18th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. import LoginActions from '../LoginRedux'
  2. import jwtDecode from 'jwt-decode'
  3. import moment from 'moment'
  4. import {startsWith} from 'lodash'
  5. import { Actions as NavigationActions } from 'react-native-router-flux'
  6.  
  7. let buffer = []
  8.  
  9. const isValidScreen = () => {
  10. if (NavigationActions.currentScene === '') return false
  11.  
  12. const notValidScreens = [
  13. 'loginScreen',
  14. 'signupScreen'
  15. ]
  16. return !notValidScreens.find(screen => screen === NavigationActions.currentScene)
  17. }
  18.  
  19. const isExpired = (token) => {
  20. const expiration = jwtDecode(token).exp
  21. return moment.unix(expiration) - moment(Date.now()) < 30
  22. }
  23.  
  24. const authMiddleware = store => next => action => {
  25. const state = store.getState()
  26. let isTokenExpired = false
  27.  
  28. if (action.type === 'REFRESH_TOKEN_REQUEST') {
  29. return next(action)
  30. }
  31.  
  32. if (action.type === 'REFRESH_TOKEN_SUCCESS') {
  33. next(action)
  34.  
  35. if (buffer.length > 0) {
  36. buffer.forEach(action => store.dispatch(action))
  37. buffer = []
  38. }
  39. }
  40.  
  41. if (!startsWith(action.type, 'REFRESH_TOKEN')) {
  42. if (state && isValidScreen()) {
  43. isTokenExpired = isExpired(state.login.token)
  44.  
  45. if (state.login.token && isTokenExpired) {
  46. if (!state.login.refreshingToken && buffer.length <= 0) {
  47. store.dispatch(LoginActions.refreshTokenRequest(state.login.refreshToken))
  48. }
  49.  
  50. buffer.push(action)
  51. }
  52. }
  53. }
  54.  
  55. if (!isTokenExpired && action.type !== 'REFRESH_TOKEN_SUCCESS') {
  56. return next(action)
  57. }
  58. }
  59.  
  60. export default authMiddleware
Add Comment
Please, Sign In to add comment