From 43545fa04ba4b76f411f0b1ce9f1169d4d84c7cf Mon Sep 17 00:00:00 2001 From: Saad Jutt Date: Sun, 5 Dec 2021 08:17:54 +0500 Subject: [PATCH] chore: added check session + code refactor --- DockerfileApi | 1 - api/public/swagger.yaml | 32 ++++++++++++++++++++--- api/src/controllers/index.ts | 1 + api/src/controllers/internal/Execution.ts | 22 ++++++---------- api/src/controllers/session.ts | 30 +++++++++++++++++++++ api/src/controllers/stp.ts | 24 +++++------------ api/src/middlewares/authenticateToken.ts | 2 +- api/src/middlewares/desktop.ts | 18 +++++++++++++ api/src/middlewares/desktopRestrict.ts | 7 ----- api/src/middlewares/index.ts | 2 +- api/src/routes/api/index.ts | 3 +++ api/src/routes/api/session.ts | 17 ++++++++++++ api/src/utils/connectDB.ts | 10 +++---- api/tsoa.json | 4 +++ 14 files changed, 123 insertions(+), 50 deletions(-) create mode 100644 api/src/controllers/session.ts create mode 100644 api/src/middlewares/desktop.ts delete mode 100644 api/src/middlewares/desktopRestrict.ts create mode 100644 api/src/routes/api/session.ts diff --git a/DockerfileApi b/DockerfileApi index 3386b4b..aefb9e2 100644 --- a/DockerfileApi +++ b/DockerfileApi @@ -1,5 +1,4 @@ FROM node:lts-alpine -RUN npm install -g @sasjs/cli WORKDIR /usr/server/api COPY ["package.json","package-lock.json", "./"] RUN npm ci diff --git a/api/public/swagger.yaml b/api/public/swagger.yaml index 4795851..eb7c25d 100644 --- a/api/public/swagger.yaml +++ b/api/public/swagger.yaml @@ -362,14 +362,15 @@ components: properties: status: type: string - log: - type: string _webout: type: string + log: + type: string message: type: string required: - status + - _webout type: object additionalProperties: false ExecuteReturnJsonPayload: @@ -981,7 +982,7 @@ paths: application/json: schema: type: string - description: "Trigger a SAS program using it's location in the _program parameter.\r\nEnable debugging using the _debug parameter.\r\nAdditional URL parameters are turned into SAS macro variables.\r\nAny files provided are placed into the session and\r\ncorresponding _WEBIN_XXX variables are created." + description: "Trigger a SAS program using it's location in the _program parameter.\nEnable debugging using the _debug parameter.\nAdditional URL parameters are turned into SAS macro variables.\nAny files provided are placed into the session and\ncorresponding _WEBIN_XXX variables are created." summary: 'Execute Stored Program, return raw content' tags: - STP @@ -1005,7 +1006,7 @@ paths: application/json: schema: $ref: '#/components/schemas/ExecuteReturnJsonResponse' - description: "Trigger a SAS program using it's location in the _program parameter.\r\nEnable debugging using the _debug parameter.\r\nAdditional URL parameters are turned into SAS macro variables.\r\nAny files provided are placed into the session and\r\ncorresponding _WEBIN_XXX variables are created." + description: "Trigger a SAS program using it's location in the _program parameter.\nEnable debugging using the _debug parameter.\nAdditional URL parameters are turned into SAS macro variables.\nAny files provided are placed into the session and\ncorresponding _WEBIN_XXX variables are created." summary: 'Execute Stored Program, return JSON' tags: - STP @@ -1026,10 +1027,33 @@ paths: application/json: schema: $ref: '#/components/schemas/ExecuteReturnJsonPayload' + /SASjsApi/session: + get: + operationId: Session + responses: + '200': + description: Ok + content: + application/json: + schema: + $ref: '#/components/schemas/UserResponse' + examples: + 'Example 1': + value: {id: 123, username: johnusername, displayName: John} + summary: 'Get session info (username).' + tags: + - Session + security: + - + bearerAuth: [] + parameters: [] servers: - url: / tags: + - + name: Session + description: 'Get Session information' - name: User description: 'Operations about users' diff --git a/api/src/controllers/index.ts b/api/src/controllers/index.ts index 0a1e74b..805cc3c 100644 --- a/api/src/controllers/index.ts +++ b/api/src/controllers/index.ts @@ -4,3 +4,4 @@ export * from './drive' export * from './group' export * from './stp' export * from './user' +export * from './session' diff --git a/api/src/controllers/internal/Execution.ts b/api/src/controllers/internal/Execution.ts index c19d2e1..6738142 100644 --- a/api/src/controllers/internal/Execution.ts +++ b/api/src/controllers/internal/Execution.ts @@ -100,26 +100,20 @@ ${program}` const debugValue = typeof vars._debug === 'string' ? parseInt(vars._debug) : vars._debug - let debugResponse: string | undefined - - if ((debugValue && debugValue >= 131) || session.crashed) { - debugResponse = `${webout}

