Skip to content

TeamService: use m2m token for internal api calls #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 45 additions & 20 deletions src/common/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)}` })
Expand Down Expand Up @@ -433,19 +440,19 @@ 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(',')
const url = `${config.TC_API}/members?fields=userId,handleLower,photoURL&handlesLower=[${handlesStr}]`

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)}` })
Expand All @@ -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)}` })
Expand Down
3 changes: 1 addition & 2 deletions src/services/JobService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
})
Expand Down
42 changes: 13 additions & 29 deletions src/services/TeamService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -58,7 +54,7 @@ async function searchTeams (currentUser, criteria) {
total,
page,
perPage,
result: await getTeamDetail(currentUser, projects)
result: await getTeamDetail(projects)
}
}

Expand All @@ -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)
Expand Down Expand Up @@ -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) {
Expand All @@ -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() })
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -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) {
Expand All @@ -271,21 +255,21 @@ 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))
)
}

const jobSkills = job.skills

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
Expand Down