export function loadUser(profilesAPIService) { function getTokenSuccess(token) { const profile = decodeToken(token) const resource = profilesAPIService.get({ id: profile.userId }) return resource.$promise.then( (response) => { currentUser = response currentUser.id = currentUser.userId currentUser.role = 'customer' if (currentUser.isCopilot) { currentUser.role = 'copilot' } if (includes(profile.roles, 'Connect Copilot')) { currentUser.role = 'copilot' } if (includes(profile.roles, 'Connect Support')) { currentUser.role = 'admin' } return currentUser }) } return getFreshToken().then(getTokenSuccess) }
// Fetches an API response and normalizes the result JSON according to schema. // This makes every API response have the same shape, regardless of how nested it was. export default function callApi({ schema, endpoint, ignoreResult, method, data }) { const executeRequest = (token) => { const config = { url: WORK_API_URL + endpoint, method: method || 'GET', headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json;charset=UTF-8' } } if (data) { config.data = JSON.stringify(data) } return axios(config) } const handleResponse = (res) => { if (ignoreResult) { return {} } else { return Object.assign({}, normalize(res.data.result.content, schema)) } } return getFreshToken() .then(executeRequest) .then(handleResponse) }
function _checkAndRefreshToken(config, token) { // logger.debug('_checkAndRefreshToken: ' + config.url + ', ' + + token) if (isTokenExpired(token)) { logger.debug(String.supplant('Token has expired, attempting to refreshToken() for "{url}"', config)) return getFreshToken().then(function(refreshedToken) { // logger.debug('Successfully refreshed V3 token.') return refreshedToken }) .catch(function(err) { // Server will not or cannot refresh token logger.debug('Unable to refresh V3 token, redirecting to login') var retUrl = CONSTANTS.MAIN_URL + '/?next=' + config.url $window.location = CONSTANTS.ACCOUNTS_APP_URL + '?retUrl=' + encodeURIComponent(retUrl) return null }) } else { // logger.debug('returning token ' + token) return token } }