Skip to content

Instantly share code, notes, and snippets.

@kjmczk
Created July 22, 2019 03:03
Show Gist options
  • Save kjmczk/2c287f1d615824c627580bd2a8067fcb to your computer and use it in GitHub Desktop.
Save kjmczk/2c287f1d615824c627580bd2a8067fcb to your computer and use it in GitHub Desktop.
#14 User Auth with Knox - Blog
// 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