diff --git a/src/common/helper.js b/src/common/helper.js index f2b775a9..f4ff1ee8 100644 --- a/src/common/helper.js +++ b/src/common/helper.js @@ -330,11 +330,18 @@ function isDocumentMissingException (err) { /** * Function to get projects - * @param {String} token the user request token + * @param {Object} currentUser the user who perform this operation * @param {Object} criteria the search criteria * @returns the request result */ -async function getProjects (token, criteria = {}) { +async function getProjects (currentUser, criteria = {}) { + let token + if (currentUser.isBookingManager || currentUser.isMachine) { + const m2mToken = await getM2Mtoken() + token = `Bearer ${m2mToken}` + } else { + token = currentUser.jwtToken + } const url = `${config.TC_API}/projects?type=talent-as-a-service` const res = await request .get(url) @@ -377,14 +384,14 @@ async function getTopcoderUserById (userId) { /** * Function to get users - * @param {String} token the user request token * @param {String} userId the user id * @returns the request result */ -async function getUserById (token, userId, enrich) { +async function getUserById (userId, enrich) { + const token = await getM2Mtoken() const res = await request .get(`${config.TC_API}/users/${userId}` + (enrich ? '?enrich=true' : '')) - .set('Authorization', token) + .set('Authorization', `Bearer ${token}`) .set('Content-Type', 'application/json') .set('Accept', 'application/json') localLogger.debug({ context: 'getUserById', message: `response body: ${JSON.stringify(res.body)}` }) @@ -433,11 +440,11 @@ async function createUserExternalProfile (userId, { organizationId, externalId } /** * Function to get members - * @param {String} token the user request token * @param {Array} handles the handle array * @returns the request result */ -async function getMembers (token, handles) { +async function getMembers (handles) { + const token = await getM2Mtoken() const handlesStr = _.map(handles, handle => { return '%22' + handle.toLowerCase() + '%22' }).join(',') @@ -445,7 +452,7 @@ async function getMembers (token, handles) { const res = await request .get(url) - .set('Authorization', token) + .set('Authorization', `Bearer ${token}`) .set('Content-Type', 'application/json') .set('Accept', 'application/json') localLogger.debug({ context: 'getMembers', message: `response body: ${JSON.stringify(res.body)}` }) @@ -454,31 +461,49 @@ async function getMembers (token, handles) { /** * Function to get project by id - * @param {String} token the user request token + * @param {Object} currentUser the user who perform this operation * @param {Number} id project id * @returns the request result */ -async function getProjectById (token, id) { +async function getProjectById (currentUser, id) { + let token + if (currentUser.isBookingManager || currentUser.isMachine) { + const m2mToken = await getM2Mtoken() + token = `Bearer ${m2mToken}` + } else { + token = currentUser.jwtToken + } const url = `${config.TC_API}/projects/${id}` - const res = await request - .get(url) - .set('Authorization', token) - .set('Content-Type', 'application/json') - .set('Accept', 'application/json') - localLogger.debug({ context: 'getProjectById', message: `response body: ${JSON.stringify(res.body)}` }) - return _.pick(res.body, ['id', 'name']) + try { + const res = await request + .get(url) + .set('Authorization', token) + .set('Content-Type', 'application/json') + .set('Accept', 'application/json') + localLogger.debug({ context: 'getProjectById', message: `response body: ${JSON.stringify(res.body)}` }) + return _.pick(res.body, ['id', 'name']) + } catch (err) { + console.log(err) + if (err.status === HttpStatus.FORBIDDEN) { + throw new errors.UnauthorizedError(`You are not allowed to access the project with id ${id}`) + } + if (err.status === HttpStatus.NOT_FOUND) { + throw new errors.NotFoundError(`id: ${id} project not found`) + } + throw err + } } /** * Function to get skill by id - * @param {String} token the user request token * @param {String} skillId the skill Id * @returns the request result */ -async function getSkillById (token, skillId) { +async function getSkillById (skillId) { + const token = await getM2Mtoken() const res = await request .get(`${config.TC_API}/skills/${skillId}`) - .set('Authorization', token) + .set('Authorization', `Bearer ${token}`) .set('Content-Type', 'application/json') .set('Accept', 'application/json') localLogger.debug({ context: 'getSkillById', message: `response body: ${JSON.stringify(res.body)}` }) diff --git a/src/services/JobService.js b/src/services/JobService.js index febffc81..9951fe07 100644 --- a/src/services/JobService.js +++ b/src/services/JobService.js @@ -54,10 +54,9 @@ async function _getJobCandidates (jobId) { * @returns {undefined} */ async function _validateSkills (skills) { - const m2mToken = await helper.getM2Mtoken() const responses = await Promise.all( skills.map( - skill => helper.getSkillById(`Bearer ${m2mToken}`, skill) + skill => helper.getSkillById(skill) .then(() => { return { found: true } }) diff --git a/src/services/TeamService.js b/src/services/TeamService.js index 403b6140..0dd56e34 100644 --- a/src/services/TeamService.js +++ b/src/services/TeamService.js @@ -39,14 +39,10 @@ async function _getJobsByProjectIds (projectIds) { * @returns {Object} the search result, contain total/page/perPage and result array */ async function searchTeams (currentUser, criteria) { - if (currentUser.isBookingManager || currentUser.isMachine) { - const m2mToken = await helper.getM2Mtoken() - currentUser.jwtToken = `Bearer ${m2mToken}` - } const sort = `${criteria.sortBy} ${criteria.sortOrder}` // Get projects from /v5/projects with searching criteria const { total, page, perPage, result: projects } = await helper.getProjects( - currentUser.jwtToken, + currentUser, { page: criteria.page, perPage: criteria.perPage, @@ -58,7 +54,7 @@ async function searchTeams (currentUser, criteria) { total, page, perPage, - result: await getTeamDetail(currentUser, projects) + result: await getTeamDetail(projects) } } @@ -79,12 +75,11 @@ searchTeams.schema = Joi.object().keys({ /** * Get team details - * @param {Object} currentUser the user who perform this operation * @param {Object} projects the projects * @param {Object} isSearch the flag whether for search function * @returns {Object} the search result */ -async function getTeamDetail (currentUser, projects, isSearch = true) { +async function getTeamDetail (projects, isSearch = true) { const projectIds = _.map(projects, 'id') // Get all assigned resourceBookings filtered by projectIds const resourceBookings = await _getAssignedResourceBookingsByProjectIds(projectIds) @@ -140,7 +135,7 @@ async function getTeamDetail (currentUser, projects, isSearch = true) { const usersPromises = [] _.map(rbs, (rb) => { usersPromises.push( - helper.getUserById(currentUser.jwtToken, rb.userId, true) + helper.getUserById(rb.userId, true) .then(user => { // If call function is not search, add jobId field if (!isSearch) { @@ -159,7 +154,7 @@ async function getTeamDetail (currentUser, projects, isSearch = true) { const userHandles = _.map(userInfos, 'handle') // Get user photo from /v5/members - const members = await helper.getMembers(currentUser.jwtToken, userHandles) + const members = await helper.getMembers(userHandles) for (const item of res.resources) { const findMember = _.find(members, { handleLower: item.handle.toLowerCase() }) @@ -197,15 +192,8 @@ async function getTeamDetail (currentUser, projects, isSearch = true) { * @returns {Object} the team */ async function getTeam (currentUser, id) { - if (currentUser.isBookingManager || currentUser.isMachine) { - const m2mToken = await helper.getM2Mtoken() - currentUser.jwtToken = `Bearer ${m2mToken}` - } - // Get users from /v5/projects - const project = await helper.getProjectById(currentUser.jwtToken, id) - - const result = await getTeamDetail(currentUser, [project], false) - + const project = await helper.getProjectById(currentUser, id) + const result = await getTeamDetail([project], false) const teamDetail = result[0] // add job skills for result @@ -214,7 +202,7 @@ async function getTeam (currentUser, id) { for (const job of teamDetail.jobs) { if (job.skills) { const usersPromises = [] - _.map(job.skills, (skillId) => { usersPromises.push(helper.getSkillById(currentUser.jwtToken, skillId)) }) + _.map(job.skills, (skillId) => { usersPromises.push(helper.getSkillById(skillId)) }) jobSkills = await Promise.all(usersPromises) job.skills = jobSkills } @@ -253,12 +241,8 @@ getTeam.schema = Joi.object().keys({ * @returns the team job */ async function getTeamJob (currentUser, id, jobId) { - if (currentUser.isBookingManager || currentUser.isMachine) { - const m2mToken = await helper.getM2Mtoken() - currentUser.jwtToken = `Bearer ${m2mToken}` - } - // Get jobs from taas api - const jobs = await _getJobsByProjectIds([id]) + const project = await helper.getProjectById(currentUser, id) + const jobs = await _getJobsByProjectIds([project.id]) const job = _.find(jobs, { id: jobId }) if (!job) { @@ -271,7 +255,7 @@ async function getTeamJob (currentUser, id, jobId) { if (job.skills) { result.skills = await Promise.all( - _.map(job.skills, (skillId) => helper.getSkillById(currentUser.jwtToken, skillId)) + _.map(job.skills, (skillId) => helper.getSkillById(skillId)) ) } @@ -279,13 +263,13 @@ async function getTeamJob (currentUser, id, jobId) { if (job && job.candidates && job.candidates.length > 0) { const usersPromises = [] - _.map(job.candidates, (candidate) => { usersPromises.push(helper.getUserById(currentUser.jwtToken, candidate.userId, true)) }) + _.map(job.candidates, (candidate) => { usersPromises.push(helper.getUserById(candidate.userId, true)) }) const candidates = await Promise.all(usersPromises) const userHandles = _.map(candidates, 'handle') if (userHandles && userHandles.length > 0) { // Get user photo from /v5/members - const members = await helper.getMembers(currentUser.jwtToken, userHandles) + const members = await helper.getMembers(userHandles) for (const item of candidates) { item.resumeLink = null