Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import LoginActions from '../LoginRedux'
- import jwtDecode from 'jwt-decode'
- import moment from 'moment'
- import {startsWith} from 'lodash'
- import { Actions as NavigationActions } from 'react-native-router-flux'
- let buffer = []
- const isValidScreen = () => {
- if (NavigationActions.currentScene === '') return false
- const notValidScreens = [
- 'loginScreen',
- 'signupScreen'
- ]
- return !notValidScreens.find(screen => screen === NavigationActions.currentScene)
- }
- const isExpired = (token) => {
- const expiration = jwtDecode(token).exp
- return moment.unix(expiration) - moment(Date.now()) < 30
- }
- const authMiddleware = store => next => action => {
- const state = store.getState()
- let isTokenExpired = false
- if (action.type === 'REFRESH_TOKEN_REQUEST') {
- return next(action)
- }
- if (action.type === 'REFRESH_TOKEN_SUCCESS') {
- next(action)
- if (buffer.length > 0) {
- buffer.forEach(action => store.dispatch(action))
- buffer = []
- }
- }
- if (!startsWith(action.type, 'REFRESH_TOKEN')) {
- if (state && isValidScreen()) {
- isTokenExpired = isExpired(state.login.token)
- if (state.login.token && isTokenExpired) {
- if (!state.login.refreshingToken && buffer.length <= 0) {
- store.dispatch(LoginActions.refreshTokenRequest(state.login.refreshToken))
- }
- buffer.push(action)
- }
- }
- }
- if (!isTokenExpired && action.type !== 'REFRESH_TOKEN_SUCCESS') {
- return next(action)
- }
- }
- export default authMiddleware
Add Comment
Please, Sign In to add comment