Created
January 16, 2019 20:00
-
-
Save OleksivO/ab0c362ce439811c1befcd6347063a73 to your computer and use it in GitHub Desktop.
the description for this gist
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'; | |
export const authStart = () => { | |
return { | |
type: AUTH_START | |
} | |
}; | |
export const authSuccess = (token, userId) => { | |
return { | |
type: AUTH_SUCCESS, | |
token: token, | |
userId: userId | |
} | |
}; | |
export const authFail = (error) => { | |
return { | |
type: AUTH_FAIL, | |
error: error | |
} | |
}; | |
export const logout = () => { | |
localStorage.removeItem('token'); | |
localStorage.removeItem('expirationDate'); | |
localStorage.removeItem('userId'); | |
return { | |
type: AUTH_LOGOUT | |
} | |
}; | |
export const auth = (email, password, signin) => { | |
return dispatch => { | |
dispatch(authStart()); | |
const url = action.signin ? 'SIGNIN_URL' : 'SIGNUP_URL'; | |
axios.post(url, { | |
email: email, | |
password: password | |
}) | |
.then(response => { | |
const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000); | |
localStorage.setItem('token', response.data.authToken); | |
localStorage.setItem('expirationDate', expirationDate); | |
localStorage.setItem('userId', response.data.userId); | |
dispatch(authSuccess(response.data.authToken, response.data.userId)); | |
dispatch(checkAuthTimeout(response.data.expiresIn)); | |
}) | |
.catch(error => { | |
dispatch(authFail(error)) | |
}) | |
} | |
}; | |
export const checkAuthTimeout = (expirationTime) => { | |
return dispatch => { | |
setTimeout(() => { | |
dispatch(logout()) | |
}, expirationTime * 1000) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment