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 }) }
/** * Handles initialization of projects loading. * @param {Object} state * @param {Object} action * @return {Object} New state. */ function onGetUserProjectsInit(state, { payload: tokenV3 }) { if (!tokenV3) { logger.error(ERROR_MSG_GET_USER_PROJECTS_WITHOUT_AUTH_TOKEN); throw new Error(ERROR_MSG_GET_USER_PROJECTS_WITHOUT_AUTH_TOKEN); } return { ...state, loadingProjectsForUsername: decodeToken(tokenV3).handle, }; }
/** * @static * @desc Creates an action that loads Topcoder user profile from v3 API. * @param {String} userTokenV3 v3 authentication token. * @return {Action} */ function loadProfileDone(userTokenV3) { if (!userTokenV3) return Promise.resolve(null); const user = decodeToken(userTokenV3); const api = getApiV3(userTokenV3); return Promise.all([ api.get(`/members/${user.handle}`) .then(res => res.json()).then(res => (res.result.status === 200 ? res.result.content : {})), api.get(`/groups?memberId=${user.userId}&membershipType=user`) .then(res => res.json()).then(res => (res.result.status === 200 ? res.result.content : [])), ]).then(([profile, groups]) => ({ ...profile, groups })); }
export async function factory(options = {}) { const state = { tokenV2: _.get(options.auth, 'tokenV2'), tokenV3: _.get(options.auth, 'tokenV3'), }; if (state.tokenV3) { state.user = decodeToken(state.tokenV3); let a = actions.auth.loadProfile(state.tokenV3); a = await redux.resolveAction(a); return create(onProfileLoaded(state, a)); } return create(state); }
export function factory(req) { let joinPromise; if (req) { const { tokenV2, tokenV3 } = getAuthTokens(req); const joinGroupId = req.query && req.query.join; // get community id let communityId = getCommunityId(req.subdomains); if (!communityId && req.url.startsWith('/community')) { [,, communityId] = req.url.split('/'); // remove possible params like ?join=<communityId> communityId = communityId ? communityId.replace(/\?.*/, '') : communityId; } if (communityId && joinGroupId && tokenV3) { const user = decodeToken(tokenV3); // as server doesn't check if user agreed with all community terms make it manually for now const termsService = getTermsService(tokenV2); joinPromise = termsService.getCommunityTerms(communityId, tokenV3).then((result) => { // if all terms agreed we can perform join action if (_.every(result.terms, 'agreed')) { return redux.resolveAction(actions.tcCommunity.joinDone( tokenV3, joinGroupId, user.userId, )); } return false; }); } } return Promise.all([ redux.resolveReducers({ meta: metaFactory(req), news: newsFactory(req), }), joinPromise, ]).then(([reducers, joinResult]) => { let state; if (joinResult) { state = onJoinDone({}, joinResult); } return redux.combineReducers(create(state), { ...reducers, }); }); }
/** * Handles the result of projects loading. * @param {Object} state * @param {Object} action * @return {Object} New state. */ function onGetUserProjectsDone(state, { error, payload }) { if (error) { logger.error(payload); throw payload; } const { projects, tokenV3 } = payload; if (!tokenV3) { logger.error(ERROR_MSG_GET_USER_PROJECTS_WITHOUT_AUTH_TOKEN); throw new Error(ERROR_MSG_GET_USER_PROJECTS_WITHOUT_AUTH_TOKEN); } if (decodeToken(tokenV3).handle !== state.loadingProjectsForUsername) { return state; } return { ...state, loadingProjectsForUsername: '', projects: projects.sort((a, b) => a.name.localeCompare(b.name)), }; }
/** * Gets all active challenges from the backend. * Once this action is completed any active challenges saved to the state before * will be dropped, and the newly fetched ones will be stored there. * @param {String} uuid * @param {String} tokenV3 Optional. Topcoder auth token v3. Without token only * public challenges will be fetched. With the token provided, the action will * also fetch private challenges related to this user. * @return {Promise} */ function getAllActiveChallengesDone(uuid, tokenV3) { const filter = { status: 'ACTIVE' }; const service = getService(tokenV3); const calls = [ getAll(params => service.getChallenges(filter, params)), ]; let user; if (tokenV3) { user = decodeToken(tokenV3).handle; calls.push(getAll(params => service.getUserChallenges(user, filter, params))); calls.push(getAll(params => service.getUserMarathonMatches(user, filter, params))); } return Promise.all(calls).then(([challenges, uch, umm]) => { /* uch and umm arrays contain challenges where the user is participating in * some role. The same challenge are already listed in res array, but they * are not attributed to the user there. This block of code marks user * challenges in an efficient way. */ if (uch && umm) { const map = {}; uch.forEach((item) => { map[item.id] = item; }); umm.forEach((item) => { map[item.id] = item; }); challenges.forEach((item) => { if (map[item.id]) { /* It is fine to reassing, as the array we modifying is created just * above within the same function. */ /* eslint-disable no-param-reassign */ item.users[user] = true; item.userDetails = map[item.id].userDetails; /* eslint-enable no-param-reassign */ } }); } return { uuid, challenges }; }); }
/** * Gets challenge details from Topcoder API v3. * NOTE: This function also uses API v2 and other v3 endpoints for now, due * to some information is missing or * incorrect in the main v3 endpoint. This may change in the future. * @param {Number|String} challengeId * @return {Promise} Resolves to the challenge object. */ async getChallengeDetails(challengeId) { const challengeV3 = await this.private.api.get(`/challenges/${challengeId}`) .then(checkError).then(res => res.content); const challengeV3Filtered = await this.private.getChallenges('/challenges/', { id: challengeId }) .then(res => res.challenges[0]); const username = this.private.tokenV3 && decodeToken(this.private.tokenV3).handle; const challengeV3User = username && await this.getUserChallenges(username, { id: challengeId }) .then(res => res.challenges[0]); const challenge = normalizeChallengeDetails( challengeV3, challengeV3Filtered, challengeV3User, username, ); challenge.fetchedWithAuth = Boolean(this.private.api.private.token); return challenge; }
[actions.auth.setTcTokenV3]: (state, { payload }) => ({ ...state, tokenV3: payload, user: payload ? decodeToken(payload) : null, }),