Created
January 15, 2020 00:00
-
-
Save danstepanov/84f4a33cd8a5348a603a335f7033664b to your computer and use it in GitHub Desktop.
JWT Authentication
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
import axios from 'axios'; | |
import { AsyncStorage } from 'react-native'; | |
import jwtDecode from 'jwt-decode'; | |
const setAuthToken = async () => { | |
const authorizationToken = await AsyncStorage.getItem('@token'); | |
axios.defaults.headers.common['Authorization'] = authorizationToken; | |
}; | |
export default const authenticateUser = async (email: String, password: String) => { | |
try { | |
const { | |
data: { token } | |
} = await axios.post('/authenticate', { | |
email, | |
password | |
}); | |
const { uuid } = await jwtDecode(token); | |
await AsyncStorage.multiSet([['@token', `Bearer ${token}`], ['@uuid', uuid]]); | |
await setAuthToken(); | |
} catch (e) { | |
throw e; | |
} | |
}; | |
export const clearAuthorization = async () => { | |
const keys = ['@uuid', '@token']; | |
try { | |
await AsyncStorage.multiRemove(keys); | |
axios.defaults.headers.common.Authorization = null; | |
} catch (e) { | |
throw e; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment