Skip to content

Instantly share code, notes, and snippets.

@danstepanov
Created January 15, 2020 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danstepanov/84f4a33cd8a5348a603a335f7033664b to your computer and use it in GitHub Desktop.
Save danstepanov/84f4a33cd8a5348a603a335f7033664b to your computer and use it in GitHub Desktop.
JWT Authentication
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