Created
July 22, 2019 03:03
-
-
Save kjmczk/2c287f1d615824c627580bd2a8067fcb to your computer and use it in GitHub Desktop.
#14 User Auth with Knox - Blog
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
// frontend/src/actions/auth.js | |
import axios from 'axios'; | |
import { stopSubmit } from 'redux-form'; | |
import { | |
USER_LOADING, | |
USER_LOADED, | |
AUTH_ERROR, | |
LOGIN_SUCCESS, | |
LOGIN_FAIL | |
} from './types'; | |
// LOAD USER | |
export const loadUser = () => async (dispatch, getState) => { | |
dispatch({ type: USER_LOADING }); | |
try { | |
const res = await axios.get('/api/auth/user', tokenConfig(getState)); | |
dispatch({ | |
type: USER_LOADED, | |
payload: res.data | |
}); | |
} catch (err) { | |
dispatch({ | |
type: AUTH_ERROR | |
}); | |
} | |
}; | |
// LOGIN USER | |
export const login = ({ username, password }) => async dispatch => { | |
// Headers | |
const config = { | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}; | |
// Request Body | |
const body = JSON.stringify({ username, password }); | |
try { | |
const res = await axios.post('/api/auth/login', body, config); | |
dispatch({ | |
type: LOGIN_SUCCESS, | |
payload: res.data | |
}); | |
} catch (err) { | |
dispatch({ | |
type: LOGIN_FAIL | |
}); | |
dispatch(stopSubmit('loginForm', err.response.data)); | |
} | |
}; | |
// helper function | |
export const tokenConfig = getState => { | |
// Get token | |
const token = getState().auth.token; | |
// Headers | |
const config = { | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}; | |
if (token) { | |
config.headers['Authorization'] = `Token ${token}`; | |
} | |
return config; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment