From 46e39d228fedd6cbb77bac46af5cd908c53894e0 Mon Sep 17 00:00:00 2001 From: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> Date: Tue, 20 Jan 2026 10:20:02 +0530 Subject: [PATCH 1/6] docs(readme): add documentation badge (#124) --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d24c6ce..37d6505e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # AMRIT - Telemedicine (TM) Service [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) -![Build Status](https://github.com/PSMRI/TM-API/actions/workflows/sast-and-package.yml/badge.svg) +[![DeepWiki](https://img.shields.io/badge/DeepWiki-PSMRI%2FTM--API-blue)](https://deepwiki.com/PSMRI/TM-API) + The AMRIT Telemedicine (TM) Service enhances the capabilities of Health and Wellness Centers (HWCs) by providing remote healthcare services, improving accessibility, enabling collaborative care, and integrating with other facilities such as drug dispensing and laboratory services. This service aims to extend the reach and convenience of HWCs, ensuring that patients receive necessary medical advice and services without the need for in-person visits. From 732e6e78b051e3affd162e96d495248fa80df74d Mon Sep 17 00:00:00 2001 From: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> Date: Wed, 11 Feb 2026 19:46:04 +0530 Subject: [PATCH 2/6] chore(swagger): automate swagger sync to amrit-docs (#127) * docs(readme): add documentation badge * chore(swagger): automate swagger sync to amrit-docs * chore(swagger): automate swagger sync to amrit-docs * chore(swagger): update swagger work flow and properties --- .github/workflows/swagger-json.yml | 107 ++++++++++++++++++ pom.xml | 5 + .../resources/application-swagger.properties | 51 +++++++++ 3 files changed, 163 insertions(+) create mode 100644 .github/workflows/swagger-json.yml create mode 100644 src/main/resources/application-swagger.properties diff --git a/.github/workflows/swagger-json.yml b/.github/workflows/swagger-json.yml new file mode 100644 index 00000000..a92bd78a --- /dev/null +++ b/.github/workflows/swagger-json.yml @@ -0,0 +1,107 @@ +name: Sync Swagger to AMRIT-Docs + +on: + push: + branches: [ main ] + workflow_dispatch: + +jobs: + swagger-sync: + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Checkout API repo + uses: actions/checkout@v4 + + - name: Set up Java 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + cache: maven + + - name: Build API (skip tests) + run: mvn -B clean package -DskipTests + + - name: Install jq + run: sudo apt-get update && sudo apt-get install -y jq + + - name: Run API in swagger profile + run: | + nohup java -jar target/tm-api-*.war \ + --spring.profiles.active=swagger \ + --server.port=9090 \ + > app.log 2>&1 & + echo $! > api_pid.txt + + - name: Wait for API & fetch Swagger + run: | + for i in {1..40}; do + CODE=$(curl --connect-timeout 2 --max-time 5 -s -o swagger_raw.json -w "%{http_code}" http://localhost:9090/v3/api-docs || true) + + if [ "$CODE" = "200" ]; then + jq . swagger_raw.json > tm-api.json || { + echo "Swagger JSON invalid" + cat swagger_raw.json + exit 1 + } + + if [ "$(jq '.paths | length' tm-api.json)" -eq 0 ]; then + echo "Swagger paths empty – failing" + exit 1 + fi + + echo "Swagger generated successfully" + exit 0 + fi + + echo "Waiting for API... ($i)" + sleep 4 + done + + echo "Swagger not generated" + cat app.log || true + exit 1 + + - name: Stop API + if: always() + run: | + # Graceful shutdown of the process group + sleep 5 + # Force kill the process group if still running + if [ -f api_pid.txt ]; then + PID=$(cat api_pid.txt) + kill -TERM -- -"$PID" 2>/dev/null || true + sleep 2 + kill -9 -- -"$PID" 2>/dev/null || true + fi + # Fallback: kill any remaining java process on port 9090 + fuser -k 9090/tcp 2>/dev/null || true + + - name: Checkout AMRIT-Docs + uses: actions/checkout@v4 + with: + repository: PSMRI/AMRIT-Docs + token: ${{ secrets.DOCS_REPO_TOKEN }} + path: amrit-docs + fetch-depth: 0 + + - name: Copy Swagger JSON + run: | + mkdir -p amrit-docs/docs/swagger + cp tm-api.json amrit-docs/docs/swagger/tm-api.json + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v8 + with: + token: ${{ secrets.DOCS_REPO_TOKEN }} + path: amrit-docs + branch: auto/swagger-update-${{ github.run_id }}-${{ github.run_attempt }} + base: main + commit-message: "chore(docs): auto-update TM-API swagger" + title: "chore(docs): auto-update TM-API swagger" + delete-branch: true + body: | + This PR automatically updates TM-API Swagger JSON + from the latest main branch build. diff --git a/pom.xml b/pom.xml index cd3a8f6d..56d3b951 100644 --- a/pom.xml +++ b/pom.xml @@ -294,6 +294,11 @@ 0.12.6 runtime + + com.h2database + h2 + runtime + diff --git a/src/main/resources/application-swagger.properties b/src/main/resources/application-swagger.properties new file mode 100644 index 00000000..fb4b94b3 --- /dev/null +++ b/src/main/resources/application-swagger.properties @@ -0,0 +1,51 @@ +spring.datasource.url=jdbc:h2:mem:swaggerdb +spring.datasource.driver-class-name=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create-drop +spring.redis.host=${REDIS_HOST:localhost} +spring.redis.port=${REDIS_PORT:6379} +cors.allowed-origins=${CORS_ALLOWED_ORIGINS:http://localhost:9090,http://localhost:8080} +logging.level.root=INFO +jwt.secret=${JWT_SECRET_KEY:#{T(java.util.UUID).randomUUID().toString()}} +common-api-url-searchBeneficiary=http://localhost:8080/beneficiary/search +common-api-url-searchuserbyid=http://localhost:8080/user/searchbyid +openkmDocUrl=http://localhost:8080/openkm +nurseWL=90 +nurseTCWL=90 +pharmaWL=90 +pharmaTCWL=90 +ashaWL=90 +ashaTCWL=90 +labWL=90 +labTCWL=90 +radioWL=90 +radioTCWL=90 +oncoWL=90 +oncoTCWL=90 +tcSpecialistSlotBook=true +tcSpecialistSlotCancel=true +TMReferredWL=90 +docWL=90 +docTCWL=90 +swymed_dnsname=swymed://psmri.swymed.com +jitsi_dnsname=https://meet.jit.si +fotesenseFilePath=${FETOSENSE_FILE_PATH:/tmp/fetosense-report} +fetosenseAPIKey=${FETOSENSE_API_KEY:defualt-key} +scheduling-slotsize=5 +schedule=default +tcSpeclistWL=90 +tcSpeclistTCWL=90 +sendSMSUrl=http://localhost:8080/sms/send +prescription=default +cancel=default +reSchedule=default +snomedCTPageSize=50 +registrarQuickSearchByIdUrl=http://localhost:8080/registrar/quicksearchbyid +registrarQuickSearchByPhoneNoUrl=http://localhost:8080/registrar/quicksearchbyphoneno +registrarAdvanceSearchUrl=http://localhost:8080/registrar/advancesearch +carestreamOrderCreateURL=http://localhost:8080/carestream/order/create +getBenImageFromIdentity=http://localhost:8080/identity/ben/image +dataSyncUploadUrl=http://localhost:8080/datasync/upload +dataSyncDownloadUrl= +registrationUrl=http://localhost:8080/registration +beneficiaryEditUrl=http://localhost:8080/beneficiary/edit From 5b646dcf5369e7ee4cf3d02e576302538b1a9653 Mon Sep 17 00:00:00 2001 From: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:32:09 +0530 Subject: [PATCH 3/6] Add new workflow and server urls (#129) * docs(readme): add documentation badge * chore(swagger): automate swagger sync to amrit-docs * chore(swagger): automate swagger sync to amrit-docs * chore(swagger): update swagger work flow and properties * chore(swagger): update swagger workflow and add server urls * chore(swagger): fix the version issue in swaggerconfig.java --- .github/workflows/swagger-json.yml | 2 +- .../com/iemr/tm/config/SwaggerConfig.java | 29 ++++++++++++++----- .../resources/application-swagger.properties | 4 +++ 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/.github/workflows/swagger-json.yml b/.github/workflows/swagger-json.yml index a92bd78a..c658d340 100644 --- a/.github/workflows/swagger-json.yml +++ b/.github/workflows/swagger-json.yml @@ -97,7 +97,7 @@ jobs: with: token: ${{ secrets.DOCS_REPO_TOKEN }} path: amrit-docs - branch: auto/swagger-update-${{ github.run_id }}-${{ github.run_attempt }} + branch: auto/swagger-update-tm-api base: main commit-message: "chore(docs): auto-update TM-API swagger" title: "chore(docs): auto-update TM-API swagger" diff --git a/src/main/java/com/iemr/tm/config/SwaggerConfig.java b/src/main/java/com/iemr/tm/config/SwaggerConfig.java index 6ebc2666..82883a43 100644 --- a/src/main/java/com/iemr/tm/config/SwaggerConfig.java +++ b/src/main/java/com/iemr/tm/config/SwaggerConfig.java @@ -2,6 +2,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; @@ -11,14 +12,26 @@ @Configuration public class SwaggerConfig { - - @Bean - public OpenAPI customOpenAPI() { - return new OpenAPI().info(new - Info().title("TeleMedicine(TM) API").version("version").description("A microservice for the creation and management of beneficiaries.")) - .addSecurityItem(new SecurityRequirement().addList("my security")) - .components(new Components().addSecuritySchemes("my security", - new SecurityScheme().name("my security").type(SecurityScheme.Type.HTTP).scheme("bearer"))); + private static final String DEFAULT_SERVER_URL = "http://localhost:9090"; + + @Bean + public OpenAPI customOpenAPI(Environment env) { + String devUrl = env.getProperty("api.dev.url", DEFAULT_SERVER_URL); + String uatUrl = env.getProperty("api.uat.url", DEFAULT_SERVER_URL); + String demoUrl = env.getProperty("api.demo.url", DEFAULT_SERVER_URL); + return new OpenAPI() + .info(new Info() + .title("TeleMedicine(TM) API") + .version("1.0.0") + .description("A microservice for TeleMedicine, providing APIs for remote healthcare consultations, patient management, and related telehealth operations.")) + .addSecurityItem(new SecurityRequirement().addList("my security")) + .components(new Components().addSecuritySchemes("my security", + new SecurityScheme().name("my security").type(SecurityScheme.Type.HTTP).scheme("bearer"))) + .servers(java.util.Arrays.asList( + new io.swagger.v3.oas.models.servers.Server().url(devUrl).description("Dev"), + new io.swagger.v3.oas.models.servers.Server().url(uatUrl).description("UAT"), + new io.swagger.v3.oas.models.servers.Server().url(demoUrl).description("Demo") + )); } } diff --git a/src/main/resources/application-swagger.properties b/src/main/resources/application-swagger.properties index fb4b94b3..826b83dd 100644 --- a/src/main/resources/application-swagger.properties +++ b/src/main/resources/application-swagger.properties @@ -1,3 +1,7 @@ +# Swagger server URLs +api.dev.url=${API_DEV_URL:https://amritwprdev.piramalswasthya.org} +api.uat.url=${API_UAT_URL:https://uatamrit.piramalswasthya.org} +api.demo.url=${API_DEMO_URL:https://amritdemo.piramalswasthya.org} spring.datasource.url=jdbc:h2:mem:swaggerdb spring.datasource.driver-class-name=org.h2.Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect From 0c6c8287729b53a4bb5656939d58fe2fdce86760 Mon Sep 17 00:00:00 2001 From: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> Date: Mon, 2 Mar 2026 10:11:52 +0530 Subject: [PATCH 4/6] feat(health,version): add health and version endpoints (#130) * feat(healt,version): add health and version endpoints * fix(health): improve Redis health semantics when not configured * fix(health): scope PROCESSLIST lock-wait check to application DB user * fix(health): Removed the unused import * fix(health): avoid blocking DB I/O under write lock and restore interrupt flag * fix: add missin close brace * fix(health): cancel in-flight futures on generic failure * fix(health): fail-open on advanced MySQL check exceptions to avoid false degraded state --- pom.xml | 28 +- .../controller/health/HealthController.java | 84 +++ .../controller/version/VersionController.java | 58 +- .../iemr/tm/service/health/HealthService.java | 526 ++++++++++++++++++ .../tm/utils/JwtUserIdValidationFilter.java | 3 +- 5 files changed, 668 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/iemr/tm/controller/health/HealthController.java create mode 100644 src/main/java/com/iemr/tm/service/health/HealthService.java diff --git a/pom.xml b/pom.xml index 56d3b951..40e64be4 100644 --- a/pom.xml +++ b/pom.xml @@ -304,7 +304,7 @@ - ${artifactId}-${version} + ${project.artifactId}-${project.version} @@ -348,6 +348,32 @@ maven-jar-plugin 3.0.2 + + io.github.git-commit-id + git-commit-id-maven-plugin + 9.0.2 + + + get-the-git-infos + + revision + + initialize + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.branch$ + ^git.commit.id.abbrev$ + ^git.build.version$ + ^git.build.time$ + + false + false + + org.springframework.boot spring-boot-maven-plugin diff --git a/src/main/java/com/iemr/tm/controller/health/HealthController.java b/src/main/java/com/iemr/tm/controller/health/HealthController.java new file mode 100644 index 00000000..650bf402 --- /dev/null +++ b/src/main/java/com/iemr/tm/controller/health/HealthController.java @@ -0,0 +1,84 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.tm.controller.health; + +import java.time.Instant; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.iemr.tm.service.health.HealthService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("/health") +@Tag(name = "Health Check", description = "APIs for checking infrastructure health status") +public class HealthController { + + private static final Logger logger = LoggerFactory.getLogger(HealthController.class); + + private final HealthService healthService; + + public HealthController(HealthService healthService) { + this.healthService = healthService; + } + + @GetMapping + @Operation(summary = "Check infrastructure health", + description = "Returns the health status of MySQL, Redis, and other configured services") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Services are UP or DEGRADED (operational with warnings)"), + @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") + }) + public ResponseEntity> checkHealth() { + logger.info("Health check endpoint called"); + + try { + Map healthStatus = healthService.checkHealth(); + String overallStatus = (String) healthStatus.get("status"); + + // Return 503 only if DOWN; 200 for both UP and DEGRADED (DEGRADED = operational with warnings) + HttpStatus httpStatus = "DOWN".equals(overallStatus) ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.OK; + + logger.debug("Health check completed with status: {}", overallStatus); + return new ResponseEntity<>(healthStatus, httpStatus); + + } catch (Exception e) { + logger.error("Unexpected error during health check", e); + + Map errorResponse = Map.of( + "status", "DOWN", + "timestamp", Instant.now().toString() + ); + + return new ResponseEntity<>(errorResponse, HttpStatus.SERVICE_UNAVAILABLE); + } + } +} diff --git a/src/main/java/com/iemr/tm/controller/version/VersionController.java b/src/main/java/com/iemr/tm/controller/version/VersionController.java index 336d34e8..d320cc8f 100644 --- a/src/main/java/com/iemr/tm/controller/version/VersionController.java +++ b/src/main/java/com/iemr/tm/controller/version/VersionController.java @@ -21,59 +21,59 @@ */ package com.iemr.tm.controller.version; -import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import com.iemr.tm.utils.response.OutputResponse; - import io.swagger.v3.oas.annotations.Operation; @RestController public class VersionController { - private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + private static final String UNKNOWN_VALUE = "unknown"; @Operation(summary = "Get version information") - @GetMapping(value = "/version") - public String versionInformation() { - OutputResponse output = new OutputResponse(); + @GetMapping(value = "/version", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> versionInformation() { + Map response = new LinkedHashMap<>(); try { logger.info("version Controller Start"); - output.setResponse(readGitProperties()); + Properties gitProperties = loadGitProperties(); + response.put("buildTimestamp", gitProperties.getProperty("git.build.time", UNKNOWN_VALUE)); + response.put("version", gitProperties.getProperty("git.build.version", UNKNOWN_VALUE)); + response.put("branch", gitProperties.getProperty("git.branch", UNKNOWN_VALUE)); + response.put("commitHash", gitProperties.getProperty("git.commit.id.abbrev", UNKNOWN_VALUE)); } catch (Exception e) { - output.setError(e); + logger.error("Failed to load version information", e); + response.put("buildTimestamp", UNKNOWN_VALUE); + response.put("version", UNKNOWN_VALUE); + response.put("branch", UNKNOWN_VALUE); + response.put("commitHash", UNKNOWN_VALUE); } - logger.info("version Controller End"); - return output.toString(); - } - - private String readGitProperties() throws Exception { - ClassLoader classLoader = getClass().getClassLoader(); - InputStream inputStream = classLoader.getResourceAsStream("git.properties"); - - return readFromInputStream(inputStream); + return ResponseEntity.ok(response); } - private String readFromInputStream(InputStream inputStream) - throws IOException { - StringBuilder resultStringBuilder = new StringBuilder(); - try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { - String line; - while ((line = br.readLine()) != null) { - resultStringBuilder.append(line).append("\n"); + private Properties loadGitProperties() throws IOException { + Properties properties = new Properties(); + try (InputStream input = getClass().getClassLoader() + .getResourceAsStream("git.properties")) { + if (input != null) { + properties.load(input); } } - return resultStringBuilder.toString(); + return properties; } } diff --git a/src/main/java/com/iemr/tm/service/health/HealthService.java b/src/main/java/com/iemr/tm/service/health/HealthService.java new file mode 100644 index 00000000..d18c76bc --- /dev/null +++ b/src/main/java/com/iemr/tm/service/health/HealthService.java @@ -0,0 +1,526 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.tm.service.health; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import jakarta.annotation.PreDestroy; +import javax.sql.DataSource; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +@Service +public class HealthService { + + private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + + private static final String STATUS_KEY = "status"; + private static final String STATUS_UP = "UP"; + private static final String STATUS_DOWN = "DOWN"; + private static final String STATUS_DEGRADED = "DEGRADED"; + private static final String SEVERITY_KEY = "severity"; + private static final String SEVERITY_OK = "OK"; + private static final String SEVERITY_WARNING = "WARNING"; + private static final String SEVERITY_CRITICAL = "CRITICAL"; + private static final String ERROR_KEY = "error"; + private static final String MESSAGE_KEY = "message"; + private static final String RESPONSE_TIME_KEY = "responseTimeMs"; + private static final long MYSQL_TIMEOUT_SECONDS = 3; + private static final long REDIS_TIMEOUT_SECONDS = 3; + + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; + private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; + + private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; + private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; + private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; + private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; + + private final DataSource dataSource; + private final RedisTemplate redisTemplate; + private final ExecutorService executorService; + + private volatile long lastAdvancedCheckTime = 0; + private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; + private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); + private final AtomicBoolean advancedCheckInProgress = new AtomicBoolean(false); + + private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; + + public HealthService(DataSource dataSource, + @Autowired(required = false) RedisTemplate redisTemplate) { + this.dataSource = dataSource; + this.redisTemplate = redisTemplate; + this.executorService = Executors.newFixedThreadPool(6); + } + + @PreDestroy + public void shutdown() { + if (executorService != null && !executorService.isShutdown()) { + try { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + logger.warn("ExecutorService did not terminate gracefully"); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + logger.warn("ExecutorService shutdown interrupted", e); + } + } + } + + public Map checkHealth() { + Map response = new LinkedHashMap<>(); + response.put("timestamp", Instant.now().toString()); + + Map mysqlStatus = new ConcurrentHashMap<>(); + Map redisStatus = new ConcurrentHashMap<>(); + + if (!executorService.isShutdown()) { + performHealthChecks(mysqlStatus, redisStatus); + } + + ensurePopulated(mysqlStatus, "MySQL"); + ensurePopulated(redisStatus, "Redis"); + + Map> components = new LinkedHashMap<>(); + components.put("mysql", mysqlStatus); + components.put("redis", redisStatus); + + response.put("components", components); + response.put(STATUS_KEY, computeOverallStatus(components)); + + return response; + } + + private void performHealthChecks(Map mysqlStatus, Map redisStatus) { + Future mysqlFuture = null; + Future redisFuture = null; + try { + mysqlFuture = executorService.submit( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); + redisFuture = executorService.submit( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); + + awaitHealthChecks(mysqlFuture, redisFuture); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", getMaxTimeout()); + cancelFutures(mysqlFuture, redisFuture); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + cancelFutures(mysqlFuture, redisFuture); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + cancelFutures(mysqlFuture, redisFuture); + } + } + + private void awaitHealthChecks(Future mysqlFuture, Future redisFuture) throws TimeoutException, InterruptedException, ExecutionException { + long maxTimeout = getMaxTimeout(); + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } + + private long getMaxTimeout() { + return Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + } + + private void cancelFutures(Future mysqlFuture, Future redisFuture) { + if (mysqlFuture != null) mysqlFuture.cancel(true); + if (redisFuture != null) redisFuture.cancel(true); + } + + private void ensurePopulated(Map status, String componentName) { + if (!status.containsKey(STATUS_KEY)) { + status.put(STATUS_KEY, STATUS_DOWN); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, componentName + " health check did not complete in time"); + } + } + + private HealthCheckResult checkMySQLHealthSync() { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) { + return new HealthCheckResult(false, "No result from health check query", false); + } + } + } catch (Exception e) { + logger.warn("MySQL health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "MySQL connection failed", false); + } + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); + return new HealthCheckResult(true, null, isDegraded); + } + + private HealthCheckResult checkRedisHealthSync() { + if (redisTemplate == null) { + return new HealthCheckResult(true, "Redis not configured — skipped", false); + } + + try { + String pong = redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); + + if ("PONG".equals(pong)) { + return new HealthCheckResult(true, null, false); + } + + return new HealthCheckResult(false, "Redis PING failed", false); + + } catch (Exception e) { + logger.warn("Redis health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "Redis connection failed", false); + } + } + + private Map performHealthCheck(String componentName, + Map status, + Supplier checker) { + long startTime = System.currentTimeMillis(); + + try { + HealthCheckResult result = checker.get(); + long responseTime = System.currentTimeMillis() - startTime; + + // Determine status: DOWN (unhealthy), DEGRADED (healthy but with issues), or UP + String componentStatus; + if (!result.isHealthy) { + componentStatus = STATUS_DOWN; + } else if (result.isDegraded) { + componentStatus = STATUS_DEGRADED; + } else { + componentStatus = STATUS_UP; + } + status.put(STATUS_KEY, componentStatus); + + // Set response time + status.put(RESPONSE_TIME_KEY, responseTime); + + // Determine severity based on health, response time, and degradation flags + String severity = determineSeverity(result.isHealthy, responseTime, result.isDegraded); + status.put(SEVERITY_KEY, severity); + + // Include message or error based on health status + if (result.error != null) { + // Use MESSAGE_KEY for informational messages when healthy + // Use ERROR_KEY for actual error messages when unhealthy + String fieldKey = result.isHealthy ? MESSAGE_KEY : ERROR_KEY; + status.put(fieldKey, result.error); + } + + return status; + + } catch (Exception e) { + long responseTime = System.currentTimeMillis() - startTime; + logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); + + status.put(STATUS_KEY, STATUS_DOWN); + status.put(RESPONSE_TIME_KEY, responseTime); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, "Health check failed with an unexpected error"); + + return status; + } + } + + private String determineSeverity(boolean isHealthy, long responseTimeMs, boolean isDegraded) { + if (!isHealthy) { + return SEVERITY_CRITICAL; + } + + if (isDegraded) { + return SEVERITY_WARNING; + } + + if (responseTimeMs > RESPONSE_TIME_THRESHOLD_MS) { + return SEVERITY_WARNING; + } + + return SEVERITY_OK; + } + + private String computeOverallStatus(Map> components) { + boolean hasCritical = false; + boolean hasDegraded = false; + + for (Map componentStatus : components.values()) { + String status = (String) componentStatus.get(STATUS_KEY); + String severity = (String) componentStatus.get(SEVERITY_KEY); + + if (STATUS_DOWN.equals(status) || SEVERITY_CRITICAL.equals(severity)) { + hasCritical = true; + } + + if (STATUS_DEGRADED.equals(status)) { + hasDegraded = true; + } + + if (SEVERITY_WARNING.equals(severity)) { + hasDegraded = true; + } + } + + if (hasCritical) { + return STATUS_DOWN; + } + + if (hasDegraded) { + return STATUS_DEGRADED; + } + + return STATUS_UP; + } + + private boolean performAdvancedMySQLChecksWithThrottle() { + if (!ADVANCED_HEALTH_CHECKS_ENABLED) { + return false; + } + + long currentTime = System.currentTimeMillis(); + + advancedCheckLock.readLock().lock(); + try { + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + return cachedAdvancedCheckResult.isDegraded; + } + } finally { + advancedCheckLock.readLock().unlock(); + } + + // Only one thread may submit; others fall back to the (stale) cache + if (!advancedCheckInProgress.compareAndSet(false, true)) { + advancedCheckLock.readLock().lock(); + try { + return cachedAdvancedCheckResult != null && cachedAdvancedCheckResult.isDegraded; + } finally { + advancedCheckLock.readLock().unlock(); + } + } + + try { + // Perform DB I/O outside the write lock to avoid lock contention + AdvancedCheckResult result; + try (Connection connection = dataSource.getConnection()) { + result = performAdvancedMySQLChecks(connection); + } catch (Exception e) { + if (e.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + logger.debug("Failed to get connection for advanced checks: {}", e.getMessage()); + result = new AdvancedCheckResult(false); + } + + // Re-acquire write lock only to update the cache atomically + advancedCheckLock.writeLock().lock(); + try { + lastAdvancedCheckTime = currentTime; + cachedAdvancedCheckResult = result; + return result.isDegraded; + } finally { + advancedCheckLock.writeLock().unlock(); + } + } finally { + advancedCheckInProgress.set(false); + } + } + + private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(false); + } + } + + private boolean hasLockWaits(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE (state = 'Waiting for table metadata lock' " + + " OR state = 'Waiting for row lock' " + + " OR state = 'Waiting for lock') " + + "AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int lockCount = rs.getInt(1); + return lockCount > 0; + } + } + } catch (Exception e) { + logger.debug("Could not check for lock waits"); + } + return false; + } + + private boolean hasSlowQueries(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE command != 'Sleep' AND time > ? AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { + stmt.setQueryTimeout(2); + stmt.setInt(1, 10); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int slowQueryCount = rs.getInt(1); + return slowQueryCount > 3; + } + } + } catch (Exception e) { + logger.debug("Could not check for slow queries"); + } + return false; + } + + private boolean hasConnectionPoolExhaustion() { + // Use HikariCP metrics if available + if (dataSource instanceof HikariDataSource hikariDataSource) { + try { + HikariPoolMXBean poolMXBean = hikariDataSource.getHikariPoolMXBean(); + + if (poolMXBean != null) { + int activeConnections = poolMXBean.getActiveConnections(); + int maxPoolSize = hikariDataSource.getMaximumPoolSize(); + + // Alert if > 80% of pool is exhausted + int threshold = (int) (maxPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + logger.debug("Could not retrieve HikariCP pool metrics"); + } + } + + // Fallback: try to get pool metrics via JMX if HikariCP is not directly available + return checkPoolMetricsViaJMX(); + } + + private boolean checkPoolMetricsViaJMX() { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + ObjectName objectName = new ObjectName("com.zaxxer.hikari:type=Pool (*)"); + var mBeans = mBeanServer.queryMBeans(objectName, null); + + for (var mBean : mBeans) { + if (evaluatePoolMetrics(mBeanServer, mBean.getObjectName())) { + return true; + } + } + } catch (Exception e) { + logger.debug("Could not access HikariCP pool metrics via JMX"); + } + + // No pool metrics available - disable this check + logger.debug("Pool exhaustion check disabled: HikariCP metrics unavailable"); + return false; + } + + private boolean evaluatePoolMetrics(MBeanServer mBeanServer, ObjectName objectName) { + try { + Integer activeConnections = (Integer) mBeanServer.getAttribute(objectName, "ActiveConnections"); + Integer maximumPoolSize = (Integer) mBeanServer.getAttribute(objectName, "MaximumPoolSize"); + + if (activeConnections != null && maximumPoolSize != null) { + int threshold = (int) (maximumPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + // Continue to next MBean + } + return false; + } + + private static class AdvancedCheckResult { + final boolean isDegraded; + + AdvancedCheckResult(boolean isDegraded) { + this.isDegraded = isDegraded; + } + } + + private static class HealthCheckResult { + final boolean isHealthy; + final String error; + final boolean isDegraded; + + HealthCheckResult(boolean isHealthy, String error, boolean isDegraded) { + this.isHealthy = isHealthy; + this.error = error; + this.isDegraded = isDegraded; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java index 5d6c05b3..23dd21a8 100644 --- a/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java @@ -78,7 +78,8 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo if (path.equals(contextPath + "/user/userAuthenticate") || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") || path.startsWith(contextPath + "/swagger-ui") || path.startsWith(contextPath + "/v3/api-docs") - || path.startsWith(contextPath + "/user/refreshToken") || path.startsWith(contextPath + "/public")) { + || path.startsWith(contextPath + "/user/refreshToken") || path.startsWith(contextPath + "/public") + || path.equals(contextPath + "/version") || path.equals(contextPath + "/health")) { logger.info("Skipping filter for path: " + path); filterChain.doFilter(servletRequest, servletResponse); return; From be13009ede285b134789543ffa41aa290cbb00ab Mon Sep 17 00:00:00 2001 From: Vanitha S <116701245+vanitha1822@users.noreply.github.com> Date: Thu, 19 Mar 2026 17:05:52 +0530 Subject: [PATCH 5/6] Merge Release 3.6.1 to main (#137) * Update version in pom.xml to 3.4.0 * story: amm-1668 task - 1754 * story: amm-1668 task - 1754 dto updated (#92) * story: amm-1668 task - 1754 dto updated (#93) * story: amm-1668 task - 1754 dto updated * story: amm-1668 task - 1754 * fix: amm-1879 doctor signature was not coming for ncdcare * fix: aam-1896 prescribed quantity was not coming in the casesheet * Update pom.xml 3.4.0 to 3.4.1 * fix: amm-1919 fix for update doctor data for higher refferal data * fix: signature enhancement for casesheet * fix: signature enhancement for casesheet * fix: signature enhancement for casesheet * fix: signature enhancement for casesheet for ncdscreening * fix: updated beneficiaryflowststusrepo file * fix: wasa-IDOR Vulnerability * fix: coderabbit comments * fix: amm-1927 res headers based on origin via allowed cors * fix: amm-1927 coderabbit comments resolved * localhost regex added * Update regex pattern for localhost in interceptor * fix: remove userid from request * Role Based Broken Access Control Implementation : WASA (#104) * fix: add @preAuthorize to RBAC * fix: wasa RBAC implementation * fix: remove duplicate dependency * fix: coderabbit comments * fix: update role * fix: enable the request matcher * fix:1896 added space for single dose after food string due * fix:1896 added single dose after and before food confition for calculated qntity * fix: role based on both jwt and auth token * add role in register api * Downgrade from 3.6.2 to 3.6.1 (#132) * fix: amm-2063 added beneficiarytype but not reflecting in the DB level * Bump version from 3.6.0 to 3.6.2 * fix: amm-2063 updated the updateBeneficiary flow * Downgrade version from 3.6.2 to 3.6.1 --------- Co-authored-by: SnehaRH Co-authored-by: SnehaRH <77656297+snehar-nd@users.noreply.github.com> * Cherry-pick health and version API enhancements to release-3.6.1 (#136) * feat(healt,version): add health and version endpoints * fix(health): improve Redis health semantics when not configured * fix(health): scope PROCESSLIST lock-wait check to application DB user * fix(health): Removed the unused import * fix(health): avoid blocking DB I/O under write lock and restore interrupt flag * fix: add missin close brace * fix(health): cancel in-flight futures on generic failure * fix(health): fail-open on advanced MySQL check exceptions to avoid false degraded state --------- Co-authored-by: Amoghavarsh <93114621+5Amogh@users.noreply.github.com> Co-authored-by: 5Amogh Co-authored-by: SnehaRH Co-authored-by: SnehaRH <77656297+snehar-nd@users.noreply.github.com> Co-authored-by: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Co-authored-by: Saurav Mishra Co-authored-by: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> --- pom.xml | 7 +- src/main/environment/common_ci.properties | 4 +- src/main/environment/common_docker.properties | 4 +- .../environment/common_example.properties | 4 +- .../anc/AntenatalCareController.java | 15 ++ .../CancerScreeningController.java | 17 ++ .../common/main/WorklistController.java | 109 +++++++++--- .../common/master/CommonMasterController.java | 2 + .../controller/covid19/CovidController.java | 10 ++ .../dataSyncActivity/StartSyncActivity.java | 3 + .../MMUDataSyncVanToServer.java | 2 + .../FoetalMonitorController.java | 1 + .../generalOPD/GeneralOPDController.java | 15 +- .../LabtechnicianController.java | 2 + .../location/LocationController.java | 2 + .../login/IemrMmuLoginController.java | 60 +++++-- .../controller/ncdCare/NCDCareController.java | 11 +- .../ncdscreening/NCDScreeningController.java | 16 +- .../vitals/AnthropometryVitalsController.java | 2 + .../PatientAppCommonMasterController.java | 11 ++ .../pnc/PostnatalCareController.java | 16 +- .../quickconsult/QuickConsultController.java | 7 + .../registrar/main/RegistrarController.java | 17 ++ .../report/CRMReportController.java | 3 + .../controller/snomedct/SnomedController.java | 2 + .../TeleConsultationController.java | 30 +++- .../VideoConsultationController.java | 26 ++- .../benFlowStatus/BeneficiaryFlowStatus.java | 20 ++- .../tm/data/ncdcare/NCDCareDiagnosis.java | 7 +- .../BeneficiaryFlowStatusRepo.java | 39 ++-- .../com/iemr/tm/repo/login/UserLoginRepo.java | 5 + .../nurse/ncdcare/NCDCareDiagnosisRepo.java | 2 +- .../iemr/tm/service/anc/ANCServiceImpl.java | 14 +- .../CommonBenStatusFlowServiceImpl.java | 21 +-- .../cancerScreening/CSServiceImpl.java | 10 +- .../transaction/CommonDoctorServiceImpl.java | 23 +-- .../transaction/CommonNurseServiceImpl.java | 21 ++- .../service/covid19/Covid19ServiceImpl.java | 15 +- .../generalOPD/GeneralOPDServiceImpl.java | 14 +- .../service/ncdCare/NCDCareServiceImpl.java | 14 +- .../NCDSCreeningDoctorServiceImpl.java | 7 +- .../ncdscreening/NCDScreeningServiceImpl.java | 7 +- .../iemr/tm/service/pnc/PNCServiceImpl.java | 14 +- .../QuickConsultationServiceImpl.java | 13 +- .../java/com/iemr/tm/utils/CookieUtil.java | 9 +- .../iemr/tm/utils/JwtAuthenticationUtil.java | 15 ++ .../tm/utils/JwtUserIdValidationFilter.java | 44 +++-- src/main/java/com/iemr/tm/utils/JwtUtil.java | 11 +- .../exception/CustomAccessDeniedHandler.java | 28 +++ .../CustomAuthenticationEntryPoint.java | 23 +++ .../tm/utils/http/HTTPRequestInterceptor.java | 39 +++- .../mapper/RoleAuthenticationFilter.java | 166 ++++++++++++++++++ .../iemr/tm/utils/mapper/SecurityConfig.java | 53 ++++++ .../com/iemr/tm/utils/redis/RedisStorage.java | 27 +++ 54 files changed, 909 insertions(+), 150 deletions(-) create mode 100644 src/main/java/com/iemr/tm/utils/exception/CustomAccessDeniedHandler.java create mode 100644 src/main/java/com/iemr/tm/utils/exception/CustomAuthenticationEntryPoint.java create mode 100644 src/main/java/com/iemr/tm/utils/mapper/RoleAuthenticationFilter.java create mode 100644 src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java diff --git a/pom.xml b/pom.xml index 40e64be4..ad1583c2 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.tm tm-api - 3.4.0 + 3.6.1 war TM-API @@ -56,6 +56,10 @@ org.springframework.boot spring-boot-starter-aop + + org.springframework.boot + spring-boot-starter-security + org.springframework.boot spring-boot-starter @@ -71,6 +75,7 @@ logback-ecs-encoder 1.3.2 + org.springdoc diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 21b482a0..4d69b134 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -10,7 +10,7 @@ carestreamOrderCreateURL=@env.COMMON_API@carestream/createOrder ## Identity - Common URLs # Registration -registrationUrl =@env.COMMON_API@beneficiary/create +registrationUrl =@env.COMMON_API@beneficiary/createBeneficiary registrarQuickSearchByIdUrl =@env.COMMON_API@beneficiary/searchUserByID @@ -19,7 +19,7 @@ registrarQuickSearchByPhoneNoUrl =@env.COMMON_API@beneficiary/searchUserByPhone getBenImageFromIdentity =@env.IDENTITY_API@id/benImageByBenRegID ##beneficiary edit -beneficiaryEditUrl =@env.COMMON_API@beneficiary/update +beneficiaryEditUrl =@env.COMMON_API@beneficiary/updateBenefciaryDetails ## Advance Search registrarAdvanceSearchUrl =@env.COMMON_API@beneficiary/searchBeneficiary diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 6316cb8f..72409768 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -10,7 +10,7 @@ carestreamOrderCreateURL=${COMMON_API}/carestream/createOrder ## Identity - Common URLs # Registration -registrationUrl=${COMMON_API}/beneficiary/create +registrationUrl=${COMMON_API}/beneficiary/createBeneficiary registrarQuickSearchByIdUrl=${COMMON_API}/beneficiary/searchUserByID @@ -19,7 +19,7 @@ registrarQuickSearchByPhoneNoUrl=${COMMON_API}/beneficiary/searchUserByPhone getBenImageFromIdentity=${IDENTITY_API}/id/benImageByBenRegID ## beneficiary edit -beneficiaryEditUrl=${COMMON_API}/beneficiary/update +beneficiaryEditUrl=${COMMON_API}/beneficiary/updateBenefciaryDetails ## Advance Search registrarAdvanceSearchUrl=${COMMON_API}/beneficiary/searchBeneficiary diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 489d2639..c90d479a 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -11,7 +11,7 @@ carestreamOrderCreateURL =http://localhost:8083/carestream/createOrder ## Identity - Common URLs # Registration -registrationUrl =http://localhost:8083/beneficiary/create +registrationUrl =http://localhost:8083/beneficiary/createBeneficiary registrarQuickSearchByIdUrl =http://localhost:8083/beneficiary/searchUserByID @@ -20,7 +20,7 @@ registrarQuickSearchByPhoneNoUrl =http://localhost:8083/beneficiary/searchUserBy getBenImageFromIdentity =http://localhost:8094/id/benImageByBenRegID ##beneficiary edit -beneficiaryEditUrl =http://localhost:8083/beneficiary/update +beneficiaryEditUrl =http://localhost:8083/beneficiary/updateBenefciaryDetails ## Advance Search registrarAdvanceSearchUrl =http://localhost:8083/beneficiary/searchBeneficiary diff --git a/src/main/java/com/iemr/tm/controller/anc/AntenatalCareController.java b/src/main/java/com/iemr/tm/controller/anc/AntenatalCareController.java index aef00a49..2d048061 100644 --- a/src/main/java/com/iemr/tm/controller/anc/AntenatalCareController.java +++ b/src/main/java/com/iemr/tm/controller/anc/AntenatalCareController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -66,6 +67,7 @@ public void setAncServiceImpl(ANCServiceImpl ancServiceImpl) { */ @Operation(summary = "Save ANC nurse data") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE') ") public String saveBenANCNurseData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -98,6 +100,7 @@ public String saveBenANCNurseData(@RequestBody String requestObj, @Operation(summary = "Save ANC doctor data") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveBenANCDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -132,6 +135,7 @@ public String saveBenANCDoctorData(@RequestBody String requestObj, @Operation(summary = "Get ANC beneficiary visit details from nurse") @PostMapping(value = { "/getBenVisitDetailsFrmNurseANC" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVisitDetailsFrmNurseANC( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -158,6 +162,7 @@ public String getBenVisitDetailsFrmNurseANC( @Operation(summary = "Get ANC beneficiary details from nurse") @PostMapping(value = { "/getBenANCDetailsFrmNurseANC" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenANCDetailsFrmNurseANC( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -184,6 +189,7 @@ public String getBenANCDetailsFrmNurseANC( @Operation(summary = "Get ANC beneficiary history from nurse") @PostMapping(value = { "/getBenANCHistoryDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenANCHistoryDetails( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -209,6 +215,7 @@ public String getBenANCHistoryDetails( @Operation(summary = "Get ANC beneficiary vitals from nurse") @PostMapping(value = { "/getBenANCVitalDetailsFrmNurseANC" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenANCVitalDetailsFrmNurseANC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -235,6 +242,7 @@ public String getBenANCVitalDetailsFrmNurseANC( @Operation(summary = "Get ANC beneficiary examination details from nurse") @PostMapping(value = { "/getBenExaminationDetailsANC" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenExaminationDetailsANC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -260,6 +268,7 @@ public String getBenExaminationDetailsANC( @Operation(summary = "Get ANC beneficiary case record") @PostMapping(value = { "/getBenCaseRecordFromDoctorANC" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") @Transactional(rollbackFor = Exception.class) public String getBenCaseRecordFromDoctorANC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { @@ -288,6 +297,7 @@ public String getBenCaseRecordFromDoctorANC( @Operation(summary = "Check high risk pregnancy status for ANC beneficiary") @PostMapping(value = { "/getHRPStatus" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getHRPStatus( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -316,6 +326,7 @@ public String getHRPStatus( @Operation(summary = "Update ANC beneficiary data") @PostMapping(value = { "/update/ANCScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateANCCareNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -344,6 +355,7 @@ public String updateANCCareNurse(@RequestBody String requestObj) { @Operation(summary = "Update ANC beneficiary history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateANCHistoryNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -372,6 +384,7 @@ public String updateANCHistoryNurse(@RequestBody String requestObj) { @Operation(summary = "Update ANC beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateANCVitalNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -400,6 +413,7 @@ public String updateANCVitalNurse(@RequestBody String requestObj) { @Operation(summary = "Update ANC examination data") @PostMapping(value = { "/update/examinationScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateANCExaminationNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -428,6 +442,7 @@ public String updateANCExaminationNurse(@RequestBody String requestObj) { @Operation(summary = "Update ANC doctor data") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateANCDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/cancerscreening/CancerScreeningController.java b/src/main/java/com/iemr/tm/controller/cancerscreening/CancerScreeningController.java index 09e217f4..b74f7427 100644 --- a/src/main/java/com/iemr/tm/controller/cancerscreening/CancerScreeningController.java +++ b/src/main/java/com/iemr/tm/controller/cancerscreening/CancerScreeningController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -70,6 +71,7 @@ public void setCancerScreeningServiceImpl(CSServiceImpl cSServiceImpl) { */ @Operation(summary = "Save cancer screening data collected by nurse") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE') ") public String saveBenCancerScreeningNurseData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -106,6 +108,7 @@ public String saveBenCancerScreeningNurseData(@RequestBody String requestObj, */ @Operation(summary = "Update cancer screening data by the doctor") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveBenCancerScreeningDoctorData(@RequestBody String requestObj, @RequestHeader String Authorization) { OutputResponse response = new OutputResponse(); @@ -137,6 +140,7 @@ public String saveBenCancerScreeningDoctorData(@RequestBody String requestObj, @Operation(summary = "Get beneficiary visit details") @PostMapping(value = { "/getBenDataFrmNurseToDocVisitDetailsScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenDataFrmNurseScrnToDocScrnVisitDetails( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -166,6 +170,7 @@ public String getBenDataFrmNurseScrnToDocScrnVisitDetails( */ @Operation(summary = "Get beneficiary cancer history") @PostMapping(value = { "/getBenDataFrmNurseToDocHistoryScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenDataFrmNurseScrnToDocScrnHistory( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -195,6 +200,7 @@ public String getBenDataFrmNurseScrnToDocScrnHistory( */ @Operation(summary = "Get beneficiary vitals") @PostMapping(value = { "/getBenDataFrmNurseToDocVitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenDataFrmNurseScrnToDocScrnVital( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -224,6 +230,7 @@ public String getBenDataFrmNurseScrnToDocScrnVital( */ @Operation(summary = "Get beneficiary examination details") @PostMapping(value = { "/getBenDataFrmNurseToDocExaminationScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenDataFrmNurseScrnToDocScrnExamination( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -253,6 +260,7 @@ public String getBenDataFrmNurseScrnToDocScrnExamination( */ @Operation(summary = "Get beneficiary family history") @PostMapping(value = { "/getBenCancerFamilyHistory" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCancerFamilyHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -284,6 +292,7 @@ public String getBenCancerFamilyHistory( */ @Operation(summary = "Get beneficiary personal history") @PostMapping(value = { "/getBenCancerPersonalHistory" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCancerPersonalHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -315,6 +324,7 @@ public String getBenCancerPersonalHistory( */ @Operation(summary = "Get beneficiary personal diet history") @PostMapping(value = { "/getBenCancerPersonalDietHistory" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCancerPersonalDietHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -346,6 +356,7 @@ public String getBenCancerPersonalDietHistory( */ @Operation(summary = "Get beneficiary obstetric history") @PostMapping(value = { "/getBenCancerObstetricHistory" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCancerObstetricHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -376,6 +387,7 @@ public String getBenCancerObstetricHistory( */ @Operation(summary = "Get beneficiary case record and referral details") @PostMapping(value = { "/getBenCaseRecordFromDoctorCS" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") @Transactional(rollbackFor = Exception.class) public String getBenCaseRecordFromDoctorCS( @Param(value = "{\"benRegID\":\"Long\", \"visitCode\":\"Long\"}") @RequestBody String comingRequest) { @@ -402,6 +414,7 @@ public String getBenCaseRecordFromDoctorCS( @Operation(summary = "Update cancer screening history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateCSHistoryNurse( @Param(value = "{\"historyDetails\": {\"familyHistory\":{\"diseases\": [{\"beneficiaryRegID\":\"Long\", \"benVisitID\":\"Long\", " + "\"providerServiceMapID\":\"Integer\", \"cancerDiseaseType\":\"String\", \"otherDiseaseType\":\"String\", \"familyMemberList\":\"List\", " @@ -453,6 +466,7 @@ public String updateCSHistoryNurse( */ @Operation(summary = "Update beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String upodateBenVitalDetail( @Param(value = "{\"ID\": \"Long\", \"beneficiaryRegID\":\"Long\",\"benVisitID\":\"Long\"," + "\"weight_Kg\":\"Double\", \"height_cm\":\"Double\", \"waistCircumference_cm\":\"Double\", \"bloodGlucose_Fasting\":\"Short\"," @@ -491,6 +505,7 @@ public String upodateBenVitalDetail( */ @Operation(summary = "Update beneficiary examination details") @PostMapping(value = { "/update/examinationScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String upodateBenExaminationDetail(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -526,6 +541,7 @@ public String upodateBenExaminationDetail(@RequestBody String requestObj) { */ @Operation(summary = "Update cancer diagnosis details by oncologist") @PostMapping(value = { "/update/examinationScreen/diagnosis" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('ONCOLOGIST') ") public String updateCancerDiagnosisDetailsByOncologist( @Param(value = "{\"beneficiaryRegID\":\"Long\", \"benVisitID\":\"Long\", \"visitCode\":\"Long\", " + "\"provisionalDiagnosisOncologist\":\"String\", \"modifiedBy\":\"string\"}") @RequestBody String requestObj) { @@ -560,6 +576,7 @@ public String updateCancerDiagnosisDetailsByOncologist( */ @Operation(summary = "Update cancer screening data") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateCancerScreeningDoctorData(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/iemr/tm/controller/common/main/WorklistController.java b/src/main/java/com/iemr/tm/controller/common/main/WorklistController.java index 36217a88..ad2c84c7 100644 --- a/src/main/java/com/iemr/tm/controller/common/main/WorklistController.java +++ b/src/main/java/com/iemr/tm/controller/common/main/WorklistController.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -34,15 +35,16 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.iemr.tm.data.benFlowStatus.BeneficiaryFlowStatus; import com.iemr.tm.service.common.transaction.CommonDoctorServiceImpl; import com.iemr.tm.service.common.transaction.CommonNurseServiceImpl; import com.iemr.tm.service.common.transaction.CommonServiceImpl; +import com.iemr.tm.utils.JwtUtil; import com.iemr.tm.utils.mapper.InputMapper; import com.iemr.tm.utils.response.OutputResponse; +import org.springframework.security.core.Authentication; import io.lettuce.core.dynamic.annotation.Param; import io.swagger.v3.oas.annotations.Operation; @@ -57,6 +59,9 @@ public class WorklistController { private CommonServiceImpl commonServiceImpl; private InputMapper inputMapper = new InputMapper(); + @Autowired + private JwtUtil jwtUtil; + @Autowired public void setCommonServiceImpl(CommonServiceImpl commonServiceImpl) { this.commonServiceImpl = commonServiceImpl; @@ -75,6 +80,7 @@ public void setCommonNurseServiceImpl(CommonNurseServiceImpl commonNurseServiceI // doc worklist new @Operation(summary = "Get doctor worklist") @GetMapping(value = { "/getDocWorklistNew/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('DOCTOR') ") public String getDocWorkListNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("serviceID") Integer serviceID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -99,6 +105,7 @@ public String getDocWorkListNew(@PathVariable("providerServiceMapID") Integer pr // doc worklist new (TM future scheduled beneficiary) @Operation(summary = "Get doctor future worklist scheduled for telemedicine") @GetMapping(value = { "/getDocWorkListNewFutureScheduledForTM/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('TC_SPECIALIST') || hasRole('TCSPECIALIST') ") public String getDocWorkListNewFutureScheduledForTM( @PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("serviceID") Integer serviceID, @PathVariable("vanID") Integer vanID) { @@ -125,6 +132,7 @@ public String getDocWorkListNewFutureScheduledForTM( // nurse worklist new @Operation(summary = "Get nurse worklist") @GetMapping(value = { "/getNurseWorklistNew/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('NURSE') ") public String getNurseWorkListNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -144,6 +152,7 @@ public String getNurseWorkListNew(@PathVariable("providerServiceMapID") Integer // nurse worklist TC schedule (current-date) new @Operation(summary = "Get worklist for teleconsultation for the current date") @GetMapping(value = { "/getNurseWorkListTcCurrentDate/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('NURSE') || hasRole('TC_SPECIALIST') || hasRole('TCSPECIALIST') ") public String getNurseWorkListTcCurrentDateNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -164,6 +173,7 @@ public String getNurseWorkListTcCurrentDateNew(@PathVariable("providerServiceMap // nurse worklist TC schedule (future-date) new @Operation(summary = "Get worklist for teleconsultation for the future date") @GetMapping(value = { "/getNurseWorkListTcFutureDate/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('NURSE') || hasRole('TC_SPECIALIST') || hasRole('TCSPECIALIST') ") public String getNurseWorkListTcFutureDateNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -183,6 +193,7 @@ public String getNurseWorkListTcFutureDateNew(@PathVariable("providerServiceMapI @Operation(summary = "Get previous significant findings") @PostMapping(value = { "/getDoctorPreviousSignificantFindings" }) + @PreAuthorize("hasRole('DOCTOR') ") public String getDoctorPreviousSignificantFindings( @Param(value = "{\"beneficiaryRegID\": \"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -209,6 +220,7 @@ public String getDoctorPreviousSignificantFindings( // Get Lab technician worklist new @Operation(summary = "Get lab technician worklist") @GetMapping(value = { "/getLabWorklistNew/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('LAB_TECHNICIAN') || hasRole('LABTECHNICIAN') ") public String getLabWorkListNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -229,6 +241,7 @@ public String getLabWorkListNew(@PathVariable("providerServiceMapID") Integer pr // Get radiologist worklist new @Operation(summary = "Get radiologist worklist") @GetMapping(value = { "/getRadiologist-worklist-New/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('RADIOLOGIST') ") public String getRadiologistWorklistNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -249,6 +262,7 @@ public String getRadiologistWorklistNew(@PathVariable("providerServiceMapID") In // Get oncologist worklist new @Operation(summary = "Get oncologist worklist") @GetMapping(value = { "/getOncologist-worklist-New/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('ONCOLOGIST') ") public String getOncologistWorklistNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -268,6 +282,7 @@ public String getOncologistWorklistNew(@PathVariable("providerServiceMapID") Int // Get pharma worklist new @Operation(summary = "Get pharmacist worklist") @GetMapping(value = { "/getPharma-worklist-New/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('PHARMACIST') ") public String getPharmaWorklistNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -287,7 +302,8 @@ public String getPharmaWorklistNew(@PathVariable("providerServiceMapID") Integer @Operation(summary = "Print case sheet of beneficiary") @PostMapping(value = { "/get/Case-sheet/printData" }) - public String getCasesheetPrintData(@RequestBody String comingReq, + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") + public String getCasesheetPrintData(@RequestBody String comingReq, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { @@ -307,6 +323,7 @@ public String getCasesheetPrintData(@RequestBody String comingReq, // Start of Fetch Previous Medical History... @Operation(summary = "Get beneficiary history") @PostMapping(value = { "/getBenPastHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenPastHistory(@Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -331,6 +348,7 @@ public String getBenPastHistory(@Param(value = "{\"benRegID\":\"Long\"}") @Reque @Operation(summary = "Get beneficiary tobacco consumption history") @PostMapping(value = { "/getBenTobaccoHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenTobaccoHistory(@Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -355,6 +373,7 @@ public String getBenTobaccoHistory(@Param(value = "{\"benRegID\":\"Long\"}") @Re @Operation(summary = "Get beneficiary alcohol consumption history") @PostMapping(value = { "/getBenAlcoholHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenAlcoholHistory(@Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -379,6 +398,7 @@ public String getBenAlcoholHistory(@Param(value = "{\"benRegID\":\"Long\"}") @Re @Operation(summary = "Get beneficiary allergy history") @PostMapping(value = { "/getBenAllergyHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenANCAllergyHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -404,6 +424,7 @@ public String getBenANCAllergyHistory( @Operation(summary = "Get beneficiary medication history") @PostMapping(value = { "/getBenMedicationHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenMedicationHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -429,6 +450,7 @@ public String getBenMedicationHistory( @Operation(summary = "Get beneficiary family history") @PostMapping(value = { "/getBenFamilyHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenFamilyHistory(@Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -453,6 +475,7 @@ public String getBenFamilyHistory(@Param(value = "{\"benRegID\":\"Long\"}") @Req @Operation(summary = "Get beneficiary menstrual history") @PostMapping(value = { "/getBenMenstrualHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenMenstrualHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -478,6 +501,7 @@ public String getBenMenstrualHistory( @Operation(summary = "Get beneficiary obstetric history") @PostMapping(value = { "/getBenPastObstetricHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenPastObstetricHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -503,6 +527,7 @@ public String getBenPastObstetricHistory( @Operation(summary = "Get beneficiary comorbidity condition details") @PostMapping(value = { "/getBenComorbidityConditionHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenANCComorbidityConditionHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -528,6 +553,7 @@ public String getBenANCComorbidityConditionHistory( @Operation(summary = "Get beneficiary optional vaccine details") @PostMapping(value = { "/getBenOptionalVaccineHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenOptionalVaccineHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -553,6 +579,7 @@ public String getBenOptionalVaccineHistory( @Operation(summary = "Get child beneficiary vaccine details") @PostMapping(value = { "/getBenChildVaccineHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenImmunizationHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -578,6 +605,7 @@ public String getBenImmunizationHistory( @Operation(summary = "Get beneficiary perinatal history") @PostMapping(value = { "/getBenPerinatalHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenPerinatalHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -603,6 +631,7 @@ public String getBenPerinatalHistory( @Operation(summary = "Get child beneficiary feeding history") @PostMapping(value = { "/getBenFeedingHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenFeedingHistory(@Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -627,6 +656,7 @@ public String getBenFeedingHistory(@Param(value = "{\"benRegID\":\"Long\"}") @Re @Operation(summary = "Get child beneficiary development history") @PostMapping(value = { "/getBenDevelopmentHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBenDevelopmentHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -658,6 +688,7 @@ public String getBenDevelopmentHistory( */ @Operation(summary = "Get beneficiary casesheet history") @PostMapping(value = { "/getBeneficiaryCaseSheetHistory" }) + @PreAuthorize("hasRole('DOCTOR') || hasRole('NURSE') ") public String getBeneficiaryCaseSheetHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -676,20 +707,28 @@ public String getBeneficiaryCaseSheetHistory( // TC specialist worklist new @Operation(summary = "Get teleconsultation specialist worklist") - @GetMapping(value = { "/getTCSpecialistWorklist/{providerServiceMapID}/{serviceID}/{userID}" }) + @GetMapping(value = { "/getTCSpecialistWorklist/{providerServiceMapID}/{serviceID}" }) public String getTCSpecialistWorkListNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, - @PathVariable("userID") Integer userID, @PathVariable("serviceID") Integer serviceID) { + @PathVariable("serviceID") Integer serviceID, Authentication authentication) { OutputResponse response = new OutputResponse(); - try { - if (providerServiceMapID != null && userID != null) { + try { + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } + + Integer userID = Integer.valueOf(authentication.getPrincipal().toString()); + + if (providerServiceMapID != null && userID != null ) { String s = commonDoctorServiceImpl.getTCSpecialistWorkListNewForTM(providerServiceMapID, userID, serviceID); if (s != null) response.setResponse(s); + } else if(userID == null ) { + response.setError(403, "Unauthorized access!"); } else { - logger.error("Invalid request, either ProviderServiceMapID or userID is invalid. PSMID = " - + providerServiceMapID + " SID = " + userID); - response.setError(5000, "Invalid request, either ProviderServiceMapID or userID is invalid"); + logger.error("Invalid request"); + response.setError(5000, "Invalid request"); } } catch (Exception e) { @@ -702,21 +741,26 @@ public String getTCSpecialistWorkListNew(@PathVariable("providerServiceMapID") I // TC specialist worklist new, patient App, 14-08-2020 @Operation(summary = "Get teleconsultation specialist worklist for patient app") @GetMapping(value = { - "/getTCSpecialistWorklistPatientApp/{providerServiceMapID}/{serviceID}/{userID}/{vanID}" }) + "/getTCSpecialistWorklistPatientApp/{providerServiceMapID}/{serviceID}/{vanID}" }) public String getTCSpecialistWorkListNewPatientApp( - @PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("userID") Integer userID, - @PathVariable("serviceID") Integer serviceID, @PathVariable("vanID") Integer vanID) { + @PathVariable("providerServiceMapID") Integer providerServiceMapID, + @PathVariable("serviceID") Integer serviceID, @PathVariable("vanID") Integer vanID, Authentication authentication) { OutputResponse response = new OutputResponse(); try { + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } + + Integer userID = Integer.valueOf(authentication.getPrincipal().toString()); if (providerServiceMapID != null && userID != null) { String s = commonDoctorServiceImpl.getTCSpecialistWorkListNewForTMPatientApp(providerServiceMapID, userID, serviceID, vanID); if (s != null) response.setResponse(s); - } else { - logger.error("Invalid request, either ProviderServiceMapID or userID is invalid. PSMID = " - + providerServiceMapID + " SID = " + userID); - response.setError(5000, "Invalid request, either ProviderServiceMapID or userID is invalid"); + } else { + logger.error("Invalid request"); + response.setError(5000, "Invalid request"); } } catch (Exception e) { @@ -729,21 +773,27 @@ public String getTCSpecialistWorkListNewPatientApp( // TC specialist worklist new future scheduled @Operation(summary = "Get teleconsultation specialist future scheduled") @GetMapping(value = { - "/getTCSpecialistWorklistFutureScheduled/{providerServiceMapID}/{serviceID}/{userID}" }) + "/getTCSpecialistWorklistFutureScheduled/{providerServiceMapID}/{serviceID}" }) public String getTCSpecialistWorklistFutureScheduled( - @PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("userID") Integer userID, - @PathVariable("serviceID") Integer serviceID) { + @PathVariable("providerServiceMapID") Integer providerServiceMapID, + @PathVariable("serviceID") Integer serviceID, Authentication authentication) { OutputResponse response = new OutputResponse(); try { - if (providerServiceMapID != null && userID != null) { + + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } + + Integer userID = Integer.valueOf(authentication.getPrincipal().toString()); + if (providerServiceMapID != null && userID != null ) { String s = commonDoctorServiceImpl.getTCSpecialistWorkListNewFutureScheduledForTM(providerServiceMapID, userID, serviceID); if (s != null) response.setResponse(s); - } else { - logger.error("Invalid request, either ProviderServiceMapID or userID is invalid. PSMID = " - + providerServiceMapID + " UserID = " + userID); - response.setError(5000, "Invalid request, either ProviderServiceMapID or userID is invalid"); + } else { + logger.error("Invalid request"); + response.setError(5000, "Invalid request"); } } catch (Exception e) { @@ -756,6 +806,7 @@ public String getTCSpecialistWorklistFutureScheduled( // openkm file download @Operation(summary = "Add file as string to openKM") @PostMapping(value = "/getKMFile", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON, headers = "Authorization") + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getKMFile(@Param(value = "{}") @RequestBody String request, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -774,6 +825,7 @@ public String getKMFile(@Param(value = "{}") @RequestBody String request, @Operation(summary = "Get beneficiary physical history") @PostMapping(value = { "/getBenPhysicalHistory" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenPhysicalHistory( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -799,6 +851,7 @@ public String getBenPhysicalHistory( @Operation(summary = "Get beneficiary symptomatic questionnaire answer details") @PostMapping(value = { "/getBenSymptomaticQuestionnaireDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenSymptomaticQuestionnaireDetails( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -824,6 +877,7 @@ public String getBenSymptomaticQuestionnaireDetails( @Operation(summary = "Get beneficiary previous diabetes history") @PostMapping(value = { "/getBenPreviousDiabetesHistoryDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenPreviousDiabetesHistoryDetails( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -850,6 +904,7 @@ public String getBenPreviousDiabetesHistoryDetails( // nurse worklist coming from MMU application @Operation(summary = "Get mmu nurse worklist") @GetMapping(value = { "/getMmuNurseWorklistNew/{providerServiceMapID}/{serviceID}/{vanID}" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getMmuNurseWorklistNew(@PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("vanID") Integer vanID) { OutputResponse response = new OutputResponse(); @@ -868,6 +923,7 @@ public String getMmuNurseWorklistNew(@PathVariable("providerServiceMapID") Integ @Operation(summary = "Get beneficiary previous referral history") @PostMapping(value = { "/getBenPreviousReferralHistoryDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenPreviousReferralHistoryDetails( @Param(value = "{\"benRegID\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -897,6 +953,7 @@ public String getBenPreviousReferralHistoryDetails( */ @Operation(summary = "Get provider specific data") @PostMapping(value = { "/getProviderSpecificData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getProviderSpecificData( @Param(value = "{\"benvisitID\":\"Long\",\"benvisitCode\":\"Long\",\"fetchMMUDataFor\":\"String\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -918,6 +975,7 @@ public String getProviderSpecificData( */ @Operation(summary = "Calculate beneficiary BMI status") @PostMapping(value = { "/calculateBMIStatus" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String calculateBMIStatus( @Param(value = "{\"bmi\":\"double\",\"yearMonth\":\"String\",\"gender\":\"String\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -935,6 +993,7 @@ public String calculateBMIStatus( @Operation(summary = "Update beneficiary status flag") @PostMapping(value = { "/update/benDetailsAndSubmitToNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String saveBeneficiaryVisitDetail( @Param(value = "{\"beneficiaryRegID\": \"Long\"}") @RequestBody String comingRequest) { @@ -969,6 +1028,7 @@ public String saveBeneficiaryVisitDetail( @Operation(summary = "Extend redis session for 30 mins") @PostMapping(value = { "/extend/redisSession" }) + @PreAuthorize("hasRole('NURSE') || hasRole('PHARMACIST') || hasRole('LABTECHNICIAN') || hasRole('REGISTRAR') || hasRole('DATASYNC') || hasRole('DATA_SYNC') || hasRole('DOCTOR') || hasRole('LAB_TECHNICIAN') || hasRole('TC_SPECIALIST') || hasRole('ONCOLOGIST') || hasRole('RADIOLOGIST')") public String extendRedisSession() { OutputResponse response = new OutputResponse(); try { @@ -982,6 +1042,7 @@ public String extendRedisSession() { @Operation(summary = "Soft delete prescribed medicine") @PostMapping(value = { "/doctor/delete/prescribedMedicine" }) + @PreAuthorize("hasRole('DOCTOR') ") public String deletePrescribedMedicine(@RequestBody String requestOBJ) { OutputResponse response = new OutputResponse(); try { diff --git a/src/main/java/com/iemr/tm/controller/common/master/CommonMasterController.java b/src/main/java/com/iemr/tm/controller/common/master/CommonMasterController.java index 009ed41b..61015517 100644 --- a/src/main/java/com/iemr/tm/controller/common/master/CommonMasterController.java +++ b/src/main/java/com/iemr/tm/controller/common/master/CommonMasterController.java @@ -26,6 +26,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -41,6 +42,7 @@ @RestController @RequestMapping(value = "/master", headers = "Authorization", consumes = "application/json", produces = "application/json") /** Objective: provides master data based on given visitCategory */ +@PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public class CommonMasterController { private Logger logger = LoggerFactory.getLogger(CommonMasterController.class); diff --git a/src/main/java/com/iemr/tm/controller/covid19/CovidController.java b/src/main/java/com/iemr/tm/controller/covid19/CovidController.java index 93d10011..e65558c6 100644 --- a/src/main/java/com/iemr/tm/controller/covid19/CovidController.java +++ b/src/main/java/com/iemr/tm/controller/covid19/CovidController.java @@ -28,6 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -61,6 +62,7 @@ public class CovidController { @Operation(summary = "Save COVID nurse data") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE') ") public String saveBenNCDCareNurseData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -97,6 +99,7 @@ public String saveBenNCDCareNurseData(@RequestBody String requestObj, */ @Operation(summary = "Save COVID doctor data") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveBenCovidDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -129,6 +132,7 @@ public String saveBenCovidDoctorData(@RequestBody String requestObj, @Operation(summary = "Get COVID beneficiary visit details") @PostMapping(value = { "/getBenVisitDetailsFrmNurseCovid" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVisitDetailsFrmNurseCovid19( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -160,6 +164,7 @@ public String getBenVisitDetailsFrmNurseCovid19( */ @Operation(summary = "Get COVID beneficiary history") @PostMapping(value = { "/getBenCovid19HistoryDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCovid19HistoryDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -190,6 +195,7 @@ public String getBenCovid19HistoryDetails( */ @Operation(summary = "Get COVID beneficiary vitals") @PostMapping(value = { "/getBenVitalDetailsFrmNurseCovid" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVitalDetailsFrmNurseNCDCare( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -222,6 +228,7 @@ public String getBenVitalDetailsFrmNurseNCDCare( @Operation(summary = "Get COVID beneficiary case-record and referral details") @PostMapping(value = { "/getBenCaseRecordFromDoctorCovid" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCaseRecordFromDoctorCovid19( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -248,6 +255,7 @@ public String getBenCaseRecordFromDoctorCovid19( @Operation(summary = "Update COVID beneficiary history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateHistoryNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -285,6 +293,7 @@ public String updateHistoryNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update COVID beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateVitalNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -319,6 +328,7 @@ public String updateVitalNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update COVID beneficiary case-record and referral details") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateCovid19DoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/dataSyncActivity/StartSyncActivity.java b/src/main/java/com/iemr/tm/controller/dataSyncActivity/StartSyncActivity.java index 7d23c218..44ccc183 100644 --- a/src/main/java/com/iemr/tm/controller/dataSyncActivity/StartSyncActivity.java +++ b/src/main/java/com/iemr/tm/controller/dataSyncActivity/StartSyncActivity.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -38,6 +39,7 @@ import com.iemr.tm.service.dataSyncActivity.DownloadDataFromServerImpl; import com.iemr.tm.service.dataSyncActivity.UploadDataToServerImpl; import com.iemr.tm.utils.response.OutputResponse; + import io.swagger.v3.oas.annotations.Operation; /*** @@ -45,6 +47,7 @@ */ @RestController @RequestMapping(value = "/dataSyncActivity", headers = "Authorization", consumes = "application/json", produces = "application/json") +@PreAuthorize("hasRole('DATASYNC') || hasRole('DATA_SYNC') ") public class StartSyncActivity { private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); diff --git a/src/main/java/com/iemr/tm/controller/dataSyncLayerCentral/MMUDataSyncVanToServer.java b/src/main/java/com/iemr/tm/controller/dataSyncLayerCentral/MMUDataSyncVanToServer.java index 3f32247a..0b58f698 100644 --- a/src/main/java/com/iemr/tm/controller/dataSyncLayerCentral/MMUDataSyncVanToServer.java +++ b/src/main/java/com/iemr/tm/controller/dataSyncLayerCentral/MMUDataSyncVanToServer.java @@ -24,6 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -48,6 +49,7 @@ */ @RestController @RequestMapping(value = "/dataSync", headers = "Authorization", consumes = "application/json", produces = "application/json") +@PreAuthorize("hasRole('DATASYNC') || hasRole('DATA_SYNC') ") public class MMUDataSyncVanToServer { private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); diff --git a/src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java b/src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java index e902ed02..2235b87c 100644 --- a/src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java +++ b/src/main/java/com/iemr/tm/controller/foetalmonitor/FoetalMonitorController.java @@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/src/main/java/com/iemr/tm/controller/generalOPD/GeneralOPDController.java b/src/main/java/com/iemr/tm/controller/generalOPD/GeneralOPDController.java index 154e3323..5ecc595c 100644 --- a/src/main/java/com/iemr/tm/controller/generalOPD/GeneralOPDController.java +++ b/src/main/java/com/iemr/tm/controller/generalOPD/GeneralOPDController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -70,6 +71,7 @@ public class GeneralOPDController { */ @Operation(summary = "Save general OPD data collected by nurse") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE')") public String saveBenGenOPDNurseData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -106,6 +108,7 @@ public String saveBenGenOPDNurseData(@RequestBody String requestObj, */ @Operation(summary = "Save general OPD data collected by doctor") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR')") public String saveBenGenOPDDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -137,6 +140,7 @@ public String saveBenGenOPDDoctorData(@RequestBody String requestObj, @Operation(summary = "Get general OPD beneficiary visit details") @PostMapping(value = { "/getBenVisitDetailsFrmNurseGOPD" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") @Transactional(rollbackFor = Exception.class) public String getBenVisitDetailsFrmNurseGOPD( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { @@ -169,7 +173,7 @@ public String getBenVisitDetailsFrmNurseGOPD( */ @Operation(summary = "Get general OPD beneficiary history") @PostMapping(value = { "/getBenHistoryDetails" }) - + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenHistoryDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -200,6 +204,7 @@ public String getBenHistoryDetails( */ @Operation(summary = "Get general OPD beneficiary vitals") @PostMapping(value = { "/getBenVitalDetailsFrmNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVitalDetailsFrmNurse( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -231,7 +236,7 @@ public String getBenVitalDetailsFrmNurse( */ @Operation(summary = "Get general OPD beneficiary examination details") @PostMapping(value = { "/getBenExaminationDetails" }) - + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenExaminationDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -263,6 +268,7 @@ public String getBenExaminationDetails( @Operation(summary = "Get general OPD beneficiary case record and referral") @PostMapping(value = { "/getBenCaseRecordFromDoctorGeneralOPD" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCaseRecordFromDoctorGeneralOPD( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -289,6 +295,7 @@ public String getBenCaseRecordFromDoctorGeneralOPD( @Operation(summary = "Update beneficiary's general OPD visit details") @PostMapping(value = { "/update/visitDetailsScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateVisitNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -323,6 +330,7 @@ public String updateVisitNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update beneficiary history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateHistoryNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -357,6 +365,7 @@ public String updateHistoryNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update general OPD beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateVitalNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -391,6 +400,7 @@ public String updateVitalNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update general OPD beneficiary examination data") @PostMapping(value = { "/update/examinationScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateGeneralOPDExaminationNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -424,6 +434,7 @@ public String updateGeneralOPDExaminationNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update general OPD beneficiary case record and referral") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateGeneralOPDDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/labtechnician/LabtechnicianController.java b/src/main/java/com/iemr/tm/controller/labtechnician/LabtechnicianController.java index f3e8fd9a..d1fa06e9 100644 --- a/src/main/java/com/iemr/tm/controller/labtechnician/LabtechnicianController.java +++ b/src/main/java/com/iemr/tm/controller/labtechnician/LabtechnicianController.java @@ -24,6 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -46,6 +47,7 @@ @RestController @RequestMapping(value = "/labTechnician", headers = "Authorization", consumes = "application/json", produces = "application/json") +@PreAuthorize("hasRole('LAB_TECHNICIAN') || hasRole('LABTECHNICIAN') ") public class LabtechnicianController { private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); diff --git a/src/main/java/com/iemr/tm/controller/location/LocationController.java b/src/main/java/com/iemr/tm/controller/location/LocationController.java index 737ab8a4..f60ffd4e 100644 --- a/src/main/java/com/iemr/tm/controller/location/LocationController.java +++ b/src/main/java/com/iemr/tm/controller/location/LocationController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -41,6 +42,7 @@ @RestController @RequestMapping(value = "/location", headers = "Authorization", produces = { "application/json" }) +@PreAuthorize("hasRole('NURSE') || hasRole('PHARMACIST') || hasRole('LABTECHNICIAN') || hasRole('REGISTRAR') || hasRole('DATASYNC') || hasRole('DATA_SYNC') || hasRole('DOCTOR') || hasRole('LAB_TECHNICIAN') || hasRole('TC_SPECIALIST') || hasRole('TCSPECIALIST') || hasRole('ONCOLOGIST') || hasRole('RADIOLOGIST')") public class LocationController { private OutputResponse response; private Logger logger = LoggerFactory.getLogger(CommonMasterController.class); diff --git a/src/main/java/com/iemr/tm/controller/login/IemrMmuLoginController.java b/src/main/java/com/iemr/tm/controller/login/IemrMmuLoginController.java index 6d2c06f7..eb64b2c5 100644 --- a/src/main/java/com/iemr/tm/controller/login/IemrMmuLoginController.java +++ b/src/main/java/com/iemr/tm/controller/login/IemrMmuLoginController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -35,13 +36,17 @@ import com.iemr.tm.controller.registrar.main.RegistrarController; import com.iemr.tm.service.login.IemrMmuLoginServiceImpl; +import com.iemr.tm.utils.JwtUtil; import com.iemr.tm.utils.mapper.InputMapper; import com.iemr.tm.utils.response.OutputResponse; +import org.springframework.security.core.Authentication; import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletRequest; @RestController @RequestMapping(value = "/user", headers = "Authorization", consumes = "application/json", produces = "application/json") +@PreAuthorize("hasRole('NURSE') || hasRole('PHARMACIST') || hasRole('LABTECHNICIAN') || hasRole('REGISTRAR') || hasRole('DATASYNC') || hasRole('DATA_SYNC') || hasRole('DOCTOR') || hasRole('LAB_TECHNICIAN') || hasRole('TC_SPECIALIST') || hasRole('ONCOLOGIST') || hasRole('RADIOLOGIST') || hasRole('ASHA')") public class IemrMmuLoginController { private Logger logger = LoggerFactory.getLogger(RegistrarController.class); @@ -49,6 +54,10 @@ public class IemrMmuLoginController { private IemrMmuLoginServiceImpl iemrMmuLoginServiceImpl; + + @Autowired + private JwtUtil jwtUtil; + @Autowired public void setIemrMmuLoginServiceImpl(IemrMmuLoginServiceImpl iemrMmuLoginServiceImpl) { this.iemrMmuLoginServiceImpl = iemrMmuLoginServiceImpl; @@ -57,13 +66,25 @@ public void setIemrMmuLoginServiceImpl(IemrMmuLoginServiceImpl iemrMmuLoginServi @Operation(summary = "Get user service point van details") @PostMapping(value = "/getUserServicePointVanDetails", produces = { "application/json" }) - public String getUserServicePointVanDetails(@RequestBody String comingRequest) { + public String getUserServicePointVanDetails(@RequestBody String comingRequest, Authentication authentication) { OutputResponse response = new OutputResponse(); try { + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } + + Integer userID = Integer.valueOf(authentication.getPrincipal().toString()); + + JSONObject obj = new JSONObject(comingRequest); logger.info("getUserServicePointVanDetails request " + comingRequest); - String responseData = iemrMmuLoginServiceImpl.getUserServicePointVanDetails(obj.getInt("userID")); + if (userID == null) { + response.setError(403, "Unauthorized access: Missing or invalid token"); + return response.toString(); + } + String responseData = iemrMmuLoginServiceImpl.getUserServicePointVanDetails(userID); response.setResponse(responseData); } catch (Exception e) { // e.printStackTrace(); @@ -97,24 +118,31 @@ public String getServicepointVillages(@RequestBody String comingRequest) { @Operation(summary = "Get user service point van details") @PostMapping(value = "/getUserVanSpDetails", produces = { "application/json" }) - public String getUserVanSpDetails(@RequestBody String comingRequest) { + public String getUserVanSpDetails(@RequestBody String comingRequest, Authentication authentication) { OutputResponse response = new OutputResponse(); try { + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } - JSONObject obj = new JSONObject(comingRequest); - logger.info("getServicepointVillages request " + comingRequest); - if (obj.has("userID") && obj.has("providerServiceMapID")) { - String responseData = iemrMmuLoginServiceImpl.getUserVanSpDetails(obj.getInt("userID"), - obj.getInt("providerServiceMapID")); - response.setResponse(responseData); - } else { - response.setError(5000, "Invalid request"); - } - } catch (Exception e) { - response.setError(5000, "Error while getting van and service points data"); - logger.error("getUserVanSpDetails failed with " + e.getMessage(), e); + Integer userID = Integer.valueOf(authentication.getPrincipal().toString()); - } + JSONObject obj = new JSONObject(comingRequest); + logger.info("getUserVanSpDetails request {}", comingRequest); + + if (obj.has("providerServiceMapID")) { + String responseData = iemrMmuLoginServiceImpl.getUserVanSpDetails(userID, obj.getInt("providerServiceMapID")); + + response.setResponse(responseData); + } else { + response.setError(400, "Invalid request"); + } + + } catch (Exception e) { + response.setError(400, "Error while getting van and service points data"); + logger.error("getUserVanSpDetails failed", e); + } logger.info("getUserVanSpDetails response " + response.toString()); return response.toString(); } diff --git a/src/main/java/com/iemr/tm/controller/ncdCare/NCDCareController.java b/src/main/java/com/iemr/tm/controller/ncdCare/NCDCareController.java index b3c050bb..59d6a440 100644 --- a/src/main/java/com/iemr/tm/controller/ncdCare/NCDCareController.java +++ b/src/main/java/com/iemr/tm/controller/ncdCare/NCDCareController.java @@ -28,6 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -69,6 +70,7 @@ public void setNcdCareServiceImpl(NCDCareServiceImpl ncdCareServiceImpl) { */ @Operation(summary = "Save NCD care data collected by nurse") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE') ") public String saveBenNCDCareNurseData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -105,6 +107,7 @@ public String saveBenNCDCareNurseData(@RequestBody String requestObj, */ @Operation(summary = "Save NCD care beneficiary case record and referral") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveBenNCDCareDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -137,6 +140,7 @@ public String saveBenNCDCareDoctorData(@RequestBody String requestObj, @Operation(summary = "Get NCD care beneficiary visit details") @PostMapping(value = { "/getBenVisitDetailsFrmNurseNCDCare" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVisitDetailsFrmNurseNCDCare( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -168,7 +172,7 @@ public String getBenVisitDetailsFrmNurseNCDCare( */ @Operation(summary = "Get NCD care beneficiary history") @PostMapping(value = { "/getBenNCDCareHistoryDetails" }) - + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenNCDCareHistoryDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -199,6 +203,7 @@ public String getBenNCDCareHistoryDetails( */ @Operation(summary = "Get NCD care beneficiary vitals") @PostMapping(value = { "/getBenVitalDetailsFrmNurseNCDCare" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVitalDetailsFrmNurseNCDCare( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -231,6 +236,7 @@ public String getBenVitalDetailsFrmNurseNCDCare( @Operation(summary = "Get NCD care beneficiary case record and referral") @PostMapping(value = { "/getBenCaseRecordFromDoctorNCDCare" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCaseRecordFromDoctorNCDCare( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -257,6 +263,7 @@ public String getBenCaseRecordFromDoctorNCDCare( @Operation(summary = "Update NCD care beneficiary history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateHistoryNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -294,6 +301,7 @@ public String updateHistoryNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update NCD care beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateVitalNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -328,6 +336,7 @@ public String updateVitalNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update NCD care beneficiary case record and referral") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateNCDCareDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/ncdscreening/NCDScreeningController.java b/src/main/java/com/iemr/tm/controller/ncdscreening/NCDScreeningController.java index 4233327c..46d2a5d3 100644 --- a/src/main/java/com/iemr/tm/controller/ncdscreening/NCDScreeningController.java +++ b/src/main/java/com/iemr/tm/controller/ncdscreening/NCDScreeningController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.GetMapping; @@ -75,6 +76,7 @@ public void setNcdScreeningServiceImpl(NCDScreeningServiceImpl ncdScreeningServi @Operation(summary = "Save NCD screening beneficiary data collected by nurse") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE')") public String saveBeneficiaryNCDScreeningDetails(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { @@ -106,6 +108,7 @@ public String saveBeneficiaryNCDScreeningDetails(@RequestBody String requestObj, @Operation(summary = "Save NCD screening beneficiary data collected by doctor") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveBenNCDScreeningDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -137,6 +140,7 @@ public String saveBenNCDScreeningDoctorData(@RequestBody String requestObj, @Operation(summary = "Get NCD screening beneficiary visit details") @PostMapping(value = { "/get/nurseData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getNCDScreenigDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { @@ -162,6 +166,7 @@ public String getNCDScreenigDetails( @Operation(summary = "Get NCD screening visit count for beneficiary register id") @GetMapping(value = { "/getNcdScreeningVisitCount/{beneficiaryRegID}" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getNcdScreeningVisitCount(@PathVariable("beneficiaryRegID") Long beneficiaryRegID) { OutputResponse response = new OutputResponse(); try { @@ -190,6 +195,7 @@ public String getNcdScreeningVisitCount(@PathVariable("beneficiaryRegID") Long b @Operation(summary = "Get NCD screening beneficiary case record and referral") @PostMapping(value = { "/getBenCaseRecordFromDoctorNCDScreening" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCaseRecordFromDoctorNCDCare( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -217,6 +223,7 @@ public String getBenCaseRecordFromDoctorNCDCare( @Operation(summary = "Get NCD screening beneficiary visit details") @PostMapping(value = { "/getBenVisitDetailsFrmNurseNCDScreening" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVisitDetailsFrmNurseGOPD( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -243,7 +250,7 @@ public String getBenVisitDetailsFrmNurseGOPD( @Operation(summary = "Get NCD screening beneficiary general OPD history") @PostMapping(value = { "/getBenHistoryDetails" }) - + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenHistoryDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -269,6 +276,7 @@ public String getBenHistoryDetails( @Operation(summary = "Get NCD screening beneficiary vitals from general OPD nurse") @PostMapping(value = { "/getBenVitalDetailsFrmNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVitalDetailsFrmNurse( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -295,6 +303,7 @@ public String getBenVitalDetailsFrmNurse( @Operation(summary = "Get NCD screening IDRS details from general OPD nurse") @PostMapping(value = { "/getBenIdrsDetailsFrmNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenIdrsDetailsFrmNurse( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -322,6 +331,7 @@ public String getBenIdrsDetailsFrmNurse( @Operation(summary = "Get NCD screening beneficiary case record and referral") @PostMapping(value = { "/update/nurseData" }) + @PreAuthorize("hasRole('NURSE') ") public String updateBeneficiaryNCDScreeningDetails(@RequestBody String requestObj) { logger.info("Update NCDScreening Details request:" + requestObj); @@ -356,6 +366,7 @@ public String updateBeneficiaryNCDScreeningDetails(@RequestBody String requestOb */ @Operation(summary = "Update NCD screening beneficiary history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateHistoryNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -384,6 +395,7 @@ public String updateHistoryNurse(@RequestBody String requestObj) { @Operation(summary = "Update NCD screening beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateVitalNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -412,6 +424,7 @@ public String updateVitalNurse(@RequestBody String requestObj) { @Operation(summary = "Update NCD screening beneficiary history") @PostMapping(value = { "/update/idrsScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateIDRSScreen(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -440,6 +453,7 @@ public String updateIDRSScreen(@RequestBody String requestObj) { @Operation(summary = "Update NCD screening beneficiary case record and referral") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/nurse/vitals/AnthropometryVitalsController.java b/src/main/java/com/iemr/tm/controller/nurse/vitals/AnthropometryVitalsController.java index 7c47f4bf..4112c355 100644 --- a/src/main/java/com/iemr/tm/controller/nurse/vitals/AnthropometryVitalsController.java +++ b/src/main/java/com/iemr/tm/controller/nurse/vitals/AnthropometryVitalsController.java @@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -18,6 +19,7 @@ @RestController @RequestMapping(value = "/anthropometryVitals", headers = "Authorization", consumes = "application/json", produces = "application/json") +@PreAuthorize("hasRole('NURSE') ") public class AnthropometryVitalsController { private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); diff --git a/src/main/java/com/iemr/tm/controller/patientApp/master/PatientAppCommonMasterController.java b/src/main/java/com/iemr/tm/controller/patientApp/master/PatientAppCommonMasterController.java index fad5b48a..bce92e5a 100644 --- a/src/main/java/com/iemr/tm/controller/patientApp/master/PatientAppCommonMasterController.java +++ b/src/main/java/com/iemr/tm/controller/patientApp/master/PatientAppCommonMasterController.java @@ -26,6 +26,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -61,6 +62,7 @@ public void setCommonPatientAppMasterService(CommonPatientAppMasterService commo */ @Operation(summary = "Chief complaints master data API for patient app") @PostMapping(value = "/patientApp/chiefComplaintsMaster/{visitCategoryID}/{providerServiceMapID}/{gender}") + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String patientAppChiefComplaintsMasterData(@PathVariable("visitCategoryID") Integer visitCategoryID, @PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("gender") String gender) { logger.info("Nurse master Data for categoryID:" + visitCategoryID + " and providerServiceMapID:" @@ -75,6 +77,7 @@ public String patientAppChiefComplaintsMasterData(@PathVariable("visitCategoryID @Operation(summary = "COVID master data API for patient app") @PostMapping(value = "/patientApp/covidMaster/{visitCategoryID}/{providerServiceMapID}/{gender}") + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String patientAppCovidMasterData(@PathVariable("visitCategoryID") Integer visitCategoryID, @PathVariable("providerServiceMapID") Integer providerServiceMapID, @PathVariable("gender") String gender) { logger.info("Nurse master Data for categoryID:" + visitCategoryID + " and providerServiceMapID:" @@ -89,6 +92,7 @@ public String patientAppCovidMasterData(@PathVariable("visitCategoryID") Integer @Operation(summary = "Save COVID data in patient app") @PostMapping(value = { "/save/covidScreeningDataPatientApp" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String saveBenCovidDoctorDataPatientApp(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -108,6 +112,7 @@ public String saveBenCovidDoctorDataPatientApp(@RequestBody String requestObj, @Operation(summary = "Save chief-complaints data in patient app") @PostMapping(value = { "/save/chiefComplaintsDataPatientApp" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String saveBenChiefComplaintsDataPatientApp(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -127,6 +132,7 @@ public String saveBenChiefComplaintsDataPatientApp(@RequestBody String requestOb @Operation(summary = "Save tele-consultation slot in data patient app") @PostMapping(value = { "/save/tcSlotDetailsDataPatientApp" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public String saveTCSlotDataPatientApp(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -148,6 +154,7 @@ public String saveTCSlotDataPatientApp(@RequestBody String requestObj, @Operation(summary = "Get patient episode data for specialist in patient app") @PostMapping(value = { "/get/getPatientEpisodeData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public String getPatientEpisodeDataMobileApp(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -169,6 +176,7 @@ public String getPatientEpisodeDataMobileApp(@RequestBody String requestObj, @Operation(summary = "Get patient booked slot data in patient app") @PostMapping(value = { "/get/getPatientBookedSlotDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public String getPatientBookedSlotDetails(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -190,6 +198,7 @@ public String getPatientBookedSlotDetails(@RequestBody String requestObj, @Operation(summary = "Save specialist diagnosis data in patient app") @PostMapping(value = { "/save/saveSpecialistDiagnosisData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public String saveSpecialistDiagnosisData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -211,6 +220,7 @@ public String saveSpecialistDiagnosisData(@RequestBody String requestObj, @Operation(summary = "Get specialist diagnosis data in patient app") @PostMapping(value = { "/save/getSpecialistDiagnosisData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public String getSpecialistDiagnosisData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -232,6 +242,7 @@ public String getSpecialistDiagnosisData(@RequestBody String requestObj, @Operation(summary = "Get last 3 episode data of the patient in patient app") @PostMapping(value = { "/get/getPatientsEpisodes" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public String getPatientsLast_3_Episode(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/iemr/tm/controller/pnc/PostnatalCareController.java b/src/main/java/com/iemr/tm/controller/pnc/PostnatalCareController.java index dd93ef2a..709a2eab 100644 --- a/src/main/java/com/iemr/tm/controller/pnc/PostnatalCareController.java +++ b/src/main/java/com/iemr/tm/controller/pnc/PostnatalCareController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -66,6 +67,7 @@ public void setPncServiceImpl(PNCServiceImpl pncServiceImpl) { */ @Operation(summary = "Save PNC nurse data") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE')") public String saveBenPNCNurseData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -103,6 +105,7 @@ public String saveBenPNCNurseData(@RequestBody String requestObj, */ @Operation(summary = "Save PNC doctor data") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveBenPNCDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -135,6 +138,7 @@ public String saveBenPNCDoctorData(@RequestBody String requestObj, @Operation(summary = "Get PNC beneficiary visit details from nurse") @PostMapping(value = { "/getBenVisitDetailsFrmNursePNC" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") @Transactional(rollbackFor = Exception.class) public String getBenVisitDetailsFrmNursePNC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { @@ -168,6 +172,7 @@ public String getBenVisitDetailsFrmNursePNC( @Operation(summary = "Get PNC beneficiary details from nurse") @PostMapping(value = { "/getBenPNCDetailsFrmNursePNC" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenPNCDetailsFrmNursePNC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -199,7 +204,7 @@ public String getBenPNCDetailsFrmNursePNC( */ @Operation(summary = "Get PNC beneficiary history nurse") @PostMapping(value = { "/getBenHistoryDetails" }) - + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenHistoryDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -230,6 +235,7 @@ public String getBenHistoryDetails( */ @Operation(summary = "Get PNC beneficiary vital details from nurse") @PostMapping(value = { "/getBenVitalDetailsFrmNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVitalDetailsFrmNurse( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -261,7 +267,7 @@ public String getBenVitalDetailsFrmNurse( */ @Operation(summary = "Get PNC beneficiary examination details from nurse") @PostMapping(value = { "/getBenExaminationDetailsPNC" }) - + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenExaminationDetailsPNC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -293,6 +299,7 @@ public String getBenExaminationDetailsPNC( @Operation(summary = "Get PNC beneficiary case record") @PostMapping(value = { "/getBenCaseRecordFromDoctorPNC" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCaseRecordFromDoctorPNC( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -319,6 +326,7 @@ public String getBenCaseRecordFromDoctorPNC( @Operation(summary = "Update PNC doctor data") @PostMapping(value = { "/update/PNCScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updatePNCCareNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -354,6 +362,7 @@ public String updatePNCCareNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update PNC beneficiary history") @PostMapping(value = { "/update/historyScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateHistoryNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -389,6 +398,7 @@ public String updateHistoryNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update PNC beneficiary vitals") @PostMapping(value = { "/update/vitalScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateVitalNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -424,6 +434,7 @@ public String updateVitalNurse(@RequestBody String requestObj) { */ @Operation(summary = "Update PNC examination data") @PostMapping(value = { "/update/examinationScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String updateGeneralOPDExaminationNurse(@RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -452,6 +463,7 @@ public String updateGeneralOPDExaminationNurse(@RequestBody String requestObj) { @Operation(summary = "Update PNC doctor data") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updatePNCDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/quickconsult/QuickConsultController.java b/src/main/java/com/iemr/tm/controller/quickconsult/QuickConsultController.java index baf4fb4b..dfecab11 100644 --- a/src/main/java/com/iemr/tm/controller/quickconsult/QuickConsultController.java +++ b/src/main/java/com/iemr/tm/controller/quickconsult/QuickConsultController.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; @@ -75,6 +76,7 @@ public void setQuickConsultationServiceImpl(QuickConsultationServiceImpl quickCo */ @Operation(summary = "Save quick consult nurse data") @PostMapping(value = { "/save/nurseData" }) + @PreAuthorize("hasRole('NURSE') ") public String saveBenQuickConsultDataNurse(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) throws Exception { OutputResponse response = new OutputResponse(); @@ -111,6 +113,7 @@ public String saveBenQuickConsultDataNurse(@RequestBody String requestObj, */ @Operation(summary = "Save quick consult doctor data") @PostMapping(value = { "/save/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String saveQuickConsultationDetail( @Param(value = "{\"quickConsultation\":{\"beneficiaryRegID\":\"Long\",\"providerServiceMapID\": \"Integer\", \"benVisitID\":\"Long\", \"benChiefComplaint\":[{\"chiefComplaintID\":\"Integer\", " + "\"chiefComplaint\":\"String\", \"duration\":\"Integer\", \"unitOfDuration\":\"String\"}], \"description\":\"String\"" @@ -149,6 +152,7 @@ public String saveQuickConsultationDetail( @Operation(summary = "Get quick consult beneficiary visit details") @PostMapping(value = { "/getBenDataFrmNurseToDocVisitDetailsScreen" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenDataFrmNurseScrnToDocScrnVisitDetails( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -179,6 +183,7 @@ public String getBenDataFrmNurseScrnToDocScrnVisitDetails( */ @Operation(summary = "Get quick consult beneficiary vital details") @PostMapping(value = { "/getBenVitalDetailsFrmNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenVitalDetailsFrmNurse( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -211,6 +216,7 @@ public String getBenVitalDetailsFrmNurse( @Operation(summary = "Get quick consult beneficiary case record") @PostMapping(value = { "/getBenCaseRecordFromDoctorQuickConsult" }) @Transactional(rollbackFor = Exception.class) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public String getBenCaseRecordFromDoctorQuickConsult( @Param(value = "{\"benRegID\":\"Long\",\"visitCode\":\"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -237,6 +243,7 @@ public String getBenCaseRecordFromDoctorQuickConsult( @Operation(summary = "Update quick consult doctor data") @PostMapping(value = { "/update/doctorData" }) + @PreAuthorize("hasRole('DOCTOR') ") public String updateGeneralOPDQCDoctorData(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { diff --git a/src/main/java/com/iemr/tm/controller/registrar/main/RegistrarController.java b/src/main/java/com/iemr/tm/controller/registrar/main/RegistrarController.java index 7564bb51..5ddcf7ce 100644 --- a/src/main/java/com/iemr/tm/controller/registrar/main/RegistrarController.java +++ b/src/main/java/com/iemr/tm/controller/registrar/main/RegistrarController.java @@ -29,6 +29,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -83,6 +84,7 @@ public void setNurseServiceImpl(NurseServiceImpl nurseServiceImpl) { // Registrar Work List API ..... @Operation(summary = "Get registrar worklist data") @PostMapping(value = { "/registrarWorkListData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String getRegistrarWorkList(@Param(value = "{\"spID\": \"Integer\"}") @RequestBody String comingRequest) throws JSONException { OutputResponse response = new OutputResponse(); @@ -102,6 +104,7 @@ public String getRegistrarWorkList(@Param(value = "{\"spID\": \"Integer\"}") @Re // Registrar Quick search ..... @Operation(summary = "Search for the beneficiary based on beneficiary id") @PostMapping(value = { "/quickSearch" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String quickSearchBeneficiary( @Param(value = "{\"benID\": \"String\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -120,6 +123,7 @@ public String quickSearchBeneficiary( // Registrar Advance search ..... @Operation(summary = "Search for the beneficiary based on provided data") @PostMapping(value = { "/advanceSearch" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String advanceSearch( @Param(value = "{\"firstName\": \"String\", \"lastName\": \"String\", \"phoneNo\": \"String\"," + "\"beneficiaryID\": \"String\", \"stateID\": \"Integer\", \"districtID\": \"Integer\", \"aadharNo\": \"String\"}," @@ -142,6 +146,7 @@ public String advanceSearch( // API for left side ben data @Operation(summary = "Get beneficiary details based on beneficiary register id") @PostMapping(value = { "/get/benDetailsByRegID" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String getBenDetailsByRegID( @Param(value = "{\"beneficiaryRegID\": \"Long\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); @@ -171,6 +176,7 @@ public String getBenDetailsByRegID( @Operation(summary = "Get beneficiary details") @PostMapping(value = { "/get/beneficiaryDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('LABTECHNICIAN') || hasRole('LAB_TECHNICIAN') || hasRole('PHARMACIST') || hasRole('REGISTRAR')") public String getBeneficiaryDetails( @Param(value = "{\"beneficiaryRegID\": \"Long\"}") @RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -205,6 +211,7 @@ public String getBeneficiaryDetails( @Operation(summary = "Get beneficiary image") @PostMapping(value = { "/get/beneficiaryImage" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('LABTECHNICIAN') || hasRole('LAB_TECHNICIAN') || hasRole('PHARMACIST') || hasRole('REGISTRAR')") public String getBeneficiaryImage( @Param(value = "{\"beneficiaryRegID\": \"Long\"}") @RequestBody String requestObj) { OutputResponse response = new OutputResponse(); @@ -231,6 +238,7 @@ public String getBeneficiaryImage( // beneficiary quick search new integrated with common and identity @Operation(summary = "Search beneficiary based on beneficiary id or beneficiary phone number") @PostMapping(value = { "/quickSearchNew" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String quickSearchNew(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { String searchList = null; @@ -254,6 +262,7 @@ public String quickSearchNew(@RequestBody String requestObj, // beneficiary Advance search new integrated with common and identity @Operation(summary = "Beneficiary advance search integrated with common and identity API") @PostMapping(value = { "/advanceSearchNew" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String advanceSearchNew(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { String searchList = null; @@ -277,6 +286,7 @@ public String advanceSearchNew(@RequestBody String requestObj, // Get Beneficiary Details for left side panel of given beneficiaryRegID new @Operation(summary = "Get beneficiary details for side panel") @PostMapping(value = { "/get/benDetailsByRegIDForLeftPanelNew" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('LABTECHNICIAN') || hasRole('LAB_TECHNICIAN') || hasRole('PHARMACIST')") public String getBenDetailsForLeftSidePanelByRegID( @Param(value = "{\"beneficiaryRegID\": \"Long\"}") @RequestBody String comingRequest, @RequestHeader(value = "Authorization") String Authorization) { @@ -308,6 +318,7 @@ public String getBenDetailsForLeftSidePanelByRegID( // new api for ben image @Operation(summary = "Get beneficiary image") @PostMapping(value = { "/getBenImage" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('LABTECHNICIAN') || hasRole('LAB_TECHNICIAN') || hasRole('PHARMACIST')") public String getBenImage(@RequestBody String requestObj, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -324,6 +335,7 @@ public String getBenImage(@RequestBody String requestObj, @Operation(summary = "Register a new beneficiary") @PostMapping(value = { "/registrarBeneficaryRegistration" }) + @PreAuthorize("hasRole('NURSE') || hasRole('REGISTRAR')") public String createBeneficiary( @Param(value = "{\"benD\":{\"firstName\": \"String\", \"lastName\": \"String\", \"gender\": \"Short\"," + "\"dob\": \"Timestamp\", \"maritalStatus\": \"Short\", \"fatherName\": \"String\", \"motherName\": \"String\"," @@ -387,6 +399,7 @@ public String createBeneficiary( // beneficiary registration with common and identity new @Operation(summary = "Register a new beneficiary new API") @PostMapping(value = { "/registrarBeneficaryRegistrationNew" }) + @PreAuthorize("hasRole('NURSE') || hasRole('REGISTRAR') || hasRole('ASHA')") public String registrarBeneficaryRegistrationNew(@RequestBody String comingReq, @RequestHeader(value = "Authorization") String Authorization) { String s; @@ -404,6 +417,7 @@ public String registrarBeneficaryRegistrationNew(@RequestBody String comingReq, @Operation(summary = "Update registered beneficiary data") @PostMapping(value = { "/update/BeneficiaryDetails" }) + @PreAuthorize("hasRole('NURSE') || hasRole('REGISTRAR') || hasRole('DOCTOR')") public String updateBeneficiary( @Param(value = "{\"benD\": {\"beneficiaryRegID\": \"Long\", \"firstName\": \"String\", \"lastName\": \"String\", \"gender\": \"Short\"," + "\"dob\": \"Timestamp\", \"maritalStatus\": \"Short\", \"fatherName\": \"String\", \"motherName\": \"String\"," @@ -467,6 +481,7 @@ public String updateBeneficiary( // revisit to nurse by searching and submitting new @Operation(summary = "Search and submit beneficiary to nurse for revisit") @PostMapping(value = { "/create/BenReVisitToNurse" }) + @PreAuthorize("hasRole('NURSE') || hasRole('REGISTRAR')") public String createReVisitForBenToNurse(@RequestBody String requestOBJ) { OutputResponse response = new OutputResponse(); try { @@ -488,6 +503,7 @@ public String createReVisitForBenToNurse(@RequestBody String requestOBJ) { @Operation(summary = "Update registered beneficiary details") @PostMapping(value = { "/update/BeneficiaryUpdate" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String beneficiaryUpdate(@RequestBody String requestOBJ, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -511,6 +527,7 @@ public String beneficiaryUpdate(@RequestBody String requestOBJ, @Operation(summary = "Get master data for registrar") @PostMapping(value = { "/registrarMasterData" }) + @PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('REGISTRAR')") public String masterDataForRegistration( @Param(value = "{\"spID\": \"Integer\"}") @RequestBody String comingRequest) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/iemr/tm/controller/report/CRMReportController.java b/src/main/java/com/iemr/tm/controller/report/CRMReportController.java index bcb3aba6..a5b659fb 100644 --- a/src/main/java/com/iemr/tm/controller/report/CRMReportController.java +++ b/src/main/java/com/iemr/tm/controller/report/CRMReportController.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -45,6 +46,8 @@ @RequestMapping("/TMReport") @RestController +@PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') || hasRole('LABTECHNICIAN') || hasRole('LAB_TECHNICIAN') || hasRole('PHARMACIST') || hasRole('TC_SPECIALIST') || hasRole('TCSPECIALIST') || hasRole('ONCOLOGIST') || hasRole('RADIOLOGIST')") + public class CRMReportController { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); diff --git a/src/main/java/com/iemr/tm/controller/snomedct/SnomedController.java b/src/main/java/com/iemr/tm/controller/snomedct/SnomedController.java index 945064d6..dab6f773 100644 --- a/src/main/java/com/iemr/tm/controller/snomedct/SnomedController.java +++ b/src/main/java/com/iemr/tm/controller/snomedct/SnomedController.java @@ -24,6 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -42,6 +43,7 @@ @RequestMapping(value = "/snomed", consumes = "application/json", produces = "application/json") @RestController +@PreAuthorize("hasRole('NURSE') || hasRole('DOCTOR') ") public class SnomedController { private Logger logger = LoggerFactory.getLogger(SnomedController.class); diff --git a/src/main/java/com/iemr/tm/controller/teleconsultation/TeleConsultationController.java b/src/main/java/com/iemr/tm/controller/teleconsultation/TeleConsultationController.java index 92e95b44..316a5e1a 100644 --- a/src/main/java/com/iemr/tm/controller/teleconsultation/TeleConsultationController.java +++ b/src/main/java/com/iemr/tm/controller/teleconsultation/TeleConsultationController.java @@ -24,6 +24,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -31,6 +33,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import jakarta.servlet.http.HttpServletRequest; + +import com.iemr.tm.utils.CookieUtil; +import com.iemr.tm.utils.JwtUtil; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -41,12 +48,16 @@ @RestController @RequestMapping(value = "/tc", headers = "Authorization", consumes = "application/json", produces = "application/json") +@PreAuthorize("hasRole('TCSPECIALIST') || hasRole('TC_SPECIALIST') ") public class TeleConsultationController { private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); @Autowired private TeleConsultationServiceImpl teleConsultationServiceImpl; + @Autowired + private JwtUtil jwtUtil; + @Operation(summary = "Update beneficiary arrival status based on request") @PostMapping(value = { "/update/benArrivalStatus" }) public String benArrivalStatusUpdater(@RequestBody String requestOBJ) { @@ -137,24 +148,33 @@ public String createTCRequestForBeneficiary(@RequestBody String requestOBJ, @Req // TC request List @Operation(summary = "Get teleconsultation request list for a specialist") @PostMapping(value = { "/getTCRequestList" }) - public String getTCSpecialistWorkListNew(@RequestBody String requestOBJ) { + public String getTCSpecialistWorkListNew(@RequestBody String requestOBJ, Authentication authentication) { OutputResponse response = new OutputResponse(); try { + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } + + Integer userID = Integer.valueOf(authentication.getPrincipal().toString()); + if (requestOBJ != null) { JsonObject jsnOBJ = new JsonObject(); JsonParser jsnParser = new JsonParser(); JsonElement jsnElmnt = jsnParser.parse(requestOBJ); jsnOBJ = jsnElmnt.getAsJsonObject(); - + if (userID != null) { String s = teleConsultationServiceImpl.getTCRequestListBySpecialistIdAndDate( - jsnOBJ.get("psmID").getAsInt(), jsnOBJ.get("userID").getAsInt(), + jsnOBJ.get("psmID").getAsInt(), userID, jsnOBJ.get("date").getAsString()); if (s != null) response.setResponse(s); } else { - logger.error("Invalid request, either ProviderServiceMapID or userID or reqDate is invalid"); + response.setError(403, "Unauthorized access!"); + } } else { + logger.error("Invalid request, either ProviderServiceMapID or reqDate is invalid"); response.setError(5000, - "Invalid request, either ProviderServiceMapID or UserID or RequestDate is invalid"); + "Invalid request, either ProviderServiceMapID or RequestDate is invalid"); } } catch (Exception e) { diff --git a/src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java b/src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java index aca8405a..5fc51fa2 100644 --- a/src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java +++ b/src/main/java/com/iemr/tm/controller/videoconsultationcontroller/VideoConsultationController.java @@ -24,6 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -33,6 +34,11 @@ import com.iemr.tm.service.videoconsultation.VideoConsultationService; import com.iemr.tm.utils.response.OutputResponse; +import jakarta.servlet.http.HttpServletRequest; + +import com.iemr.tm.utils.CookieUtil; +import com.iemr.tm.utils.JwtUtil; + import io.swagger.v3.oas.annotations.Operation; @RestController @@ -44,19 +50,29 @@ public class VideoConsultationController { @Autowired private VideoConsultationService videoConsultationService; + @Autowired + private JwtUtil jwtUtil; + @Operation(summary = "Login to video consultation service") @GetMapping(value = "/login/{userID}", headers = "Authorization", produces = { "application/json" }) - public String login(@PathVariable("userID") Long userID) { + public String login(@PathVariable("userID") Long userID, Authentication authentication) { OutputResponse response = new OutputResponse(); - try { + if (authentication == null || !authentication.isAuthenticated()) { + response.setError(403, "Unauthorized access"); + return response.toString(); + } - String createdData = videoConsultationService.login(userID); - - response.setResponse(createdData.toString()); + String userId = authentication.getPrincipal().toString(); + if(userID.toString().equals(userId)) { + String createdData = videoConsultationService.login(userID); + response.setResponse(createdData.toString()); + } else { + response.setError(403, "Unauthorized access!"); + } } catch (Exception e) { logger.error(e.getMessage()); response.setError(e); diff --git a/src/main/java/com/iemr/tm/data/benFlowStatus/BeneficiaryFlowStatus.java b/src/main/java/com/iemr/tm/data/benFlowStatus/BeneficiaryFlowStatus.java index f7f65b0e..884e1b48 100644 --- a/src/main/java/com/iemr/tm/data/benFlowStatus/BeneficiaryFlowStatus.java +++ b/src/main/java/com/iemr/tm/data/benFlowStatus/BeneficiaryFlowStatus.java @@ -295,7 +295,11 @@ public class BeneficiaryFlowStatus { @Expose @Column(name = "referred_visit_id") private Long referred_visit_id; - + + @Expose + @Column(name = "doctor_signature_flag") + private Boolean doctorSignatureFlag = false; + @Transient private I_bendemographics i_bendemographics; @Transient @@ -374,6 +378,9 @@ public static BeneficiaryFlowStatus getBeneficiaryFlowStatusForLeftPanel(ArrayLi (String) objArr[11], (String) objArr[12], (String) objArr[13], (Long) objArr[14], (Timestamp) objArr[15], (Timestamp) objArr[16], (Long) objArr[17], (Timestamp) objArr[18], (String) objArr[19], (String) objArr[20]); + if (objArr.length > 21) { + obj.setDoctorSignatureFlag((Boolean) objArr[21]); + } } } return obj; @@ -991,9 +998,12 @@ public Long getReferred_visit_id() { public void setReferred_visit_id(Long referred_visit_id) { this.referred_visit_id = referred_visit_id; } - - - - + public Boolean getDoctorSignatureFlag() { + return doctorSignatureFlag; + } + + public void setDoctorSignatureFlag(Boolean doctorSignatureFlag) { + this.doctorSignatureFlag = doctorSignatureFlag; + } } diff --git a/src/main/java/com/iemr/tm/data/ncdcare/NCDCareDiagnosis.java b/src/main/java/com/iemr/tm/data/ncdcare/NCDCareDiagnosis.java index a9eac0d8..19b93a29 100644 --- a/src/main/java/com/iemr/tm/data/ncdcare/NCDCareDiagnosis.java +++ b/src/main/java/com/iemr/tm/data/ncdcare/NCDCareDiagnosis.java @@ -379,7 +379,7 @@ public void setNcdScreeningConditionOther(String ncdScreeningConditionOther) { public NCDCareDiagnosis(Long beneficiaryRegID, Long benVisitID, Integer providerServiceMapID, Long prescriptionID, String ncdCareCondition, String ncdComplication, String ncdCareType, Long visitCode, - String externalInvestigation, String ncdCareConditionOther) { + String externalInvestigation, String ncdCareConditionOther, String createdBy, Timestamp createdDate) { super(); this.beneficiaryRegID = beneficiaryRegID; this.benVisitID = benVisitID; @@ -391,6 +391,8 @@ public NCDCareDiagnosis(Long beneficiaryRegID, Long benVisitID, Integer provider this.visitCode = visitCode; this.externalInvestigation = externalInvestigation; this.ncdScreeningConditionOther = ncdCareConditionOther; + this.createdBy = createdBy; + this.createdDate = createdDate; } public static NCDCareDiagnosis getNCDCareDiagnosisDetails(ArrayList resList) { @@ -398,7 +400,8 @@ public static NCDCareDiagnosis getNCDCareDiagnosisDetails(ArrayList re if (null != resList && resList.size() > 0) { Object[] obj = resList.get(0); cOBJ = new NCDCareDiagnosis((Long) obj[0], (Long) obj[1], (Integer) obj[2], (Long) obj[3], (String) obj[4], - (String) obj[5], (String) obj[6], (Long) obj[7], null, (String) obj[8]); + (String) obj[5], (String) obj[6], (Long) obj[7], null, (String) obj[8], (String) obj[9], + (Timestamp) obj[10]); } return cOBJ; diff --git a/src/main/java/com/iemr/tm/repo/benFlowStatus/BeneficiaryFlowStatusRepo.java b/src/main/java/com/iemr/tm/repo/benFlowStatus/BeneficiaryFlowStatusRepo.java index 0db522e5..579f7631 100644 --- a/src/main/java/com/iemr/tm/repo/benFlowStatus/BeneficiaryFlowStatusRepo.java +++ b/src/main/java/com/iemr/tm/repo/benFlowStatus/BeneficiaryFlowStatusRepo.java @@ -118,7 +118,7 @@ public int updateBenFlowStatusAfterNurseActivityANC(@Param("benFlowID") Long ben @Query("SELECT t.benFlowID, t.beneficiaryRegID, t.visitDate, t.benName, t.age, t.ben_age_val, t.genderID, t.genderName, " + " t.villageName, t.districtName, t.beneficiaryID, t.servicePointName, t.VisitReason, t.VisitCategory, t.benVisitID, " - + " t.registrationDate, t.benVisitDate, t.visitCode, t.consultationDate, t.fatherName, t.preferredPhoneNum FROM BeneficiaryFlowStatus t " + + " t.registrationDate, t.benVisitDate, t.visitCode, t.consultationDate, t.fatherName, t.preferredPhoneNum, t.doctorSignatureFlag FROM BeneficiaryFlowStatus t " + " Where t.beneficiaryRegID = :benRegID AND t.benFlowID = :benFlowID ") public ArrayList getBenDetailsForLeftSidePanel(@Param("benRegID") Long benRegID, @Param("benFlowID") Long benFlowID); @@ -204,17 +204,18 @@ public ArrayList getLabWorklistNew( *updating lab technician flag as well after feto sense. */ @Transactional - @Modifying + @Modifying @Query("UPDATE BeneficiaryFlowStatus t set t.doctorFlag = :docFlag , t.pharmacist_flag = :pharmaFlag, " + " t.oncologist_flag = :oncologistFlag, t.consultationDate = now(), t.processed = 'U', " + " t.specialist_flag = :tcSpecialistFlag, t.tCSpecialistUserID = :tcSpecialistUserID, " - + "t.tCRequestDate = :tcDate, t.lab_technician_flag = :labTechnicianFlag " + + "t.tCRequestDate = :tcDate, t.lab_technician_flag = :labTechnicianFlag, t.doctorSignatureFlag = :signatureFlag " + " WHERE t.benFlowID = :benFlowID AND " + " t.beneficiaryRegID = :benRegID AND t.beneficiaryID = :benID ") public int updateBenFlowStatusAfterDoctorActivity(@Param("benFlowID") Long benFlowID, @Param("benRegID") Long benRegID, @Param("benID") Long benID, @Param("docFlag") Short docFlag, @Param("pharmaFlag") Short pharmaFlag, @Param("oncologistFlag") Short oncologistFlag, @Param("tcSpecialistFlag") Short tcSpecialistFlag, @Param("tcSpecialistUserID") int tcSpecialistUserID, - @Param("tcDate") Timestamp tcDate,@Param("labTechnicianFlag") Short labTechnicianFlag); + @Param("tcDate") Timestamp tcDate,@Param("labTechnicianFlag") Short labTechnicianFlag, + @Param("signatureFlag") Boolean signatureFlag); /*** * @author DU20091017 @@ -224,12 +225,12 @@ public int updateBenFlowStatusAfterDoctorActivity(@Param("benFlowID") Long benFl @Modifying @Query("UPDATE BeneficiaryFlowStatus t set t.doctorFlag = :docFlag , t.pharmacist_flag = :pharmaFlag, " + " t.oncologist_flag = :oncologistFlag, t.consultationDate = now(), t.processed = 'U', " - + " t.specialist_flag = :tcSpecialistFlag , t.lab_technician_flag = :labTechnicianFlag " + + " t.specialist_flag = :tcSpecialistFlag , t.lab_technician_flag = :labTechnicianFlag, t.doctorSignatureFlag = :signatureFlag " + " WHERE t.benFlowID = :benFlowID AND t.beneficiaryRegID = :benRegID AND t.beneficiaryID = :benID ") public int updateBenFlowStatusAfterDoctorActivitySpecialist(@Param("benFlowID") Long benFlowID, @Param("benRegID") Long benRegID, @Param("benID") Long benID, @Param("docFlag") Short docFlag, @Param("pharmaFlag") Short pharmaFlag, @Param("oncologistFlag") Short oncologistFlag, - @Param("tcSpecialistFlag") Short tcSpecialistFlag,@Param("labTechnicianFlag") Short labTechnicianFlag); + @Param("tcSpecialistFlag") Short tcSpecialistFlag,@Param("labTechnicianFlag") Short labTechnicianFlag, @Param("signatureFlag") Boolean signatureFlag); /*** * @author DU20091017 @@ -239,12 +240,12 @@ public int updateBenFlowStatusAfterDoctorActivitySpecialist(@Param("benFlowID") @Modifying @Query("UPDATE BeneficiaryFlowStatus t set t.doctorFlag = :docFlag , t.pharmacist_flag = :pharmaFlag, " + " t.oncologist_flag = :oncologistFlag, t.consultationDate = now(), t.processed = 'U', " - + " t.specialist_flag = :tcSpecialistFlag , t.lab_technician_flag = :labTechnicianFlag " + + " t.specialist_flag = :tcSpecialistFlag , t.lab_technician_flag = :labTechnicianFlag, t.doctorSignatureFlag = :signatureFlag" + " WHERE t.benFlowID = :benFlowID AND t.beneficiaryRegID = :benRegID AND t.beneficiaryID = :benID ") public int updateBenFlowStatusAfterDoctorActivitySpecialistANC(@Param("benFlowID") Long benFlowID, @Param("benRegID") Long benRegID, @Param("benID") Long benID, @Param("docFlag") Short docFlag, @Param("pharmaFlag") Short pharmaFlag, @Param("oncologistFlag") Short oncologistFlag, - @Param("tcSpecialistFlag") Short tcSpecialistFlag,@Param("labTechnicianFlag") Short labTechnicianFlag); + @Param("tcSpecialistFlag") Short tcSpecialistFlag,@Param("labTechnicianFlag") Short labTechnicianFlag, @Param("signatureFlag") Boolean signatureFlag); /*** * @author DU20091017 @@ -254,22 +255,24 @@ public int updateBenFlowStatusAfterDoctorActivitySpecialistANC(@Param("benFlowID @Modifying @Query("UPDATE BeneficiaryFlowStatus t set t.pharmacist_flag = :pharmaFlag, " + " t.oncologist_flag = :oncologistFlag, t.processed = 'U', t.specialist_flag = :tcSpecialistFlag, " - + "t.lab_technician_flag = :labTechnicianFlag" + + "t.lab_technician_flag = :labTechnicianFlag, t.doctorSignatureFlag = :signatureFlag" + " WHERE t.benFlowID = :benFlowID AND t.beneficiaryRegID = :benRegID AND t.beneficiaryID = :benID ") public int updateBenFlowStatusAfterDoctorActivityTCSpecialist(@Param("benFlowID") Long benFlowID, @Param("benRegID") Long benRegID, @Param("benID") Long benID, @Param("pharmaFlag") Short pharmaFlag, @Param("oncologistFlag") Short oncologistFlag, @Param("tcSpecialistFlag") Short tcSpecialistFlag, - @Param("labTechnicianFlag") Short labTechnicianFlag); + @Param("labTechnicianFlag") Short labTechnicianFlag, @Param("signatureFlag") Boolean signatureFlag); @Transactional - @Modifying - @Query("UPDATE BeneficiaryFlowStatus t set t.doctorFlag = :docFlag , t.pharmacist_flag = :pharmaFlag, " - + " t.oncologist_flag = :oncologistFlag , t.processed = 'U' " + " WHERE t.benFlowID = :benFlowID AND " - + " t.beneficiaryRegID = :benRegID AND t.beneficiaryID = :benID ") - public int updateBenFlowStatusAfterDoctorActivityUpdate(@Param("benFlowID") Long benFlowID, - @Param("benRegID") Long benRegID, @Param("benID") Long benID, @Param("docFlag") Short docFlag, - @Param("pharmaFlag") Short pharmaFlag, @Param("oncologistFlag") Short oncologistFlag); - + @Modifying + @Query("UPDATE BeneficiaryFlowStatus t set t.doctorFlag = :docFlag , t.pharmacist_flag = :pharmaFlag, " + + " t.oncologist_flag = :oncologistFlag , t.processed = 'U', t.doctorSignatureFlag = :signatureFlag" + + " WHERE t.benFlowID = :benFlowID AND " + + " t.beneficiaryRegID = :benRegID AND t.beneficiaryID = :benID ") + public int updateBenFlowStatusAfterDoctorActivityUpdate(@Param("benFlowID") Long benFlowID, + @Param("benRegID") Long benRegID, @Param("benID") Long benID, @Param("docFlag") Short docFlag, + @Param("pharmaFlag") Short pharmaFlag, @Param("oncologistFlag") Short oncologistFlag, + @Param("signatureFlag") Boolean signatureFlag); + @Query("SELECT t from BeneficiaryFlowStatus t " + " WHERE t.benVisitDate >= Date(:fromDate) AND t.vanID = :vanID AND t.radiologist_flag = 1 " + " AND t.providerServiceMapId= :providerServiceMapId ORDER BY t.benVisitDate DESC ") diff --git a/src/main/java/com/iemr/tm/repo/login/UserLoginRepo.java b/src/main/java/com/iemr/tm/repo/login/UserLoginRepo.java index 0898602d..f0b2f746 100644 --- a/src/main/java/com/iemr/tm/repo/login/UserLoginRepo.java +++ b/src/main/java/com/iemr/tm/repo/login/UserLoginRepo.java @@ -1,5 +1,7 @@ package com.iemr.tm.repo.login; +import java.util.List; + import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; @@ -13,4 +15,7 @@ public interface UserLoginRepo extends CrudRepository { @Query(" SELECT u FROM Users u WHERE u.userID = :userID AND u.Deleted = false ") public Users getUserByUserID(@Param("userID") Long userID); + @Query(nativeQuery = true,value = "select rolename from m_role where roleid in (select roleid from m_userservicerolemapping where userid=:userID)") + List getRoleNamebyUserId(@Param("userID") Long userID); + } diff --git a/src/main/java/com/iemr/tm/repo/nurse/ncdcare/NCDCareDiagnosisRepo.java b/src/main/java/com/iemr/tm/repo/nurse/ncdcare/NCDCareDiagnosisRepo.java index e7337050..47b30973 100644 --- a/src/main/java/com/iemr/tm/repo/nurse/ncdcare/NCDCareDiagnosisRepo.java +++ b/src/main/java/com/iemr/tm/repo/nurse/ncdcare/NCDCareDiagnosisRepo.java @@ -39,7 +39,7 @@ public interface NCDCareDiagnosisRepo extends CrudRepository { @Query(" SELECT beneficiaryRegID, benVisitID, providerServiceMapID, prescriptionID, " - + " ncdScreeningCondition, ncdComplication, ncdCareType, visitCode, ncdScreeningConditionOther " + + " ncdScreeningCondition, ncdComplication, ncdCareType, visitCode, ncdScreeningConditionOther, createdBy, createdDate " + " from NCDCareDiagnosis ba " + " WHERE ba.beneficiaryRegID = :benRegID" + " AND ba.visitCode = :visitCode AND ba.deleted = false " + " ORDER BY createdDate desc") public ArrayList getNCDCareDiagnosisDetails(@Param("benRegID") Long benRegID, diff --git a/src/main/java/com/iemr/tm/service/anc/ANCServiceImpl.java b/src/main/java/com/iemr/tm/service/anc/ANCServiceImpl.java index fc1da82c..8f8db36f 100644 --- a/src/main/java/com/iemr/tm/service/anc/ANCServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/anc/ANCServiceImpl.java @@ -350,6 +350,11 @@ public Long saveANCDoctorData(JsonObject requestOBJ, String Authorization) throw Long referSaveSuccessFlag = null; Integer tcRequestStatusFlag = null; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + if (requestOBJ != null) { TeleconsultationRequestOBJ tcRequestOBJ = null; // TcSpecialistSlotBookingRequestOBJ tcSpecialistSlotBookingRequestOBJ = null; @@ -466,7 +471,7 @@ public Long saveANCDoctorData(JsonObject requestOBJ, String Authorization) throw } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ,doctorSignatureFlag); if (i > 0) saveSuccessFlag = diagnosisSuccessFlag; @@ -1488,6 +1493,11 @@ public Long updateANCDoctorData(JsonObject requestOBJ, String Authorization) thr Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1596,7 +1606,7 @@ public Long updateANCDoctorData(JsonObject requestOBJ, String Authorization) thr } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, - isTestPrescribed, isMedicinePrescribed, tcRequestOBJ); + isTestPrescribed, isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = investigationSuccessFlag; else diff --git a/src/main/java/com/iemr/tm/service/benFlowStatus/CommonBenStatusFlowServiceImpl.java b/src/main/java/com/iemr/tm/service/benFlowStatus/CommonBenStatusFlowServiceImpl.java index df561ae9..d905a7a7 100644 --- a/src/main/java/com/iemr/tm/service/benFlowStatus/CommonBenStatusFlowServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/benFlowStatus/CommonBenStatusFlowServiceImpl.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Calendar; +import org.checkerframework.checker.units.qual.s; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -242,11 +243,11 @@ private BeneficiaryFlowStatus getBenFlowRecordObj(String requestOBJ, Long benefi } public int updateBenFlowAfterDocData(Long benFlowID, Long benRegID, Long benID, Long benVisitID, short docFlag, - short pharmaFlag, short oncologistFlag, short tcSpecialistFlag, int tcUserID, Timestamp tcDate,short labTechnicianFlag) { + short pharmaFlag, short oncologistFlag, short tcSpecialistFlag, int tcUserID, Timestamp tcDate,short labTechnicianFlag, Boolean signatureFlag) { int i = 0; try { i = beneficiaryFlowStatusRepo.updateBenFlowStatusAfterDoctorActivity(benFlowID, benRegID, benID, docFlag, - pharmaFlag, oncologistFlag, tcSpecialistFlag, tcUserID, tcDate,labTechnicianFlag); + pharmaFlag, oncologistFlag, tcSpecialistFlag, tcUserID, tcDate,labTechnicianFlag, signatureFlag); } catch (Exception e) { logger.error("Error in ben flow creation = " + e); } @@ -254,11 +255,11 @@ public int updateBenFlowAfterDocData(Long benFlowID, Long benRegID, Long benID, } public int updateBenFlowAfterDocDataFromSpecialist(Long benFlowID, Long benRegID, Long benID, Long benVisitID, - short docFlag, short pharmaFlag, short oncologistFlag, short tcSpecialistFlag,short labTechnicianFlag) { + short docFlag, short pharmaFlag, short oncologistFlag, short tcSpecialistFlag,short labTechnicianFlag, Boolean signatureFlag) { int i = 0; try { i = beneficiaryFlowStatusRepo.updateBenFlowStatusAfterDoctorActivitySpecialist(benFlowID, benRegID, benID, - docFlag, pharmaFlag, oncologistFlag, tcSpecialistFlag,labTechnicianFlag); + docFlag, pharmaFlag, oncologistFlag, tcSpecialistFlag, labTechnicianFlag, signatureFlag); } catch (Exception e) { logger.error("Error in ben flow creation = " + e); } @@ -266,11 +267,11 @@ public int updateBenFlowAfterDocDataFromSpecialist(Long benFlowID, Long benRegID } public int updateBenFlowAfterDocDataFromSpecialistANC(Long benFlowID, Long benRegID, Long benID, Long benVisitID, - short docFlag, short pharmaFlag, short oncologistFlag, short tcSpecialistFlag,short labTechnicianFlag) { + short docFlag, short pharmaFlag, short oncologistFlag, short tcSpecialistFlag,short labTechnicianFlag, Boolean signatureFlag) { int i = 0; try { i = beneficiaryFlowStatusRepo.updateBenFlowStatusAfterDoctorActivitySpecialistANC(benFlowID, benRegID, benID, - docFlag, pharmaFlag, oncologistFlag, tcSpecialistFlag,labTechnicianFlag); + docFlag, pharmaFlag, oncologistFlag, tcSpecialistFlag, labTechnicianFlag, signatureFlag); } catch (Exception e) { logger.error("Error in ben flow creation = " + e); } @@ -279,7 +280,7 @@ public int updateBenFlowAfterDocDataFromSpecialistANC(Long benFlowID, Long benRe public int updateBenFlowAfterDocDataUpdate(Long benFlowID, Long benRegID, Long benID, Long benVisitID, short docFlag, short pharmaFlag, short oncologistFlag, short tcSpecialistFlag, int tcUserID, - Timestamp tcDate,short labTechnicianFlag) throws Exception { + Timestamp tcDate,short labTechnicianFlag, Boolean signatureFlag) throws Exception { int i = 0; try { Short pharmaF = beneficiaryFlowStatusRepo.getPharmaFlag(benFlowID); @@ -291,7 +292,7 @@ public int updateBenFlowAfterDocDataUpdate(Long benFlowID, Long benRegID, Long b pharmaF1 = pharmaFlag; i = beneficiaryFlowStatusRepo.updateBenFlowStatusAfterDoctorActivity(benFlowID, benRegID, benID, docFlag, - pharmaF1, oncologistFlag, tcSpecialistFlag, tcUserID, tcDate,labTechnicianFlag); + pharmaF1, oncologistFlag, tcSpecialistFlag, tcUserID, tcDate, labTechnicianFlag, signatureFlag); } catch (Exception e) { logger.error("Error in ben flow creation = " + e); throw new Exception(e); @@ -301,7 +302,7 @@ public int updateBenFlowAfterDocDataUpdate(Long benFlowID, Long benRegID, Long b public int updateBenFlowAfterDocDataUpdateTCSpecialist(Long benFlowID, Long benRegID, Long benID, Long benVisitID, short docFlag, short pharmaFlag, short oncologistFlag, short tcSpecialistFlag, int tcUserID, - Timestamp tcDate, short labTechnicianFlag) throws Exception { + Timestamp tcDate, short labTechnicianFlag, Boolean signatureFlag) throws Exception { int i = 0; try { Short pharmaF = beneficiaryFlowStatusRepo.getPharmaFlag(benFlowID); @@ -313,7 +314,7 @@ public int updateBenFlowAfterDocDataUpdateTCSpecialist(Long benFlowID, Long benR pharmaF1 = pharmaFlag; i = beneficiaryFlowStatusRepo.updateBenFlowStatusAfterDoctorActivityTCSpecialist(benFlowID, benRegID, benID, - pharmaF1, oncologistFlag, tcSpecialistFlag,labTechnicianFlag); + pharmaF1, oncologistFlag, tcSpecialistFlag, labTechnicianFlag, signatureFlag); } catch (Exception e) { logger.error("Error in ben flow creation = " + e); throw new Exception(e); diff --git a/src/main/java/com/iemr/tm/service/cancerScreening/CSServiceImpl.java b/src/main/java/com/iemr/tm/service/cancerScreening/CSServiceImpl.java index 260a783b..a9bd3575 100644 --- a/src/main/java/com/iemr/tm/service/cancerScreening/CSServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/cancerScreening/CSServiceImpl.java @@ -811,6 +811,12 @@ public Long saveCancerScreeningDoctorData(JsonObject requestOBJ, String Authoriz Long docDataSuccessFlag = null; Long tcRequestStatusFlag = null; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + + if (requestOBJ != null && requestOBJ.has("diagnosis") && !requestOBJ.get("diagnosis").isJsonNull()) { TeleconsultationRequestOBJ tcRequestOBJ = null; @@ -907,7 +913,7 @@ public Long saveCancerScreeningDoctorData(JsonObject requestOBJ, String Authoriz && commonUtilityClass.getIsSpecialist() == true) { l1 = commonBenStatusFlowServiceImpl.updateBenFlowAfterDocDataFromSpecialist(tmpBenFlowID, tmpbeneficiaryRegID, tmpBeneficiaryID, tmpBenVisitID, docFlag, pharmaFalg, oncologistFlag, - tcSpecialistFlag, (short) 0); + tcSpecialistFlag, (short) 0, doctorSignatureFlag); if (tcSpecialistFlag == 9) { int l = tCRequestModelRepo.updateStatusIfConsultationCompleted( @@ -916,7 +922,7 @@ public Long saveCancerScreeningDoctorData(JsonObject requestOBJ, String Authoriz } else { l2 = commonBenStatusFlowServiceImpl.updateBenFlowAfterDocData(tmpBenFlowID, tmpbeneficiaryRegID, tmpBeneficiaryID, tmpBenVisitID, docFlag, pharmaFalg, oncologistFlag, tcSpecialistFlag, - tcUserID, tcDate, (short) 0); + tcUserID, tcDate, (short) 0, doctorSignatureFlag); } if (l1 > 0 || l2 > 0) diff --git a/src/main/java/com/iemr/tm/service/common/transaction/CommonDoctorServiceImpl.java b/src/main/java/com/iemr/tm/service/common/transaction/CommonDoctorServiceImpl.java index 91b18adb..32661569 100644 --- a/src/main/java/com/iemr/tm/service/common/transaction/CommonDoctorServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/common/transaction/CommonDoctorServiceImpl.java @@ -676,11 +676,12 @@ public Long updateBenReferDetails(JsonObject referObj) throws IEMRException { referDetailsList.add(referDetailsTemp); } } - } /* - * else { if (referDetails.getReferredToInstituteName() != null || - * referDetails.getRevisitDate() != null || referDetails.getReferralReason() != - * null) referDetailsList.add(referDetails); } - */ + } else { + if (referDetails.getReferredToInstituteName() != null || + referDetails.getRevisitDate() != null || referDetails.getReferralReason() != null) { + referDetailsList.add(referDetails); + } + } ArrayList res = (ArrayList) benReferDetailsRepo.saveAll(referDetailsList); if (referDetailsList.size() == res.size()) { @@ -701,7 +702,7 @@ public Long updateBenReferDetails(JsonObject referObj) throws IEMRException { /// ------Start of beneficiary flow table after doctor data save------------- public int updateBenFlowtableAfterDocDataSave(CommonUtilityClass commonUtilityClass, Boolean isTestPrescribed, - Boolean isMedicinePrescribed, TeleconsultationRequestOBJ tcRequestOBJ) throws IEMRException { + Boolean isMedicinePrescribed, TeleconsultationRequestOBJ tcRequestOBJ, Boolean signatureFlag) throws IEMRException { short pharmaFalg; short docFlag = (short) 1; short tcSpecialistFlag = (short) 0; @@ -782,7 +783,7 @@ public int updateBenFlowtableAfterDocDataSave(CommonUtilityClass commonUtilityCl // updating lab technician flag as well after feto sense i = commonBenStatusFlowServiceImpl.updateBenFlowAfterDocDataFromSpecialist(tmpBenFlowID, tmpbeneficiaryRegID, tmpBeneficiaryID, tmpBenVisitID, docFlag, pharmaFalg, (short) 0, - tcSpecialistFlag, labTechnicianFlag); + tcSpecialistFlag, labTechnicianFlag,signatureFlag); if (tcSpecialistFlag == 9) { int l = tCRequestModelRepo.updateStatusIfConsultationCompleted(commonUtilityClass.getBeneficiaryRegID(), commonUtilityClass.getVisitCode(), "D"); @@ -807,7 +808,7 @@ public int updateBenFlowtableAfterDocDataSave(CommonUtilityClass commonUtilityCl } else i = commonBenStatusFlowServiceImpl.updateBenFlowAfterDocData(tmpBenFlowID, tmpbeneficiaryRegID, tmpBeneficiaryID, tmpBenVisitID, docFlag, pharmaFalg, (short) 0, tcSpecialistFlag, tcUserID, tcDate, - labTechnicianFlag); + labTechnicianFlag, signatureFlag); // TM Prescription SMS if (commonUtilityClass.getIsSpecialist() == true) { if (tcSpecialistFlag == 9) { @@ -845,7 +846,7 @@ public int updateBenFlowtableAfterDocDataSave(CommonUtilityClass commonUtilityCl * @return */ public int updateBenFlowtableAfterDocDataUpdate(CommonUtilityClass commonUtilityClass, Boolean isTestPrescribed, - Boolean isMedicinePrescribed, TeleconsultationRequestOBJ tcRequestOBJ) throws Exception { + Boolean isMedicinePrescribed, TeleconsultationRequestOBJ tcRequestOBJ, Boolean doctorSignatureFlag) throws Exception { int i = 0; short pharmaFalg; short docFlag = (short) 0; @@ -896,7 +897,7 @@ public int updateBenFlowtableAfterDocDataUpdate(CommonUtilityClass commonUtility i = commonBenStatusFlowServiceImpl.updateBenFlowAfterDocDataUpdateTCSpecialist(tmpBenFlowID, tmpbeneficiaryRegID, tmpBeneficiaryID, tmpBenVisitID, docFlag, pharmaFalg, (short) 0, - tcSpecialistFlag, tcUserID, tcDate, labTechnicianFlag); + tcSpecialistFlag, tcUserID, tcDate, labTechnicianFlag, doctorSignatureFlag); if (tcSpecialistFlag == 9) { int l = tCRequestModelRepo.updateStatusIfConsultationCompleted(commonUtilityClass.getBeneficiaryRegID(), @@ -944,7 +945,7 @@ public int updateBenFlowtableAfterDocDataUpdate(CommonUtilityClass commonUtility i = commonBenStatusFlowServiceImpl.updateBenFlowAfterDocDataUpdate(tmpBenFlowID, tmpbeneficiaryRegID, tmpBeneficiaryID, tmpBenVisitID, docFlag, pharmaFalg, (short) 0, tcSpecialistFlag, tcUserID, tcDate, - labTechnicianFlag); + labTechnicianFlag, doctorSignatureFlag); } diff --git a/src/main/java/com/iemr/tm/service/common/transaction/CommonNurseServiceImpl.java b/src/main/java/com/iemr/tm/service/common/transaction/CommonNurseServiceImpl.java index 3d0248fc..e2f47509 100644 --- a/src/main/java/com/iemr/tm/service/common/transaction/CommonNurseServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/common/transaction/CommonNurseServiceImpl.java @@ -2887,7 +2887,8 @@ private int calculateQtyPrescribed(String form, String dose, String frequency, S if (form != null && dose != null && frequency != null && duration != null && durationUnit != null) { double qtyInOneDay = getQtyForOneDay(form, dose, frequency); - if (frequency.equalsIgnoreCase("Single Dose") || frequency.equalsIgnoreCase("Stat Dose")) { + if (frequency.equalsIgnoreCase("Single Dose") || frequency.equalsIgnoreCase("Stat Dose")|| + frequency.equalsIgnoreCase("Single Dose Before Food") || frequency.equalsIgnoreCase("Single Dose After Food")) { qtyPrescribed = (int) Math.ceil(qtyInOneDay); } else { if (durationUnit.equalsIgnoreCase("Day(s)")) @@ -2906,7 +2907,8 @@ else if (durationUnit.equalsIgnoreCase("Month(s)")) private double getQtyForOneDay(String form, String dose, String frequency) { double qtyInOneDay = 0; if (form != null && dose != null && frequency != null) { - if (frequency.equalsIgnoreCase("Once Daily(OD)")) { + if (frequency.equalsIgnoreCase("Once Daily(OD)") || frequency.equalsIgnoreCase("Once Daily(OD) Before Food")|| + frequency.equalsIgnoreCase("Once Daily(OD) After Food")|| frequency.equalsIgnoreCase("Once Daily(OD) At Bedtime")) { if (form.equalsIgnoreCase("Tablet")) { if (dose.equalsIgnoreCase("Half Tab")) { qtyInOneDay = .5; @@ -2930,7 +2932,8 @@ private double getQtyForOneDay(String form, String dose, String frequency) { } } } else { - if (frequency.equalsIgnoreCase("Twice Daily(BD)")) { + if (frequency.equalsIgnoreCase("Twice Daily(BD)") || frequency.equalsIgnoreCase("Twice Daily(BD) Before Food")|| + frequency.equalsIgnoreCase("Twice Daily(BD) After Food")) { if (form.equalsIgnoreCase("Tablet")) { if (dose.equalsIgnoreCase("Half Tab")) { qtyInOneDay = 1; @@ -2954,7 +2957,8 @@ private double getQtyForOneDay(String form, String dose, String frequency) { } } } else { - if (frequency.equalsIgnoreCase("Thrice Daily (TID)")) { + if (frequency.equalsIgnoreCase("Thrice Daily (TID)") || frequency.equalsIgnoreCase("Thrice Daily (TID) After Food")|| + frequency.equalsIgnoreCase("Thrice Daily (TID) Before Food")) { if (form.equalsIgnoreCase("Tablet")) { if (dose.equalsIgnoreCase("Half Tab")) { qtyInOneDay = 1.5; @@ -2978,7 +2982,8 @@ private double getQtyForOneDay(String form, String dose, String frequency) { } } } else { - if (frequency.equalsIgnoreCase("Four Times in a Day (QID)")) { + if (frequency.equalsIgnoreCase("Four Times in a Day (QID)") || frequency.equalsIgnoreCase("Four Times in a Day AF")|| + frequency.equalsIgnoreCase("Four Times in a Day BF")) { if (form.equalsIgnoreCase("Tablet")) { if (dose.equalsIgnoreCase("Half Tab")) { qtyInOneDay = 2; @@ -3002,7 +3007,8 @@ private double getQtyForOneDay(String form, String dose, String frequency) { } } } else { - if (frequency.equalsIgnoreCase("Single Dose") || frequency.equalsIgnoreCase("Stat Dose")) { + if (frequency.equalsIgnoreCase("Single Dose") || frequency.equalsIgnoreCase("Stat Dose")|| + frequency.equalsIgnoreCase("Single Dose Before Food") || frequency.equalsIgnoreCase("Single Dose After Food")) { if (form.equalsIgnoreCase("Tablet")) { if (dose.equalsIgnoreCase("Half Tab")) { qtyInOneDay = .5; @@ -3026,7 +3032,8 @@ private double getQtyForOneDay(String form, String dose, String frequency) { } } } else { - if (frequency.equalsIgnoreCase("Once in a Week")) { + if (frequency.equalsIgnoreCase("Once in a Week") || frequency.equalsIgnoreCase("Once in a Week After Food") + || frequency.equalsIgnoreCase("Once in a Week Before Food")) { if (form.equalsIgnoreCase("Tablet")) { if (dose.equalsIgnoreCase("Half Tab")) { qtyInOneDay = .07142; diff --git a/src/main/java/com/iemr/tm/service/covid19/Covid19ServiceImpl.java b/src/main/java/com/iemr/tm/service/covid19/Covid19ServiceImpl.java index 0d0e424a..db0adb7f 100644 --- a/src/main/java/com/iemr/tm/service/covid19/Covid19ServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/covid19/Covid19ServiceImpl.java @@ -981,6 +981,11 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1085,7 +1090,7 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) saveSuccessFlag = referSaveSuccessFlag; @@ -1187,6 +1192,12 @@ public Long updateCovid19DoctorData(JsonObject requestOBJ, String Authorization) Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1304,7 +1315,7 @@ public Long updateCovid19DoctorData(JsonObject requestOBJ, String Authorization) } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, - isTestPrescribed, isMedicinePrescribed, tcRequestOBJ); + isTestPrescribed, isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = investigationSuccessFlag; diff --git a/src/main/java/com/iemr/tm/service/generalOPD/GeneralOPDServiceImpl.java b/src/main/java/com/iemr/tm/service/generalOPD/GeneralOPDServiceImpl.java index a74a874f..aa09b486 100644 --- a/src/main/java/com/iemr/tm/service/generalOPD/GeneralOPDServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/generalOPD/GeneralOPDServiceImpl.java @@ -754,6 +754,11 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -857,7 +862,7 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) saveSuccessFlag = investigationSuccessFlag; @@ -1360,6 +1365,11 @@ public Long updateGeneralOPDDoctorData(JsonObject requestOBJ, String Authorizati Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1474,7 +1484,7 @@ public Long updateGeneralOPDDoctorData(JsonObject requestOBJ, String Authorizati } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, - isTestPrescribed, isMedicinePrescribed, tcRequestOBJ); + isTestPrescribed, isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = investigationSuccessFlag; diff --git a/src/main/java/com/iemr/tm/service/ncdCare/NCDCareServiceImpl.java b/src/main/java/com/iemr/tm/service/ncdCare/NCDCareServiceImpl.java index e5754bf6..2076464d 100644 --- a/src/main/java/com/iemr/tm/service/ncdCare/NCDCareServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/ncdCare/NCDCareServiceImpl.java @@ -771,6 +771,11 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -907,7 +912,7 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) saveSuccessFlag = diagnosisSuccessFlag; @@ -1203,6 +1208,11 @@ public Long updateNCDCareDoctorData(JsonObject requestOBJ, String Authorization) Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1312,7 +1322,7 @@ public Long updateNCDCareDoctorData(JsonObject requestOBJ, String Authorization) } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, - isTestPrescribed, isMedicinePrescribed, tcRequestOBJ); + isTestPrescribed, isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = investigationSuccessFlag; diff --git a/src/main/java/com/iemr/tm/service/ncdscreening/NCDSCreeningDoctorServiceImpl.java b/src/main/java/com/iemr/tm/service/ncdscreening/NCDSCreeningDoctorServiceImpl.java index 2b6c8825..b21423b7 100644 --- a/src/main/java/com/iemr/tm/service/ncdscreening/NCDSCreeningDoctorServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/ncdscreening/NCDSCreeningDoctorServiceImpl.java @@ -94,6 +94,11 @@ public int updateDoctorData(JsonObject requestOBJ, String Authorization) throws Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -188,7 +193,7 @@ public int updateDoctorData(JsonObject requestOBJ, String Authorization) throws // call method to update beneficiary flow table int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, - isTestPrescribed, isMedicinePrescribed, tcRequestOBJ); + isTestPrescribed, isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = 1; diff --git a/src/main/java/com/iemr/tm/service/ncdscreening/NCDScreeningServiceImpl.java b/src/main/java/com/iemr/tm/service/ncdscreening/NCDScreeningServiceImpl.java index 0f750746..dc91a21a 100644 --- a/src/main/java/com/iemr/tm/service/ncdscreening/NCDScreeningServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/ncdscreening/NCDScreeningServiceImpl.java @@ -1023,6 +1023,11 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1119,7 +1124,7 @@ public Long saveDoctorData(JsonObject requestOBJ, String Authorization) throws E } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) saveSuccessFlag = investigationSuccessFlag; diff --git a/src/main/java/com/iemr/tm/service/pnc/PNCServiceImpl.java b/src/main/java/com/iemr/tm/service/pnc/PNCServiceImpl.java index 6fe25634..7ad63321 100644 --- a/src/main/java/com/iemr/tm/service/pnc/PNCServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/pnc/PNCServiceImpl.java @@ -315,6 +315,11 @@ public Long savePNCDoctorData(JsonObject requestOBJ, String Authorization) throw Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -416,7 +421,7 @@ public Long savePNCDoctorData(JsonObject requestOBJ, String Authorization) throw } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) saveSuccessFlag = diagnosisSuccessFlag; @@ -1381,6 +1386,11 @@ public Long updatePNCDoctorData(JsonObject requestOBJ, String Authorization) thr Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (requestOBJ.has("doctorSignatureFlag") && !requestOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = requestOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // checking if test is prescribed if (requestOBJ.has("investigation") && !requestOBJ.get("investigation").isJsonNull() && requestOBJ.get("investigation") != null) { @@ -1489,7 +1499,7 @@ public Long updatePNCDoctorData(JsonObject requestOBJ, String Authorization) thr } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, - isTestPrescribed, isMedicinePrescribed, tcRequestOBJ); + isTestPrescribed, isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = investigationSuccessFlag; diff --git a/src/main/java/com/iemr/tm/service/quickConsultation/QuickConsultationServiceImpl.java b/src/main/java/com/iemr/tm/service/quickConsultation/QuickConsultationServiceImpl.java index 8176b158..9ca3e73a 100644 --- a/src/main/java/com/iemr/tm/service/quickConsultation/QuickConsultationServiceImpl.java +++ b/src/main/java/com/iemr/tm/service/quickConsultation/QuickConsultationServiceImpl.java @@ -339,6 +339,11 @@ public Integer quickConsultDoctorDataInsert(JsonObject quickConsultDoctorOBJ, St if (drugList != null && !drugList.isJsonNull() && drugList.size() > 0) isMedicinePrescribed = true; + Boolean doctorSignatureFlag = false; + if (quickConsultDoctorOBJ.has("doctorSignatureFlag") && !quickConsultDoctorOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = quickConsultDoctorOBJ.get("doctorSignatureFlag").getAsBoolean(); + } + // save prescribed medicine if (isMedicinePrescribed) { @@ -414,7 +419,7 @@ public Integer quickConsultDoctorDataInsert(JsonObject quickConsultDoctorOBJ, St } // call method to update beneficiary flow table int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataSave(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) returnOBJ = 1; @@ -521,6 +526,10 @@ public Long updateGeneralOPDQCDoctorData(JsonObject quickConsultDoctorOBJ, Strin Boolean isTestPrescribed = false; Boolean isMedicinePrescribed = false; + Boolean doctorSignatureFlag = false; + if (quickConsultDoctorOBJ.has("doctorSignatureFlag") && !quickConsultDoctorOBJ.get("doctorSignatureFlag").isJsonNull()) { + doctorSignatureFlag = quickConsultDoctorOBJ.get("doctorSignatureFlag").getAsBoolean(); + } // checking if test is prescribed if (quickConsultDoctorOBJ.has("labTestOrders")) { testList = quickConsultDoctorOBJ.getAsJsonArray("labTestOrders"); @@ -609,7 +618,7 @@ public Long updateGeneralOPDQCDoctorData(JsonObject quickConsultDoctorOBJ, Strin } int i = commonDoctorServiceImpl.updateBenFlowtableAfterDocDataUpdate(commonUtilityClass, isTestPrescribed, - isMedicinePrescribed, tcRequestOBJ); + isMedicinePrescribed, tcRequestOBJ, doctorSignatureFlag); if (i > 0) updateSuccessFlag = benChiefComplaintID; diff --git a/src/main/java/com/iemr/tm/utils/CookieUtil.java b/src/main/java/com/iemr/tm/utils/CookieUtil.java index b20d6256..1faea949 100644 --- a/src/main/java/com/iemr/tm/utils/CookieUtil.java +++ b/src/main/java/com/iemr/tm/utils/CookieUtil.java @@ -12,7 +12,7 @@ @Service public class CookieUtil { - public Optional getCookieValue(HttpServletRequest request, String cookieName) { + public static Optional getCookieValue(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { @@ -36,4 +36,11 @@ public static String getJwtTokenFromCookie(HttpServletRequest request) { .findFirst() .orElse(null); } + + /** + * Get auth token from cookies (for legacy support) + */ + public static String getAuthTokenFromCookie(HttpServletRequest request) { + return getCookieValue(request, "Authorization").orElse(null); + } } diff --git a/src/main/java/com/iemr/tm/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/tm/utils/JwtAuthenticationUtil.java index cd32bea1..d266bf02 100644 --- a/src/main/java/com/iemr/tm/utils/JwtAuthenticationUtil.java +++ b/src/main/java/com/iemr/tm/utils/JwtAuthenticationUtil.java @@ -1,5 +1,6 @@ package com.iemr.tm.utils; +import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; @@ -130,4 +131,18 @@ private Users fetchUserFromDB(String userId) { return null; } + public List getUserRoles(Long userId) throws IEMRException { + if (null == userId || userId <= 0) { + throw new IEMRException("Invalid User ID : " + userId); + } + try { + List role = userLoginRepo.getRoleNamebyUserId(userId); + if (null == role || role.isEmpty()) { + throw new IEMRException("No role found for userId : " + userId); + } + return role; + } catch (Exception e) { + throw new IEMRException("Failed to retrieverole for usedId : " + userId + " error : " + e.getMessage()); + } + } } diff --git a/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java index 23dd21a8..1835cb9b 100644 --- a/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/tm/utils/JwtUserIdValidationFilter.java @@ -37,28 +37,46 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo HttpServletResponse response = (HttpServletResponse) servletResponse; String origin = request.getHeader("Origin"); + String method = request.getMethod(); + String uri = request.getRequestURI(); logger.debug("Incoming Origin: {}", origin); logger.debug("Allowed Origins Configured: {}", allowedOrigins); + if ("OPTIONS".equalsIgnoreCase(method)) { + if (origin == null) { + logger.warn("BLOCKED - OPTIONS request without Origin header | Method: {} | URI: {}", method, uri); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "OPTIONS request requires Origin header"); + return; + } + if (!isOriginAllowed(origin)) { + logger.warn("BLOCKED - Unauthorized Origin | Origin: {} | Method: {} | URI: {}", origin, method, uri); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); + return; + } + } else { + // For non-OPTIONS requests, validate origin if present + if (origin != null && !isOriginAllowed(origin)) { + logger.warn("BLOCKED - Unauthorized Origin | Origin: {} | Method: {} | URI: {}", origin, method, uri); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); + return; + } + } + + String path = request.getRequestURI(); + String contextPath = request.getContextPath(); if (origin != null && isOriginAllowed(origin)) { - response.setHeader("Access-Control-Allow-Origin", origin); - response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); - response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken"); - response.setHeader("Vary", "Origin"); + response.setHeader("Access-Control-Allow-Origin", origin); // Never use wildcard + response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS"); + response.setHeader("Access-Control-Allow-Headers", + "Authorization, Content-Type, Accept, Jwttoken, serverAuthorization, ServerAuthorization, serverauthorization, Serverauthorization"); response.setHeader("Access-Control-Allow-Credentials", "true"); + response.setHeader("Access-Control-Max-Age", "3600"); + logger.info("Origin Validated | Origin: {} | Method: {} | URI: {}", origin, method, uri); } else { logger.warn("Origin [{}] is NOT allowed. CORS headers NOT added.", origin); } - if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { - logger.info("OPTIONS request - skipping JWT validation"); - response.setStatus(HttpServletResponse.SC_OK); - return; - } - - String path = request.getRequestURI(); - String contextPath = request.getContextPath(); logger.info("JwtUserIdValidationFilter invoked for path: " + path); // Log cookies for debugging @@ -143,7 +161,7 @@ private boolean isOriginAllowed(String origin) { String regex = pattern .replace(".", "\\.") .replace("*", ".*") - .replace("http://localhost:.*", "http://localhost:\\d+"); // special case for wildcard port + .replace("http://localhost:.*", "http://localhost:\\d+"); boolean matched = origin.matches(regex); return matched; diff --git a/src/main/java/com/iemr/tm/utils/JwtUtil.java b/src/main/java/com/iemr/tm/utils/JwtUtil.java index 2639896e..5d3d7561 100644 --- a/src/main/java/com/iemr/tm/utils/JwtUtil.java +++ b/src/main/java/com/iemr/tm/utils/JwtUtil.java @@ -59,11 +59,20 @@ public T extractClaim(String token, Function claimsResolver) { return claims != null ? claimsResolver.apply(claims) : null; } - private Claims extractAllClaims(String token) { + public Claims extractAllClaims(String token) { return Jwts.parser() .verifyWith(getSigningKey()) .build() .parseSignedClaims(token) .getPayload(); } + + public String getUserIdFromToken(String token) { + Claims claims = validateToken(token); + if (claims == null) { + return null; + } + return claims.get("userId", String.class); + } } + diff --git a/src/main/java/com/iemr/tm/utils/exception/CustomAccessDeniedHandler.java b/src/main/java/com/iemr/tm/utils/exception/CustomAccessDeniedHandler.java new file mode 100644 index 00000000..ff62fc62 --- /dev/null +++ b/src/main/java/com/iemr/tm/utils/exception/CustomAccessDeniedHandler.java @@ -0,0 +1,28 @@ +package com.iemr.tm.utils.exception; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.Map; + +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + private static final ObjectMapper mapper = new ObjectMapper(); + @Override + public void handle(HttpServletRequest request, + HttpServletResponse response, + AccessDeniedException accessDeniedException) throws IOException { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 + response.setContentType("application/json"); + Map errorResponse = Map.of("error" , "Forbidden", + "message","Access denied"); + response.getWriter().write(mapper.writeValueAsString(errorResponse)); + } +} \ No newline at end of file diff --git a/src/main/java/com/iemr/tm/utils/exception/CustomAuthenticationEntryPoint.java b/src/main/java/com/iemr/tm/utils/exception/CustomAuthenticationEntryPoint.java new file mode 100644 index 00000000..df622dfb --- /dev/null +++ b/src/main/java/com/iemr/tm/utils/exception/CustomAuthenticationEntryPoint.java @@ -0,0 +1,23 @@ +package com.iemr.tm.utils.exception; + +import java.io.IOException; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, + AuthenticationException authException) throws IOException { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 + response.setContentType("application/json"); + response.getWriter().write("{\"error\": \"Unauthorized\", \"message\": \"" + authException.getMessage() + "\"}"); + } +} \ No newline at end of file diff --git a/src/main/java/com/iemr/tm/utils/http/HTTPRequestInterceptor.java b/src/main/java/com/iemr/tm/utils/http/HTTPRequestInterceptor.java index 2da14401..f8160d83 100644 --- a/src/main/java/com/iemr/tm/utils/http/HTTPRequestInterceptor.java +++ b/src/main/java/com/iemr/tm/utils/http/HTTPRequestInterceptor.java @@ -21,11 +21,14 @@ */ package com.iemr.tm.utils.http; +import java.util.Arrays; + import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.HandlerInterceptor; @@ -39,6 +42,9 @@ @Component public class HTTPRequestInterceptor implements HandlerInterceptor { Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + @Value("${cors.allowed-origins}") + private String allowedOrigins; private SessionObject sessionObject; @@ -95,7 +101,13 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons response.getOutputStream().print(output.toString()); response.setContentType(MediaType.APPLICATION_JSON); response.setContentLength(output.toString().length()); - response.setHeader("Access-Control-Allow-Origin", "*"); + String origin = request.getHeader("Origin"); + if (origin != null && isOriginAllowed(origin)) { + response.setHeader("Access-Control-Allow-Origin", origin); + response.setHeader("Access-Control-Allow-Credentials", "true"); + } else if (origin != null) { + logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin); + } status = false; } } @@ -126,4 +138,27 @@ public void afterCompletion(HttpServletRequest request, HttpServletResponse resp throws Exception { logger.debug("In afterCompletion Request Completed"); } -} \ No newline at end of file + + /** + * Check if the given origin is allowed based on configured allowedOrigins. + * Uses the same logic as JwtUserIdValidationFilter for consistency. + * + * @param origin The origin to validate + * @return true if origin is allowed, false otherwise + */ + private boolean isOriginAllowed(String origin) { + if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) { + return false; + } + + return Arrays.stream(allowedOrigins.split(",")) + .map(String::trim) + .anyMatch(pattern -> { + String regex = pattern + .replace(".", "\\.") + .replace("*", ".*") + .replace("http://localhost:.*", "http://localhost:\\d+"); + return origin.matches(regex); + }); + } +} diff --git a/src/main/java/com/iemr/tm/utils/mapper/RoleAuthenticationFilter.java b/src/main/java/com/iemr/tm/utils/mapper/RoleAuthenticationFilter.java new file mode 100644 index 00000000..168f684c --- /dev/null +++ b/src/main/java/com/iemr/tm/utils/mapper/RoleAuthenticationFilter.java @@ -0,0 +1,166 @@ +package com.iemr.tm.utils.mapper; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import com.iemr.tm.utils.CookieUtil; +import com.iemr.tm.utils.JwtAuthenticationUtil; +import com.iemr.tm.utils.JwtUtil; +import com.iemr.tm.utils.redis.RedisStorage; + +import io.jsonwebtoken.Claims; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class RoleAuthenticationFilter extends OncePerRequestFilter { + + private static final Logger logger + = LoggerFactory.getLogger(RoleAuthenticationFilter.class); + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private RedisStorage redisService; + + @Autowired + private JwtAuthenticationUtil userService; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) + throws ServletException, java.io.IOException { + + try { + Long userId = null; + + /* ======================= + * TRY JWT TOKEN FIRST + * ======================= */ + String jwtToken + = CookieUtil.getJwtTokenFromCookie(request) != null + ? CookieUtil.getJwtTokenFromCookie(request) + : request.getHeader("Jwttoken"); + + if (jwtToken != null && !jwtToken.isBlank()) { + Claims claims = jwtUtil.validateToken(jwtToken); + if (claims != null && claims.get("userId") != null) { + userId = Long.valueOf(claims.get("userId").toString()); + logger.info("UserId resolved from JWT: {}", userId); + } + } + + /* ================================= + * FALLBACK → LEGACY AUTH + REDIS + * ================================= */ + if (userId == null) { + String authToken = resolveAuthToken(request); + logger.info("Resolved authToken: {}", authToken); + + if (authToken != null && !authToken.isBlank()) { + String sessionJson = null; + try { + sessionJson = redisService.getObject(authToken, true, 100000); + } catch (Exception ex) { + logger.warn("No Redis session found for authToken: {}", authToken); + filterChain.doFilter(request, response); + return; + } + + if (sessionJson != null && !sessionJson.isBlank()) { + JSONObject json = new JSONObject(sessionJson); + + if (json.has("userID")) { + userId = json.getLong("userID"); + logger.info("UserId resolved from Redis: {}", userId); + } + } + } + } + + /* ======================= + * NO USER → SKIP + * ======================= */ + if (userId == null) { + logger.debug("No userId resolved, skipping authentication"); + filterChain.doFilter(request, response); + return; + } + + /* ======================= + * LOAD USER ROLES + * ======================= */ + List authRoles + = redisService.getUserRoleFromCache(userId); + + if (authRoles == null || authRoles.isEmpty()) { + authRoles = userService.getUserRoles(userId) + .stream() + .filter(Objects::nonNull) + .map(String::trim) + .map(r -> "ROLE_" + r.toUpperCase().replace(" ", "_")) + .collect(Collectors.toList()); + + redisService.cacheUserRoles(userId, authRoles); + } + + /* ======================= + * SET SECURITY CONTEXT + * ======================= */ + List authorities = authRoles.stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + UsernamePasswordAuthenticationToken authentication + = new UsernamePasswordAuthenticationToken( + userId, null, authorities); + + SecurityContextHolder.getContext() + .setAuthentication(authentication); + + logger.info("Authentication set for userId {}", userId); + + } catch (Exception e) { + logger.error("Authentication error", e); + SecurityContextHolder.clearContext(); + } + + filterChain.doFilter(request, response); + } + + /* ======================= + * AUTH TOKEN RESOLVER + * ======================= */ + private String resolveAuthToken(HttpServletRequest request) { + + String token = request.getHeader("Authorization"); + + if (token == null || token.isBlank()) { + token = request.getHeader("AuthToken"); + } + if (token == null || token.isBlank()) { + token = request.getHeader("X-Auth-Token"); + } + if (token == null || token.isBlank()) { + token = CookieUtil.getCookieValue(request, "Authorization") + .orElse(null); + } + return token; + } +} diff --git a/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java b/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java new file mode 100644 index 00000000..ed74da7b --- /dev/null +++ b/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java @@ -0,0 +1,53 @@ +package com.iemr.tm.utils.mapper; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; + +import com.iemr.tm.utils.exception.CustomAccessDeniedHandler; +import com.iemr.tm.utils.exception.CustomAuthenticationEntryPoint; + + +@Configuration +@EnableMethodSecurity +@EnableWebSecurity +public class SecurityConfig { + private final RoleAuthenticationFilter roleAuthenticationFilter; + private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; + private final CustomAccessDeniedHandler customAccessDeniedHandler; + + public SecurityConfig(RoleAuthenticationFilter roleAuthenticationFilter, + CustomAuthenticationEntryPoint customAuthenticationEntryPoint, + CustomAccessDeniedHandler customAccessDeniedHandler) { + this.roleAuthenticationFilter = roleAuthenticationFilter; + this.customAuthenticationEntryPoint = customAuthenticationEntryPoint; + this.customAccessDeniedHandler = customAccessDeniedHandler; + } + +@Bean +public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + CookieCsrfTokenRepository csrfTokenRepository = new CookieCsrfTokenRepository(); + csrfTokenRepository.setCookieHttpOnly(true); + csrfTokenRepository.setCookiePath("/"); + http + .csrf(csrf -> csrf.disable()) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/user/*").permitAll() + .anyRequest().authenticated() + ) + .exceptionHandling(ex -> ex + .authenticationEntryPoint(customAuthenticationEntryPoint) + .accessDeniedHandler(customAccessDeniedHandler) + ) + .addFilterBefore(roleAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); +} +} diff --git a/src/main/java/com/iemr/tm/utils/redis/RedisStorage.java b/src/main/java/com/iemr/tm/utils/redis/RedisStorage.java index 49b2c586..69fa170a 100644 --- a/src/main/java/com/iemr/tm/utils/redis/RedisStorage.java +++ b/src/main/java/com/iemr/tm/utils/redis/RedisStorage.java @@ -21,12 +21,15 @@ */ package com.iemr.tm.utils.redis; +import java.util.List; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisStringCommands.SetOption; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.types.Expiration; import org.springframework.stereotype.Component; @@ -92,4 +95,28 @@ public String updateObject(String key, String value, Boolean extendExpirationTim return key; } + + @Autowired + private RedisTemplate redisTemplate; + + public void cacheUserRoles(Long userId, List roles) { + try { + String key = "roles:" + userId; + redisTemplate.delete(key); // Clear previous cache + redisTemplate.opsForList().rightPushAll(key, roles); + redisTemplate.expire(key, 30, java.util.concurrent.TimeUnit.MINUTES); + } catch (Exception e) { + logger.warn("Failed to cache role for user {} : {} ", userId, e.getMessage()); + } + + } + + public List getUserRoleFromCache(Long userId) { + try { + return redisTemplate.opsForList().range("roles:" + userId, 0, -1); + } catch (Exception e) { + logger.warn("Failed to retrieve cached role for user {} : {} ", userId, e.getMessage()); + return null; + } + } } From 8202dbaec5b20d24edcc8fa443c18b5a1f0132d5 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Tue, 24 Mar 2026 18:40:00 +0530 Subject: [PATCH 6/6] feat(security): update security configuration to permit health and version apis --- src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java b/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java index ed74da7b..ab86b05b 100644 --- a/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java +++ b/src/main/java/com/iemr/tm/utils/mapper/SecurityConfig.java @@ -40,6 +40,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers("/user/*").permitAll() + .requestMatchers("/health").permitAll() + .requestMatchers("/version").permitAll() .anyRequest().authenticated() ) .exceptionHandling(ex -> ex