-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add JWT token auth provider based on djangorestframework-simplejwt (#36)
* Add JWT token auth for DRF integration * Add docs * Working tests * Update jwt token path * Update demo with JWT auth
- Loading branch information
1 parent
e71b91f
commit 90c541f
Showing
11 changed files
with
251 additions
and
5 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,3 +4,4 @@ node_modules | |
dist | ||
coverage/ | ||
example/backend/db.sqlite3 | ||
.idea |
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
Django==3.0.14 | ||
djangorestframework==3.11.2 | ||
djangorestframework-simplejwt==4.6 | ||
django-filter==2.1.0 | ||
jsonfield==3.1.0 | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
SKIP_PREFLIGHT_CHECK=true | ||
REACT_APP_USE_JWT_AUTH=false |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
export function parseBool(val) { | ||
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1) | ||
return true; | ||
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0) | ||
return false; | ||
|
||
return null; | ||
} |
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import { AuthProvider, fetchUtils } from 'ra-core'; | ||
|
||
export interface Options { | ||
obtainAuthTokenUrl?: string; | ||
} | ||
|
||
function jwtTokenAuthProvider(options: Options = {}): AuthProvider { | ||
const opts = { | ||
obtainAuthTokenUrl: '/api/token/', | ||
...options, | ||
}; | ||
return { | ||
login: async ({ username, password }) => { | ||
const request = new Request(opts.obtainAuthTokenUrl, { | ||
method: 'POST', | ||
body: JSON.stringify({ username, password }), | ||
headers: new Headers({ 'Content-Type': 'application/json' }), | ||
}); | ||
const response = await fetch(request); | ||
if (response.ok) { | ||
const responseJSON = await response.json(); | ||
localStorage.setItem('access', responseJSON.access); | ||
localStorage.setItem('refresh', responseJSON.refresh); | ||
return; | ||
} | ||
if (response.headers.get('content-type') !== 'application/json') { | ||
throw new Error(response.statusText); | ||
} | ||
|
||
const json = await response.json(); | ||
const error = json.non_field_errors; | ||
throw new Error(error || response.statusText); | ||
}, | ||
logout: () => { | ||
localStorage.removeItem('access'); | ||
localStorage.removeItem('refresh'); | ||
return Promise.resolve(); | ||
}, | ||
checkAuth: () => | ||
localStorage.getItem('access') ? Promise.resolve() : Promise.reject(), | ||
checkError: error => { | ||
const status = error.status; | ||
if (status === 401 || status === 403) { | ||
localStorage.removeItem('access'); | ||
localStorage.removeItem('refresh'); | ||
return Promise.reject(); | ||
} | ||
return Promise.resolve(); | ||
}, | ||
getPermissions: () => { | ||
return Promise.resolve(); | ||
}, | ||
}; | ||
} | ||
|
||
export function createOptionsFromJWTToken() { | ||
const token = localStorage.getItem('access'); | ||
if (!token) { | ||
return {}; | ||
} | ||
return { | ||
user: { | ||
authenticated: true, | ||
token: 'Bearer ' + token, | ||
}, | ||
}; | ||
} | ||
|
||
export function fetchJsonWithAuthJWTToken(url: string, options: object) { | ||
return fetchUtils.fetchJson( | ||
url, | ||
Object.assign(createOptionsFromJWTToken(), options) | ||
); | ||
} | ||
|
||
export default jwtTokenAuthProvider; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
import 'cross-fetch/polyfill'; | ||
import fetchMock from 'fetch-mock-jest'; | ||
|
||
import jwtTokenAuthProvider, { | ||
createOptionsFromJWTToken, | ||
fetchJsonWithAuthJWTToken, | ||
} from '../src/jwtTokenAuthProvider'; | ||
|
||
fetchMock.config.overwriteRoutes = true; | ||
|
||
describe('login', () => { | ||
const LOGIN_DATA = { | ||
username: 'foo', | ||
password: 'example', | ||
}; | ||
|
||
it('should throw error with statusText for non json responses', async () => { | ||
fetchMock.post('/api/token/', () => { | ||
return 404; | ||
}); | ||
await expect(jwtTokenAuthProvider().login(LOGIN_DATA)).rejects.toThrow( | ||
'Not Found' | ||
); | ||
}); | ||
|
||
it('should throw error with non_field_errors', async () => { | ||
const error = 'Unable to log in with provided credentials.'; | ||
fetchMock.post('/api/token/', { | ||
body: { | ||
non_field_errors: [error], | ||
}, | ||
status: 400, | ||
}); | ||
await expect(jwtTokenAuthProvider().login(LOGIN_DATA)).rejects.toThrow(error); | ||
}); | ||
|
||
it('should set token when successfull', async () => { | ||
const access = 'abcdef'; | ||
fetchMock.post('/api/token/', { | ||
body: { access }, | ||
}); | ||
await jwtTokenAuthProvider().login(LOGIN_DATA); | ||
expect(localStorage.getItem('access')).toBe(access); | ||
}); | ||
}); | ||
|
||
describe('logout', () => { | ||
it('should remove token', async () => { | ||
localStorage.setItem('access', 'abcdef'); | ||
await jwtTokenAuthProvider().logout({}); | ||
}); | ||
}); | ||
|
||
describe('checkAuth', () => { | ||
it('should return resolve when token exists', async () => { | ||
localStorage.setItem('access', 'abcdef'); | ||
await expect(jwtTokenAuthProvider().checkAuth({})).resolves.toBeUndefined(); | ||
}); | ||
it('should return reject when token does not exists', async () => { | ||
localStorage.clear(); | ||
await expect(jwtTokenAuthProvider().checkAuth({})).rejects.toBeUndefined(); | ||
}); | ||
}); | ||
|
||
describe('checkError', () => { | ||
it('should remove token and reject for 401 or 403 error', async () => { | ||
[401, 403].forEach(async status => { | ||
await expect( | ||
jwtTokenAuthProvider().checkError({ status }) | ||
).rejects.toBeUndefined(); | ||
}); | ||
}); | ||
it('should resolve on other errors', async () => { | ||
await expect( | ||
jwtTokenAuthProvider().checkError({ status: 500 }) | ||
).resolves.toBeUndefined(); | ||
}); | ||
}); | ||
|
||
describe('getPermissions', () => { | ||
it.todo('missing implementation'); | ||
}); | ||
|
||
describe('createOptionsFromJWTToken', () => { | ||
test('with token', () => { | ||
localStorage.setItem('access', 'abcdef'); | ||
expect(createOptionsFromJWTToken()).toEqual({ | ||
user: { | ||
authenticated: true, | ||
token: 'Bearer abcdef', | ||
}, | ||
}); | ||
}); | ||
|
||
test('without token', () => { | ||
localStorage.clear(); | ||
expect(createOptionsFromJWTToken()).toEqual({}); | ||
}); | ||
}); | ||
|
||
describe('fetchJsonWithAuthJWTToken', function() { | ||
fetchMock.patch('/', 200); | ||
test('with options', () => { | ||
fetchJsonWithAuthJWTToken('/', { | ||
method: 'PATCH', | ||
}); | ||
}); | ||
}); |