Skip to content
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

Added proxy for private content update #53

Open
wants to merge 6 commits into
base: cbrelease-3.0.1
Choose a base branch
from
Open
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
122 changes: 122 additions & 0 deletions src/protectedApi_v8/contentprivate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import axios from 'axios'
import { Router } from 'express'

import { axiosRequestConfig } from '../configs/request.config'
import { CONSTANTS } from '../utils/env'
import { logError} from '../utils/logger'
import { ERROR } from '../utils/message'
import { extractUserId, extractUserOrgData, extractUserToken } from '../utils/requestExtract'

export const contentPrivateApi = Router()

const API_END_POINTS = {
getHierarchyDetails: (id: string) => `${CONSTANTS.KNOWLEDGE_MW_API_BASE}/action/content/v3/hierarchy/${id}?mode=edit`,
readUserEndPoint: (userId: string) => `${CONSTANTS.KONG_API_BASE}/user/v2/read/${userId}`,
updateContentEndPoint: (id: string) => `${CONSTANTS.KONG_API_BASE}/private/content/v3/update/${id}`,
}

const editableFields = ['versionKey', 'createdBy', 'creatorContacts']
const userIdFailedMessage = 'NO_USER_ID'
const FIELD_VALIDATION_ERROR = 'TRYING_TO_UPDATE_NON_EDITABLE_FIELDS'
const CHANNEL_VALIDATION_ERROR = 'SOURCE_MISMATCH_ERROR'

contentPrivateApi.patch('/update/:id', async (req, res) => {
try {
const id = req.params.id
const content = req.body.request.content
const fields = Object.keys(content)
const userId = extractUserId(req)
const userToken = extractUserToken(req) as string
if (!userId) {
res.status(400).send(userIdFailedMessage)
return
}
if (fields instanceof Array) {
for (const entry of fields) {
if (editableFields.indexOf(entry) === -1) {
res.status(400).send({
msg: res.status(400).send({
msg: FIELD_VALIDATION_ERROR,
}),
})
}
}
}
// tslint:disable-next-line: no-console
console.log('calling for user channel')
const userChannel = extractUserOrgData(req)
const channelData = JSON.stringify(userChannel)
// tslint:disable-next-line: no-console
console.log('channelData=====>', channelData)
const hierarchySource = await getHierarchyDetails(userToken, id)
// tslint:disable-next-line: no-console
console.log('hierarchy source ' + hierarchySource)
if (userChannel !== hierarchySource) {
res.status(400).send({
msg: res.status(400).send({
msg: CHANNEL_VALIDATION_ERROR,
}),
})
}
const response = await axios.patch(
API_END_POINTS.updateContentEndPoint(id),
req.body,
{
...axiosRequestConfig,
headers: {
Authorization: CONSTANTS.SB_API_KEY,
// tslint:disable-next-line: all
'x-authenticated-user-token': userToken,
},
}
)
res.status(response.status).send(response.data)
} catch (err) {
logError(Error + err)
res.status((err && err.response && err.response.status) || 500).send(
(err && err.response && err.response.data) || {
error: ERROR.GENERAL_ERR_MSG,
}
)
}
})

export async function getHierarchyDetails(token: string, id: string) {
try {
const response = await axios.get(API_END_POINTS.getHierarchyDetails(id), {
...axiosRequestConfig,
headers: {
Authorization: CONSTANTS.SB_API_KEY,
// tslint:disable-next-line: all
'x-authenticated-user-token': token,
},
})
const hierarchyResult = response.data.result.content
if (typeof hierarchyResult !== 'undefined' && hierarchyResult != null) {
return hierarchyResult.source
}
} catch (error) {
logError('ERROR WHILE FETCHING THE Hierarchy DETAILS --> ', error)
return 'contentSourceDetails'
}
}

export async function getUserChannel(token: string, userId: string) {
try {
const response = await axios.get(API_END_POINTS.readUserEndPoint(userId), {
...axiosRequestConfig,
headers: {
Authorization: CONSTANTS.SB_API_KEY,
// tslint:disable-next-line: all
'x-authenticated-user-token': token,
},
})
const userProfileResult = response.data.result.response
if (typeof userProfileResult !== 'undefined' && userProfileResult != null) {
return userProfileResult.channel
}
} catch (error) {
logError('ERROR WHILE FETCHING THE USER DETAILS --> ', error)
return 'userChannelDetails'
}
}
2 changes: 2 additions & 0 deletions src/protectedApi_v8/protectedApiV8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { conceptGraphApi } from './concept'
// import { connectionsApi } from './connections'
import { connectionsV2Api } from './connections_v2'
import { contentApi } from './content'
import { contentPrivateApi } from './contentprivate'
import { contentValidationApi } from './contentValidation'
import { counterApi } from './counter'
import { deptApi } from './departments'
Expand Down Expand Up @@ -79,3 +80,4 @@ protectedApiV8.use('/roleactivity', roleActivityApi)
protectedApiV8.use('/resource', userAuthKeyCloakApi)
protectedApiV8.use('/workallocation', workAllocationApi)
protectedApiV8.use('/frac', fracApi)
protectedApiV8.use('/contentprivate', contentPrivateApi)
3 changes: 3 additions & 0 deletions src/utils/permissionHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export const PERMISSION_HELPER = {
reqObj.session.userRoles = userData.result.response.roles
reqObj.session.orgs = userData.result.response.organisations
reqObj.session.rootOrgId = userData.result.response.rootOrgId
reqObj.session.channel = userData.result.response.rootOrg.channel
reqObj.session.orgName = userData.result.response.rootOrg.orgName

if (!_.includes(reqObj.session.userRoles, 'PUBLIC')) {
reqObj.session.userRoles.push('PUBLIC')
}
Expand Down
5 changes: 5 additions & 0 deletions src/utils/requestExtract.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Request } from 'express'
import _ from 'lodash'
import uuid from 'uuid'
export interface IAuthorizedRequest extends Request {
kauth?: {
Expand Down Expand Up @@ -73,4 +74,8 @@ export const extractRootOrgFromRequest = (req: IAuthorizedRequest): string => {

}

export const extractUserOrgData = (req: Request) => {
return (_.get(req, 'session.orgs')) ? _.get(req, 'session.orgs') : []
}

export const getUUID = () => uuid.v1()
8 changes: 8 additions & 0 deletions src/utils/whitelistApis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,13 @@ export const API_LIST = {
ROLE.PUBLIC,
],
},
'/protected/v8/contentprivate/update/:id': {
checksNeeded: [CHECK.ROLE],
// tslint:disable-next-line: object-literal-sort-keys
ROLE_CHECK: [
ROLE.PUBLIC,
],
},
},
URL_PATTERN:
[
Expand Down Expand Up @@ -1379,5 +1386,6 @@ export const API_LIST = {
'/protected/v8/connections/v2/connections/suggests',
'/protected/v8/connections/v2/update/connection',
'/protected/v8/user/profileDetails/createUserWithoutInvitationEmail',
'/protected/v8/contentprivate/update/:id',
],
}