Skip to content

Commit b815105

Browse files
committed
TeamService: use m2m token for internal api calls
1 parent 512df40 commit b815105

File tree

3 files changed

+59
-51
lines changed

3 files changed

+59
-51
lines changed

src/common/helper.js

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -330,11 +330,18 @@ function isDocumentMissingException (err) {
330330

331331
/**
332332
* Function to get projects
333-
* @param {String} token the user request token
333+
* @param {Object} currentUser the user who perform this operation
334334
* @param {Object} criteria the search criteria
335335
* @returns the request result
336336
*/
337-
async function getProjects (token, criteria = {}) {
337+
async function getProjects (currentUser, criteria = {}) {
338+
let token
339+
if (currentUser.isBookingManager || currentUser.isMachine) {
340+
const m2mToken = await getM2Mtoken()
341+
token = `Bearer ${m2mToken}`
342+
} else {
343+
token = currentUser.jwtToken
344+
}
338345
const url = `${config.TC_API}/projects?type=talent-as-a-service`
339346
const res = await request
340347
.get(url)
@@ -377,14 +384,14 @@ async function getTopcoderUserById (userId) {
377384

378385
/**
379386
* Function to get users
380-
* @param {String} token the user request token
381387
* @param {String} userId the user id
382388
* @returns the request result
383389
*/
384-
async function getUserById (token, userId, enrich) {
390+
async function getUserById (userId, enrich) {
391+
const token = await getM2Mtoken()
385392
const res = await request
386393
.get(`${config.TC_API}/users/${userId}` + (enrich ? '?enrich=true' : ''))
387-
.set('Authorization', token)
394+
.set('Authorization', `Bearer ${token}`)
388395
.set('Content-Type', 'application/json')
389396
.set('Accept', 'application/json')
390397
localLogger.debug({ context: 'getUserById', message: `response body: ${JSON.stringify(res.body)}` })
@@ -433,19 +440,19 @@ async function createUserExternalProfile (userId, { organizationId, externalId }
433440

434441
/**
435442
* Function to get members
436-
* @param {String} token the user request token
437443
* @param {Array} handles the handle array
438444
* @returns the request result
439445
*/
440-
async function getMembers (token, handles) {
446+
async function getMembers (handles) {
447+
const token = await getM2Mtoken()
441448
const handlesStr = _.map(handles, handle => {
442449
return '%22' + handle.toLowerCase() + '%22'
443450
}).join(',')
444451
const url = `${config.TC_API}/members?fields=userId,handleLower,photoURL&handlesLower=[${handlesStr}]`
445452

446453
const res = await request
447454
.get(url)
448-
.set('Authorization', token)
455+
.set('Authorization', `Bearer ${token}`)
449456
.set('Content-Type', 'application/json')
450457
.set('Accept', 'application/json')
451458
localLogger.debug({ context: 'getMembers', message: `response body: ${JSON.stringify(res.body)}` })
@@ -454,31 +461,49 @@ async function getMembers (token, handles) {
454461

455462
/**
456463
* Function to get project by id
457-
* @param {String} token the user request token
464+
* @param {Object} currentUser the user who perform this operation
458465
* @param {Number} id project id
459466
* @returns the request result
460467
*/
461-
async function getProjectById (token, id) {
468+
async function getProjectById (currentUser, id) {
469+
let token
470+
if (currentUser.isBookingManager || currentUser.isMachine) {
471+
const m2mToken = await getM2Mtoken()
472+
token = `Bearer ${m2mToken}`
473+
} else {
474+
token = currentUser.jwtToken
475+
}
462476
const url = `${config.TC_API}/projects/${id}`
463-
const res = await request
464-
.get(url)
465-
.set('Authorization', token)
466-
.set('Content-Type', 'application/json')
467-
.set('Accept', 'application/json')
468-
localLogger.debug({ context: 'getProjectById', message: `response body: ${JSON.stringify(res.body)}` })
469-
return _.pick(res.body, ['id', 'name'])
477+
try {
478+
const res = await request
479+
.get(url)
480+
.set('Authorization', token)
481+
.set('Content-Type', 'application/json')
482+
.set('Accept', 'application/json')
483+
localLogger.debug({ context: 'getProjectById', message: `response body: ${JSON.stringify(res.body)}` })
484+
return _.pick(res.body, ['id', 'name'])
485+
} catch (err) {
486+
console.log(err)
487+
if (err.status === HttpStatus.FORBIDDEN) {
488+
throw new errors.UnauthorizedError(`You are not allowed to access the project with id ${id}`)
489+
}
490+
if (err.status === HttpStatus.NOT_FOUND) {
491+
throw new errors.NotFoundError(`id: ${id} project not found`)
492+
}
493+
throw err
494+
}
470495
}
471496

472497
/**
473498
* Function to get skill by id
474-
* @param {String} token the user request token
475499
* @param {String} skillId the skill Id
476500
* @returns the request result
477501
*/
478-
async function getSkillById (token, skillId) {
502+
async function getSkillById (skillId) {
503+
const token = await getM2Mtoken()
479504
const res = await request
480505
.get(`${config.TC_API}/skills/${skillId}`)
481-
.set('Authorization', token)
506+
.set('Authorization', `Bearer ${token}`)
482507
.set('Content-Type', 'application/json')
483508
.set('Accept', 'application/json')
484509
localLogger.debug({ context: 'getSkillById', message: `response body: ${JSON.stringify(res.body)}` })

src/services/JobService.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,9 @@ async function _getJobCandidates (jobId) {
5454
* @returns {undefined}
5555
*/
5656
async function _validateSkills (skills) {
57-
const m2mToken = await helper.getM2Mtoken()
5857
const responses = await Promise.all(
5958
skills.map(
60-
skill => helper.getSkillById(`Bearer ${m2mToken}`, skill)
59+
skill => helper.getSkillById(skill)
6160
.then(() => {
6261
return { found: true }
6362
})

src/services/TeamService.js

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,10 @@ async function _getJobsByProjectIds (projectIds) {
3939
* @returns {Object} the search result, contain total/page/perPage and result array
4040
*/
4141
async function searchTeams (currentUser, criteria) {
42-
if (currentUser.isBookingManager || currentUser.isMachine) {
43-
const m2mToken = await helper.getM2Mtoken()
44-
currentUser.jwtToken = `Bearer ${m2mToken}`
45-
}
4642
const sort = `${criteria.sortBy} ${criteria.sortOrder}`
4743
// Get projects from /v5/projects with searching criteria
4844
const { total, page, perPage, result: projects } = await helper.getProjects(
49-
currentUser.jwtToken,
45+
currentUser,
5046
{
5147
page: criteria.page,
5248
perPage: criteria.perPage,
@@ -58,7 +54,7 @@ async function searchTeams (currentUser, criteria) {
5854
total,
5955
page,
6056
perPage,
61-
result: await getTeamDetail(currentUser, projects)
57+
result: await getTeamDetail(projects)
6258
}
6359
}
6460

@@ -79,12 +75,11 @@ searchTeams.schema = Joi.object().keys({
7975

8076
/**
8177
* Get team details
82-
* @param {Object} currentUser the user who perform this operation
8378
* @param {Object} projects the projects
8479
* @param {Object} isSearch the flag whether for search function
8580
* @returns {Object} the search result
8681
*/
87-
async function getTeamDetail (currentUser, projects, isSearch = true) {
82+
async function getTeamDetail (projects, isSearch = true) {
8883
const projectIds = _.map(projects, 'id')
8984
// Get all assigned resourceBookings filtered by projectIds
9085
const resourceBookings = await _getAssignedResourceBookingsByProjectIds(projectIds)
@@ -140,7 +135,7 @@ async function getTeamDetail (currentUser, projects, isSearch = true) {
140135
const usersPromises = []
141136
_.map(rbs, (rb) => {
142137
usersPromises.push(
143-
helper.getUserById(currentUser.jwtToken, rb.userId, true)
138+
helper.getUserById(rb.userId, true)
144139
.then(user => {
145140
// If call function is not search, add jobId field
146141
if (!isSearch) {
@@ -159,7 +154,7 @@ async function getTeamDetail (currentUser, projects, isSearch = true) {
159154

160155
const userHandles = _.map(userInfos, 'handle')
161156
// Get user photo from /v5/members
162-
const members = await helper.getMembers(currentUser.jwtToken, userHandles)
157+
const members = await helper.getMembers(userHandles)
163158

164159
for (const item of res.resources) {
165160
const findMember = _.find(members, { handleLower: item.handle.toLowerCase() })
@@ -197,15 +192,8 @@ async function getTeamDetail (currentUser, projects, isSearch = true) {
197192
* @returns {Object} the team
198193
*/
199194
async function getTeam (currentUser, id) {
200-
if (currentUser.isBookingManager || currentUser.isMachine) {
201-
const m2mToken = await helper.getM2Mtoken()
202-
currentUser.jwtToken = `Bearer ${m2mToken}`
203-
}
204-
// Get users from /v5/projects
205-
const project = await helper.getProjectById(currentUser.jwtToken, id)
206-
207-
const result = await getTeamDetail(currentUser, [project], false)
208-
195+
const project = await helper.getProjectById(currentUser, id)
196+
const result = await getTeamDetail([project], false)
209197
const teamDetail = result[0]
210198

211199
// add job skills for result
@@ -214,7 +202,7 @@ async function getTeam (currentUser, id) {
214202
for (const job of teamDetail.jobs) {
215203
if (job.skills) {
216204
const usersPromises = []
217-
_.map(job.skills, (skillId) => { usersPromises.push(helper.getSkillById(currentUser.jwtToken, skillId)) })
205+
_.map(job.skills, (skillId) => { usersPromises.push(helper.getSkillById(skillId)) })
218206
jobSkills = await Promise.all(usersPromises)
219207
job.skills = jobSkills
220208
}
@@ -253,12 +241,8 @@ getTeam.schema = Joi.object().keys({
253241
* @returns the team job
254242
*/
255243
async function getTeamJob (currentUser, id, jobId) {
256-
if (currentUser.isBookingManager || currentUser.isMachine) {
257-
const m2mToken = await helper.getM2Mtoken()
258-
currentUser.jwtToken = `Bearer ${m2mToken}`
259-
}
260-
// Get jobs from taas api
261-
const jobs = await _getJobsByProjectIds([id])
244+
const project = await helper.getProjectById(currentUser, id)
245+
const jobs = await _getJobsByProjectIds([project.id])
262246
const job = _.find(jobs, { id: jobId })
263247

264248
if (!job) {
@@ -271,21 +255,21 @@ async function getTeamJob (currentUser, id, jobId) {
271255

272256
if (job.skills) {
273257
result.skills = await Promise.all(
274-
_.map(job.skills, (skillId) => helper.getSkillById(currentUser.jwtToken, skillId))
258+
_.map(job.skills, (skillId) => helper.getSkillById(skillId))
275259
)
276260
}
277261

278262
const jobSkills = job.skills
279263

280264
if (job && job.candidates && job.candidates.length > 0) {
281265
const usersPromises = []
282-
_.map(job.candidates, (candidate) => { usersPromises.push(helper.getUserById(currentUser.jwtToken, candidate.userId, true)) })
266+
_.map(job.candidates, (candidate) => { usersPromises.push(helper.getUserById(candidate.userId, true)) })
283267
const candidates = await Promise.all(usersPromises)
284268

285269
const userHandles = _.map(candidates, 'handle')
286270
if (userHandles && userHandles.length > 0) {
287271
// Get user photo from /v5/members
288-
const members = await helper.getMembers(currentUser.jwtToken, userHandles)
272+
const members = await helper.getMembers(userHandles)
289273

290274
for (const item of candidates) {
291275
item.resumeLink = null

0 commit comments

Comments
 (0)