diff --git a/src/publicApi_v8/parichayAuth.ts b/src/publicApi_v8/parichayAuth.ts index 80d4c0ff..d8f62276 100644 --- a/src/publicApi_v8/parichayAuth.ts +++ b/src/publicApi_v8/parichayAuth.ts @@ -64,7 +64,7 @@ parichayAuth.get('/callback', async (req, res) => { if (req.session) { req.session.parichayToken = tokenResponse.data req.session.cookie.expires = new Date(getCurrnetExpiryTime(tokenResponse.data.access_token)) - logInfo('Parichay Token is set in request Session.' + tokenResponse.data.access_token) + logInfo('Parichay Token is set in request Session.') } else { logError('Failed to set Parichay token in req session. Session not available...') } @@ -77,7 +77,7 @@ parichayAuth.get('/callback', async (req, res) => { url: CONSTANTS.PARICHAY_USER_DETAILS_URL, }) - logInfo('User information from Parichay : ' + JSON.stringify(userDetailResponse.data)) + logInfo('User information from Parichay received successfully. ') const loginId = userDetailResponse.data.loginId if (!loginId) { const errorMessage = 'iGOT login failed. You must allow Email id on the consent form for Login. ' @@ -130,7 +130,7 @@ parichayAuth.get('/callback', async (req, res) => { + ', Received a keycloak error: ' + keycloakResult.errMessage) result.errMessage = keycloakResult.errMessage } - logInfo('Parichay user session established in Keycloak: ' + JSON.stringify(keycloakResult)) + logInfo('Parichay user session established in Keycloak successfully.') } } if (result.errMessage !== '') { diff --git a/src/publicApi_v8/ssoUserHelper.ts b/src/publicApi_v8/ssoUserHelper.ts index 7e40cbbd..d0fa31d3 100644 --- a/src/publicApi_v8/ssoUserHelper.ts +++ b/src/publicApi_v8/ssoUserHelper.ts @@ -30,20 +30,20 @@ export async function fetchUserByEmailId(emailId: string) { } else if (sbUserSearchRes.data.result.response.count === 1) { const contentObj = sbUserSearchRes.data.result.response.content[0] const status = contentObj.status - logInfo('user account exist. Data: ' + JSON.stringify(sbUserSearchRes.data) + ', Status: ' + status) + logInfo('ssoUserHelper:: user account exist for :: ' + emailId + ', Status: ' + status) if (status === 1) { - logInfo('user account enabled. returning true') + logInfo('ssoUserHelper:: user account enabled. returning true') result.userExist = true result.rootOrgId = contentObj.rootOrgId } else { - logInfo('user account is diabled. throwing error') + logInfo('ssoUserHelper:: user account is diabled. throwing error') result.errMessage = 'Account Disabled. Please contact Admin.' } } else { result.errMessage = 'More than one user account exists. Please contact Admin.' } } else { - logError('googleOauthHelper: fetchUserByEmailId failed' + JSON.stringify(sbUserSearchRes.data)) + logError('ssoUserHelper:: fetchUserByEmailId failed' + JSON.stringify(sbUserSearchRes.data)) result.errMessage = 'Failed to verify email exist. Internal Server Error.' } return Promise.resolve(result) @@ -110,7 +110,7 @@ export async function createUserWithMailId(emailId: string, firstNameStr: string } } catch (signUpErr) { const errMsg = signUpErr.response.data.params.errmsg - logError ('Failed to create User, error msg : ' + errMsg) + logError ('ssoUserHelper:: Failed to create User, error msg : ' + errMsg) result.errMessage = errMsg } return Promise.resolve(result) @@ -131,7 +131,7 @@ export async function updateKeycloakSession(emailId: string, req: any, res: any) req.kauth.grant = grant const userId = req.kauth.grant.access_token.content.sub.split(':') req.session.userId = userId[userId.length - 1] - logInfo('userId ::', userId, '------', new Date().toString()) + logInfo('ssoUserHelper::updateKeycloakSession:: userId ::', userId, ' dateTime :: ', new Date().toString()) req.session.keycloakClientId = CONSTANTS.KEYCLOAK_GOOGLE_CLIENT_ID req.session.keycloakClientSecret = CONSTANTS.KEYCLOAK_GOOGLE_CLIENT_SECRET result.access_token = grant.access_token.token diff --git a/src/server.ts b/src/server.ts index 41c9dc1b..61701c89 100644 --- a/src/server.ts +++ b/src/server.ts @@ -188,11 +188,6 @@ export class Server { this.app.use('/reset', (_req, res) => { logInfo('CLEARING RES COOKIES') const host = _req.get('host') - logInfo('host is: ' + host) - logInfo('response cookies: ' + JSON.stringify(_req.session)) - logInfo('Cookies:' + _req.get('cookies')) - logInfo('Cookie:' + _req.get('cookie')) - logInfo('Cookies::::' + JSON.stringify(_req.cookies)) let domainUrl = '' if (host !== undefined) { if (host.includes('localhost')) { diff --git a/src/utils/apiWhiteList.ts b/src/utils/apiWhiteList.ts index 14ed6175..3d2c8432 100644 --- a/src/utils/apiWhiteList.ts +++ b/src/utils/apiWhiteList.ts @@ -366,27 +366,49 @@ const validateAPI = (req: Request, res: Response, next: NextFunction) => { respond403(req, res) } } +// tslint:disable-next-line: no-any +const shouldSkipWhitelistCheck = (path: string) => { + return path === '/' || checkIsStaticRoute(path) || _.includes(path, '/resource') || _.includes(path, '/eclogin') +} + +// tslint:disable-next-line: no-any +const hasValidUserRoles = (session: any) => { + return session && 'userRoles' in session && session.userRoles.length > 0 +} + +// tslint:disable-next-line: no-any +const logSessionDebugInfo = (session: any) => { + logError('Portal_API_WHITELIST_LOGGER: User needs to authenticated themselves', '------', new Date().toString()) + logError('Session ID: ' + (session ? session.id : 'NO SESSION ID')) + logError('Session userId: ' + (session ? session.userId : 'UNDEFINED')) + logError('Session userName: ' + (session ? session.userName : 'UNDEFINED')) + logError('Session userRoles: ' + (session ? JSON.stringify(session.userRoles) : 'UNDEFINED')) + logError('Session keycloak-token exists: ' + (session && session['keycloak-token'] ? 'YES' : 'NO')) +} + /** * This function is used for checking whether */ export function apiWhiteListLogger() { return (req: Request, res: Response, next: NextFunction) => { - if (req.path === '/' || checkIsStaticRoute(req.path)) { + if (shouldSkipWhitelistCheck(req.path)) { next() return } - const REQ_URL = req.path - if (!_.includes(REQ_URL, '/resource') && !_.includes(REQ_URL, '/eclogin') && (req.session)) { - if (!('userRoles' in req.session) || (('userRoles' in req.session) && (req.session.userRoles.length === 0))) { - logError('Portal_API_WHITELIST_LOGGER: User needs to authenticated themselves', '------', new Date().toString()) - respond419(req, res) - } else { - // Pattern match for URL - logInfo('In WhilteList Call========' + REQ_URL, '------', new Date().toString()) - validateAPI(req, res, next) - } - } else { - next() + + if (!req.session) { + logError('Portal_API_WHITELIST_LOGGER: No session found', '------', new Date().toString()) + respond419(req, res) + return } + + if (hasValidUserRoles(req.session)) { + logInfo('In WhilteList Call========' + req.path, '------', new Date().toString()) + validateAPI(req, res, next) + return + } + + logSessionDebugInfo(req.session) + respond419(req, res) } } diff --git a/src/utils/permissionHelper.ts b/src/utils/permissionHelper.ts index 962ada80..42a6ea45 100644 --- a/src/utils/permissionHelper.ts +++ b/src/utils/permissionHelper.ts @@ -9,10 +9,10 @@ import { extractUserToken } from './requestExtract' export const PERMISSION_HELPER = { // tslint:disable-next-line: no-any setRolesData(reqObj: any, callback: any, body: any) { - logInfo('permission helper:: setRolesData function ', '------', new Date().toString()) + logInfo('permissionHelper:: setRolesData function ', '------', new Date().toString()) // tslint:disable-next-line: no-any const userData: any = JSON.parse(body) - logInfo(JSON.stringify(userData)) + logInfo('permissionHelper:: received user data successfully.') if (reqObj.session) { reqObj.session.userId = userData.result.response.id ? userData.result.response.id : userData.result.response.userId reqObj.session.userName = userData.result.response.userName @@ -31,22 +31,22 @@ export const PERMISSION_HELPER = { if (!_.includes(reqObj.session.userRoles, 'PUBLIC')) { reqObj.session.userRoles.push('PUBLIC') } - this.createNodeBBUser(reqObj, callback) + + // Explicitly save session to ensure persistence // tslint:disable-next-line: no-any - // reqObj.session.save((error: any) => { - // if (error) { - // logError('reqObj.session.save error -- ', error) - // callback(error, null) - // } else { - // logInfo('Before calling createNodeBBUser', '------', new Date().toString()) - // this.createNodeBBUser(reqObj, callback) - // // callback(null, userData) - // } - // }) + reqObj.session.save((error: any) => { + if (error) { + logError('permissionHelper:: ERROR: Failed to save session with roles -- ', error) + callback(error, null) + } else { + logInfo('permissionHelper:: SUCCESS: Session saved with roles at ' + new Date().toString()) + callback(null, userData) + } + }) } else { - callback('reqObj.session no session', null) + callback('permissionHelper:: reqObj.session no session', null) } - logInfo('permission helper:: setRolesData function end', '------', new Date().toString()) + logInfo('permissionHelper:: setRolesData function end', '------', new Date().toString()) }, // tslint:disable-next-line: no-any setNodeBBUID(reqObj: any, callback: any, body: any) { @@ -72,7 +72,7 @@ export const PERMISSION_HELPER = { // tslint:disable-next-line: no-any getCurrentUserRoles(reqObj: any, callback: any) { const userId = reqObj.session.userId - logInfo('Step 3: getCurrentUserRoles for user ' + userId, '------', new Date().toString()) + logInfo('permissionHelper:: Step 3: getCurrentUserRoles for user ' + userId, '------', new Date().toString()) const readUrl = `${CONSTANTS.KONG_API_BASE}/user/v2/read/` + userId const options = { headers: { @@ -89,7 +89,7 @@ export const PERMISSION_HELPER = { // tslint:disable-next-line: no-any const userData: any = JSON.parse(body) if (userData.responseCode.toUpperCase() === 'OK') { - logInfo('Success user/v2/read::', '------', new Date().toString()) + logInfo('permissionHelper:: Success user/v2/read::', '------', new Date().toString()) this.setRolesData(reqObj, callback, body) } else { const errMsg = 'Failed to read the user with Id: ' + userId + 'Error: ' + userData.responseCode @@ -98,7 +98,7 @@ export const PERMISSION_HELPER = { } } if (err) { - logError('Making axios call to nodeBB ERROR -- ', err, '------', new Date().toString()) + logError('Making axios call to user read. ERROR -- ', err, '------', new Date().toString()) callback(err, null) } })