Skip to content

Instantly share code, notes, and snippets.

@faceyspacey
Last active August 10, 2017 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faceyspacey/d27ccf7031534198d53c498b2237392c to your computer and use it in GitHub Desktop.
Save faceyspacey/d27ccf7031534198d53c498b2237392c to your computer and use it in GitHub Desktop.
// 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