Last active
August 10, 2017 09:47
-
-
Save faceyspacey/d27ccf7031534198d53c498b2237392c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/options.js | |
const options = { | |
onBeforeChange: (dispatch, getState, action) => { | |
const state = getState() | |
const user = userFromState(action.type, state) | |
if (!user) { | |
const action = redirect({ type: 'LOGIN' }) | |
dispatch(action) | |
} | |
if (!state.user) { | |
const action = { type: 'USER_FOUND', payload: user } | |
dispatch(action) | |
} | |
} | |
} | |
// src/reducers/user.js | |
const user = (state = null, action = {}) { | |
switch (action.type) { | |
case 'USER_FOUND': | |
return state.payload | |
default: | |
return state | |
} | |
} | |
// src/selectors/userFromState.js | |
import jwt from 'jsonwebtoken' | |
const userFromState = (type, state) => { | |
const user = isServer | |
? jwt.verify(state.jwToken, process.env.JWT_SECRET) | |
: state.user | |
const role = routesMap[type] && routesMap[type].role | |
if (!role) return user | |
if (!user) return null | |
return user.roles.includes(role) && user | |
} | |
const isServer = typeof window === 'undefined' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment