1
0
mirror of https://github.com/sasjs/server.git synced 2025-12-11 03:34:35 +00:00

chore: added check session + code refactor

This commit is contained in:
Saad Jutt
2021-12-05 08:17:54 +05:00
parent a80e5c8ead
commit 43545fa04b
14 changed files with 123 additions and 50 deletions

View File

@@ -1,5 +1,4 @@
FROM node:lts-alpine FROM node:lts-alpine
RUN npm install -g @sasjs/cli
WORKDIR /usr/server/api WORKDIR /usr/server/api
COPY ["package.json","package-lock.json", "./"] COPY ["package.json","package-lock.json", "./"]
RUN npm ci RUN npm ci

View File

@@ -362,14 +362,15 @@ components:
properties: properties:
status: status:
type: string type: string
log:
type: string
_webout: _webout:
type: string type: string
log:
type: string
message: message:
type: string type: string
required: required:
- status - status
- _webout
type: object type: object
additionalProperties: false additionalProperties: false
ExecuteReturnJsonPayload: ExecuteReturnJsonPayload:
@@ -981,7 +982,7 @@ paths:
application/json: application/json:
schema: schema:
type: string 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' summary: 'Execute Stored Program, return raw content'
tags: tags:
- STP - STP
@@ -1005,7 +1006,7 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/ExecuteReturnJsonResponse' $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' summary: 'Execute Stored Program, return JSON'
tags: tags:
- STP - STP
@@ -1026,10 +1027,33 @@ paths:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/ExecuteReturnJsonPayload' $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: servers:
- -
url: / url: /
tags: tags:
-
name: Session
description: 'Get Session information'
- -
name: User name: User
description: 'Operations about users' description: 'Operations about users'

View File

@@ -4,3 +4,4 @@ export * from './drive'
export * from './group' export * from './group'
export * from './stp' export * from './stp'
export * from './user' export * from './user'
export * from './session'

View File

@@ -100,26 +100,20 @@ ${program}`
const debugValue = const debugValue =
typeof vars._debug === 'string' ? parseInt(vars._debug) : vars._debug typeof vars._debug === 'string' ? parseInt(vars._debug) : vars._debug
let debugResponse: string | undefined
if ((debugValue && debugValue >= 131) || session.crashed) {
debugResponse = `<html><body>${webout}<div style="text-align:left"><hr /><h2>SAS Log</h2><pre>${log}</pre></div></body></html>`
}
session.inUse = false session.inUse = false
sessionController.deleteSession(session) sessionController.deleteSession(session)
if (returnJson) { if (returnJson) {
const response: any = { return {
webout: webout 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
? `<html><body>${webout}<div style="text-align:left"><hr /><h2>SAS Log</h2><pre>${log}</pre></div></body></html>`
: webout
} }
buildDirectorytree() { buildDirectorytree() {

View File

@@ -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<UserResponse>({
id: 123,
username: 'johnusername',
displayName: 'John'
})
@Get('/')
public async session(
@Request() request: express.Request
): Promise<UserResponse> {
return session(request)
}
}
const session = (req: any) => ({
id: req.user.id,
username: req.user.username,
displayName: req.user.displayName
})

View File

@@ -1,16 +1,6 @@
import express, { response } from 'express' import express from 'express'
import path from 'path' import path from 'path'
import { import { Request, Security, Route, Tags, Post, Body, Get, Query } from 'tsoa'
Request,
Security,
Route,
Tags,
Example,
Post,
Body,
Get,
Query
} from 'tsoa'
import { ExecutionController } from './internal' import { ExecutionController } from './internal'
import { PreProgramVars } from '../types' import { PreProgramVars } from '../types'
import { getTmpFilesFolderPath, makeFilesNamesMap } from '../utils' import { getTmpFilesFolderPath, makeFilesNamesMap } from '../utils'
@@ -24,8 +14,8 @@ interface ExecuteReturnJsonPayload {
} }
interface ExecuteReturnJsonResponse { interface ExecuteReturnJsonResponse {
status: string status: string
_webout: string
log?: string log?: string
_webout?: string
message?: string message?: string
} }
@@ -111,17 +101,17 @@ const executeReturnJson = async (
const filesNamesMap = req.files?.length ? makeFilesNamesMap(req.files) : null const filesNamesMap = req.files?.length ? makeFilesNamesMap(req.files) : null
try { try {
const jsonResult: any = await new ExecutionController().execute( const { webout, log } = (await new ExecutionController().execute(
sasCodePath, sasCodePath,
getPreProgramVariables(req), getPreProgramVariables(req),
{ ...req.query, ...req.body }, { ...req.query, ...req.body },
{ filesNamesMap: filesNamesMap }, { filesNamesMap: filesNamesMap },
true true
) )) as { webout: string; log: string }
return { return {
status: 'success', status: 'success',
_webout: jsonResult.webout, _webout: webout,
log: jsonResult.log log
} }
} catch (err: any) { } catch (err: any) {
throw { throw {

View File

@@ -26,7 +26,7 @@ const authenticateToken = (
res: any, res: any,
next: any, next: any,
key: string, key: string,
tokenType: 'accessToken' | 'refreshToken' = 'accessToken' tokenType: 'accessToken' | 'refreshToken'
) => { ) => {
const { MODE } = process.env const { MODE } = process.env
if (MODE?.trim() !== 'server') { if (MODE?.trim() !== 'server') {

View File

@@ -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()
}

View File

@@ -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()
}

View File

@@ -1,4 +1,4 @@
export * from './authenticateToken' export * from './authenticateToken'
export * from './desktopRestrict' export * from './desktop'
export * from './verifyAdmin' export * from './verifyAdmin'
export * from './verifyAdminIfNeeded' export * from './verifyAdminIfNeeded'

View File

@@ -5,6 +5,7 @@ import swaggerUi from 'swagger-ui-express'
import { import {
authenticateAccessToken, authenticateAccessToken,
desktopRestrict, desktopRestrict,
desktopUsername,
verifyAdmin verifyAdmin
} from '../../middlewares' } from '../../middlewares'
@@ -14,9 +15,11 @@ import userRouter from './user'
import groupRouter from './group' import groupRouter from './group'
import clientRouter from './client' import clientRouter from './client'
import authRouter from './auth' import authRouter from './auth'
import sessionRouter from './session'
const router = express.Router() const router = express.Router()
router.use('/session', desktopUsername, authenticateAccessToken, sessionRouter)
router.use('/auth', desktopRestrict, authRouter) router.use('/auth', desktopRestrict, authRouter)
router.use( router.use(
'/client', '/client',

View File

@@ -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

View File

@@ -18,13 +18,13 @@ export const connectDB = async () => {
process.driveLoc = driveLoc process.driveLoc = driveLoc
return 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) console.log('sasLoc: ', process.sasLoc)
mongoose.connect(process.env.DB_CONNECT as string, async (err) => { mongoose.connect(process.env.DB_CONNECT as string, async (err) => {

View File

@@ -11,6 +11,10 @@
} }
}, },
"tags": [ "tags": [
{
"name": "Session",
"description": "Get Session information"
},
{ {
"name": "User", "name": "User",
"description": "Operations about users" "description": "Operations about users"