· 7 years ago · Aug 30, 2018, 08:48 AM
1JWT_AUTH = {
2 'JWT_SECRET_KEY': SECRET_KEY,
3 'JWT_VERIFY': True,
4 'JWT_VERIFY_EXPIRATION': True,
5 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14),
6 'JWT_ALLOW_REFRESH': True,
7 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
8 'JWT_AUTH_HEADER_PREFIX': 'Bearer',
9}
10
11urlpatterns = [
12 path('auth/get-token/', obtain_jwt_token),
13 path('auth/refresh-token/', refresh_jwt_token),
14]
15
16import axios from 'axios'
17import jwt_decode from 'jwt-decode' // eslint-disable-line
18import { signOut } from '../actions/authActions'
19
20const signOutOn401 = (statusCode) => {
21 if (statusCode === 401) {
22 signOut()
23 window.location = '/signin'
24 }
25}
26
27const client = axios.create({
28 baseURL: process.env.API_URL,
29 headers: {'Authorization': ''}
30})
31
32/*
33 * This interceptor is used for:
34 * - adding Authorization header if JWT available
35 * - refreshing JWT to keep user authenticated
36 */
37client.interceptors.request.use((config) => {
38 if (window.localStorage.getItem('token')) {
39 let token = window.localStorage.getItem('token')
40 // Calculate time difference in days
41 // between now and token expiration date
42 const t = ((jwt_decode(token).exp * 1000) - Date.now()) / 1000 / 60 / 60 / 24
43 // Refresh the token if the time difference is
44 // smaller than 13 days (original token is valid 14 days)
45 if (t < 13) {
46 axios.post(`${process.env.API_URL}/auth/refresh-token/`, {
47 token: token
48 })
49 .then(({data}) => {
50 token = data.token
51 })
52 .catch((error) => {
53 signOutOn401(error.response.status)
54 return error
55 })
56 }
57 config.headers['Authorization'] = `Bearer ${token}`
58 }
59
60 return config
61})
62
63/*
64 * This interceptor is used for:
65 * - disconnect user if JWT is expired or revoked
66 */
67client.interceptors.response.use(
68 (response) => {
69 return response
70 },
71 (error) => {
72 signOutOn401(error.response.status)
73 return error
74 }
75)
76
77export default client
78
79export const signOut = () => {
80 window.localStorage.clear()
81
82 return ({
83 type: SIGN_OUT,
84 payload: {
85 authenticated: false,
86 user: {},
87 errorMessage: ''
88 }
89 })
90}