SAS Log

${log}
` - } - session.inUse = false sessionController.deleteSession(session) if (returnJson) { - const response: any = { - webout: webout + return { + webout, + log: + (debugValue && debugValue >= 131) || session.crashed ? log : undefined } - if ((debugValue && debugValue >= 131) || session.crashed) { - response.log = log - } - - return response } - return debugResponse ?? webout + + return (debugValue && debugValue >= 131) || session.crashed + ? `${webout}

SAS Log

${log}
` + : webout } buildDirectorytree() { diff --git a/api/src/controllers/session.ts b/api/src/controllers/session.ts new file mode 100644 index 0000000..1e3dd59 --- /dev/null +++ b/api/src/controllers/session.ts @@ -0,0 +1,30 @@ +import express from 'express' +import { Request, Security, Route, Tags, Example, Get } from 'tsoa' +import { UserResponse } from './user' + +@Security('bearerAuth') +@Route('SASjsApi/session') +@Tags('Session') +export class SessionController { + /** + * @summary Get session info (username). + * + */ + @Example({ + id: 123, + username: 'johnusername', + displayName: 'John' + }) + @Get('/') + public async session( + @Request() request: express.Request + ): Promise { + return session(request) + } +} + +const session = (req: any) => ({ + id: req.user.id, + username: req.user.username, + displayName: req.user.displayName +}) diff --git a/api/src/controllers/stp.ts b/api/src/controllers/stp.ts index 632b576..eb90c9d 100644 --- a/api/src/controllers/stp.ts +++ b/api/src/controllers/stp.ts @@ -1,16 +1,6 @@ -import express, { response } from 'express' +import express from 'express' import path from 'path' -import { - Request, - Security, - Route, - Tags, - Example, - Post, - Body, - Get, - Query -} from 'tsoa' +import { Request, Security, Route, Tags, Post, Body, Get, Query } from 'tsoa' import { ExecutionController } from './internal' import { PreProgramVars } from '../types' import { getTmpFilesFolderPath, makeFilesNamesMap } from '../utils' @@ -24,8 +14,8 @@ interface ExecuteReturnJsonPayload { } interface ExecuteReturnJsonResponse { status: string + _webout: string log?: string - _webout?: string message?: string } @@ -111,17 +101,17 @@ const executeReturnJson = async ( const filesNamesMap = req.files?.length ? makeFilesNamesMap(req.files) : null try { - const jsonResult: any = await new ExecutionController().execute( + const { webout, log } = (await new ExecutionController().execute( sasCodePath, getPreProgramVariables(req), { ...req.query, ...req.body }, { filesNamesMap: filesNamesMap }, true - ) + )) as { webout: string; log: string } return { status: 'success', - _webout: jsonResult.webout, - log: jsonResult.log + _webout: webout, + log } } catch (err: any) { throw { diff --git a/api/src/middlewares/authenticateToken.ts b/api/src/middlewares/authenticateToken.ts index 82c5952..b53900e 100644 --- a/api/src/middlewares/authenticateToken.ts +++ b/api/src/middlewares/authenticateToken.ts @@ -26,7 +26,7 @@ const authenticateToken = ( res: any, next: any, key: string, - tokenType: 'accessToken' | 'refreshToken' = 'accessToken' + tokenType: 'accessToken' | 'refreshToken' ) => { const { MODE } = process.env if (MODE?.trim() !== 'server') { diff --git a/api/src/middlewares/desktop.ts b/api/src/middlewares/desktop.ts new file mode 100644 index 0000000..3444adf --- /dev/null +++ b/api/src/middlewares/desktop.ts @@ -0,0 +1,18 @@ +export const desktopRestrict = (req: any, res: any, next: any) => { + const { MODE } = process.env + if (MODE?.trim() !== 'server') + return res.status(403).send('Not Allowed while in Desktop Mode.') + + next() +} +export const desktopUsername = (req: any, res: any, next: any) => { + const { MODE } = process.env + if (MODE?.trim() !== 'server') + return res.status(200).send({ + userId: 12345, + username: 'DESKTOPusername', + displayName: 'DESKTOP User' + }) + + next() +} diff --git a/api/src/middlewares/desktopRestrict.ts b/api/src/middlewares/desktopRestrict.ts deleted file mode 100644 index f555293..0000000 --- a/api/src/middlewares/desktopRestrict.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const desktopRestrict = (req: any, res: any, next: any) => { - const { MODE } = process.env - if (MODE?.trim() !== 'server') - return res.status(403).send('Not Allowed while in Desktop Mode.') - - next() -} diff --git a/api/src/middlewares/index.ts b/api/src/middlewares/index.ts index 3c32d97..7798de3 100644 --- a/api/src/middlewares/index.ts +++ b/api/src/middlewares/index.ts @@ -1,4 +1,4 @@ export * from './authenticateToken' -export * from './desktopRestrict' +export * from './desktop' export * from './verifyAdmin' export * from './verifyAdminIfNeeded' diff --git a/api/src/routes/api/index.ts b/api/src/routes/api/index.ts index fcfb6d9..b91715c 100644 --- a/api/src/routes/api/index.ts +++ b/api/src/routes/api/index.ts @@ -5,6 +5,7 @@ import swaggerUi from 'swagger-ui-express' import { authenticateAccessToken, desktopRestrict, + desktopUsername, verifyAdmin } from '../../middlewares' @@ -14,9 +15,11 @@ import userRouter from './user' import groupRouter from './group' import clientRouter from './client' import authRouter from './auth' +import sessionRouter from './session' const router = express.Router() +router.use('/session', desktopUsername, authenticateAccessToken, sessionRouter) router.use('/auth', desktopRestrict, authRouter) router.use( '/client', diff --git a/api/src/routes/api/session.ts b/api/src/routes/api/session.ts new file mode 100644 index 0000000..436f0b2 --- /dev/null +++ b/api/src/routes/api/session.ts @@ -0,0 +1,17 @@ +import express from 'express' +import { SessionController } from '../../controllers' +import { authenticateAccessToken } from '../../middlewares' + +const sessionRouter = express.Router() + +sessionRouter.get('/', async (req, res) => { + const controller = new SessionController() + try { + const response = await controller.session(req) + res.send(response) + } catch (err: any) { + res.status(403).send(err.toString()) + } +}) + +export default sessionRouter diff --git a/api/src/utils/connectDB.ts b/api/src/utils/connectDB.ts index 1ba640a..4e28cb2 100644 --- a/api/src/utils/connectDB.ts +++ b/api/src/utils/connectDB.ts @@ -18,13 +18,13 @@ export const connectDB = async () => { process.driveLoc = driveLoc return - } else { - const { SAS_PATH } = process.env - const sasDir = SAS_PATH ?? configuration.sasPath - - process.sasLoc = path.join(sasDir, 'sas') } + const { SAS_PATH } = process.env + const sasDir = SAS_PATH ?? configuration.sasPath + + process.sasLoc = path.join(sasDir, 'sas') + console.log('sasLoc: ', process.sasLoc) mongoose.connect(process.env.DB_CONNECT as string, async (err) => { diff --git a/api/tsoa.json b/api/tsoa.json index 6bb9d1a..b1b912b 100644 --- a/api/tsoa.json +++ b/api/tsoa.json @@ -11,6 +11,10 @@ } }, "tags": [ + { + "name": "Session", + "description": "Get Session information" + }, { "name": "User", "description": "Operations about users"