diff --git a/.github/workflows/db-test.yml b/.github/workflows/db-test.yml
new file mode 100644
index 00000000000..262b7c24eea
--- /dev/null
+++ b/.github/workflows/db-test.yml
@@ -0,0 +1,37 @@
+name: PostgreSQL Test
+
+on:
+ release:
+ types: [published]
+ pull_request:
+ types: [opened, reopened, synchronize]
+ workflow_dispatch:
+ inputs:
+ message:
+ description: 'Message for manually triggering'
+ required: false
+ default: 'Triggered for Updates'
+ type: string
+ push:
+ branches:
+ - '!release-branch'
+ - release*
+ - master
+ - 1.*
+ - develop*
+ - MOSIP*
+ paths:
+ - 'db_scripts/**'
+
+jobs:
+ build-db-test:
+ strategy:
+ matrix:
+ include:
+ - DB_LOCATION: 'db_scripts/mosip_ida'
+ DB_NAME: 'mosip_ida'
+ fail-fast: false
+ name: ${{ matrix.DB_NAME }}
+ uses: mosip/kattu/.github/workflows/db-test.yml@master
+ with:
+ DB_LOCATION: ${{ matrix.DB_LOCATION}}
diff --git a/.github/workflows/postgres-init_trigger.yml b/.github/workflows/postgres-init_trigger.yml
deleted file mode 100644
index 3de4c6f32c5..00000000000
--- a/.github/workflows/postgres-init_trigger.yml
+++ /dev/null
@@ -1,83 +0,0 @@
-name: Trigger postgres-init repo upon db scripts updates
-
-on:
- push:
- branches:
- - master
- - 1.*
- - develop
- - release*
- paths:
- - db_release_scripts/**
- - db_scripts/**
-
-jobs:
- paths-filter:
- runs-on: ubuntu-latest
- outputs:
- db_release_scripts: ${{ steps.filter.outputs.db_release_scripts }}
- db_scripts: ${{ steps.filter.outputs.db_scripts }}
- steps:
- - uses: actions/checkout@v2
- - uses: dorny/paths-filter@v2
- id: filter
- with:
- base: ${{ github.ref }}
- filters: |
- db_release_scripts:
- - 'db_release_scripts/**'
- db_scripts:
- - 'db_scripts/**'
-
- # run only if 'db_release_scripts' files were changed
- db_release_scripts_updates:
- needs: paths-filter
- if: needs.paths-filter.outputs.db_release_scripts == 'true'
- runs-on: ubuntu-latest
- steps:
- - name: Check for updates
- run: echo "Updates are present in db_release_scripts directory, Triggering postgres-init repo"
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required
- if: success() # Pick up events when the job is successful.
-
- # run only if not 'db_release_scripts' files were changed
- - name: Check for no updates
- if: needs.paths-filter.outputs.db_release_scripts != 'true'
- run: echo "Updates are not present in db_release_scripts directory"
-
- # run only if 'db_scripts' files were changed
- db_scripts_updates:
- needs: paths-filter
- if: needs.paths-filter.outputs.db_scripts == 'true'
- runs-on: ubuntu-latest
- steps:
- - name: Check for updates
- run: echo "Updates are present in db_scripts directory, Triggering postgres-init repo"
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required
- if: success() # Pick up events when the job is successful.
-
- # run only if not 'db_scripts' files were changed
- - name: Check for no updates
- if: needs.paths-filter.outputs.db_scripts != 'true'
- run: echo "Updates are not present in db_scripts directory"
-
- # This job is to trigger postgres-init repo.
- trigger-postgres_init_repo:
- runs-on: ubuntu-latest
- steps:
- - uses: peter-evans/repository-dispatch@v2
- with:
- token: ${{ secrets.ACTION_PAT }}
- repository: mosip/postgres-init
- base: ${{ github.ref }}
- event-type: db-event
diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml
new file mode 100644
index 00000000000..da2a570e147
--- /dev/null
+++ b/.github/workflows/push-trigger.yml
@@ -0,0 +1,91 @@
+name: Maven Package upon a push
+
+on:
+ release:
+ types: [published]
+ pull_request:
+ types: [opened, reopened, synchronize]
+ workflow_dispatch:
+ inputs:
+ message:
+ description: 'Message for manually triggering'
+ required: false
+ default: 'Triggered for Updates'
+ type: string
+ push:
+ branches:
+ - '!release-branch'
+ - release*
+ - master
+ - 1.*
+ - develop
+ - MOSIP*
+
+jobs:
+ build-maven-authentication:
+ uses: mosip/kattu/.github/workflows/maven-build.yml@master
+ with:
+ SERVICE_LOCATION: ./authentication
+ BUILD_ARTIFACT: authentication
+ secrets:
+ OSSRH_USER: ${{ secrets.OSSRH_USER }}
+ OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }}
+ OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }}
+ GPG_SECRET: ${{ secrets.GPG_SECRET }}
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
+
+ publish_to_nexus:
+ if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}"
+ needs: build-maven-authentication
+ uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master
+ with:
+ SERVICE_LOCATION: ./authentication
+ secrets:
+ OSSRH_USER: ${{ secrets.OSSRH_USER }}
+ OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }}
+ OSSRH_URL: ${{ secrets.RELEASE_URL }}
+ OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }}
+ GPG_SECRET: ${{ secrets.GPG_SECRET }}
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
+
+ build-dockers:
+ needs: build-maven-authentication
+ strategy:
+ matrix:
+ include:
+ - SERVICE_LOCATION: 'authentication/authentication-otp-service'
+ SERVICE_NAME: 'authentication-otp-service'
+ BUILD_ARTIFACT: 'authentication'
+ - SERVICE_LOCATION: 'authentication/authentication-internal-service'
+ SERVICE_NAME: 'authentication-internal-service'
+ BUILD_ARTIFACT: 'authentication'
+ - SERVICE_LOCATION: 'authentication/authentication-service'
+ SERVICE_NAME: 'authentication-service'
+ BUILD_ARTIFACT: 'authentication'
+ fail-fast: false
+ name: ${{ matrix.SERVICE_NAME }}
+ uses: mosip/kattu/.github/workflows/docker-build.yml@master
+ with:
+ SERVICE_LOCATION: ${{ matrix.SERVICE_LOCATION }}
+ SERVICE_NAME: ${{ matrix.SERVICE_NAME }}
+ BUILD_ARTIFACT: ${{ matrix.BUILD_ARTIFACT }}
+ secrets:
+ DEV_NAMESPACE_DOCKER_HUB: ${{ secrets.DEV_NAMESPACE_DOCKER_HUB }}
+ ACTOR_DOCKER_HUB: ${{ secrets.ACTOR_DOCKER_HUB }}
+ RELEASE_DOCKER_HUB: ${{ secrets.RELEASE_DOCKER_HUB }}
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
+
+ sonar_analysis:
+ needs: build-maven-authentication
+ if: "${{ github.event_name != 'pull_request' }}"
+ uses: mosip/kattu/.github/workflows/maven-sonar-analysis.yml@master
+ with:
+ SERVICE_LOCATION: ./authentication
+ secrets:
+ SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
+ ORG_KEY: ${{ secrets.ORG_KEY }}
+ OSSRH_USER: ${{ secrets.OSSRH_USER }}
+ OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }}
+ OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }}
+ GPG_SECRET: ${{ secrets.GPG_SECRET }}
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml
deleted file mode 100644
index 106b5158e8a..00000000000
--- a/.github/workflows/push_trigger.yml
+++ /dev/null
@@ -1,377 +0,0 @@
-
-name: Maven Package upon a push
-
-on:
- push:
- branches:
- - '!release-branch'
- - release-1*
- - master
- - 1.*
- - develop
-
-jobs:
- build:
-
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Set up JDK 11
- uses: actions/setup-java@v1
- with:
- ref: ${{ github.ref }}
- java-version: 11
- server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
- settings-path: ${{ github.workspace }} # location for the settings.xml file
-
- - name: Setup branch and env
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
- echo "GPG_TTY=$(tty)" >> $GITHUB_ENV
-
- - name: Setup branch and GPG public key
- run: |
- # Strip git ref prefix from version
- echo ${{ env.BRANCH_NAME }}
- echo ${{ env.GPG_TTY }}
- sudo apt-get --yes install gnupg2
- gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg
- gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg
-
- - uses: actions/cache@v1
- with:
- path: ~/.m2/repository
- key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- ${{ runner.os }}-maven-${{ env.BRANCH_NAME }}
-
- - name: Setup the settings file for ossrh server
- run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml
-
- - name: Build with Maven
- run: |
- cd authentication
- mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml -e
-
- - name: Ready the springboot artifacts
- run: find -name '*.jar' -executable -type f -exec zip release.zip {} +
-
- - name: Upload the springboot jars
- uses: actions/upload-artifact@v1
- with:
- name: release
- path: ./release.zip
-
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,workflow,job # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required
- if: failure() # Pick up events even if the job fails or is canceled.
-
- publish_to_nexus:
- if: "!contains(github.ref, 'master')"
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Set up JDK 11
- uses: actions/setup-java@v1
- with:
- ref: ${{ github.ref }}
- java-version: 11
- server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
- settings-path: ${{ github.workspace }} # location for the settings.xml file
-
- - name: Setup branch and env
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
- echo "GPG_TTY=$(tty)" >> $GITHUB_ENV
-
- - name: Setup branch and GPG public key
- run: |
- # Strip git ref prefix from version
- echo ${{ env.BRANCH_NAME }}
- echo ${{ env.GPG_TTY }}
- sudo apt-get --yes install gnupg2
- gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg
- gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --always-trust --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg
-
- - uses: actions/cache@v1
- with:
- path: ~/.m2/repository
- key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- ${{ runner.os }}-maven-${{ env.BRANCH_NAME }}
-
- - name: Install xmllint
- run: |
- sudo apt-get update
- sudo apt-get install libxml2-utils
-
- - name: Setup the settings file for ossrh server
- run: echo " ossrh ${{secrets.RELEASE_USER}} ${{secrets.RELEASE_TOKEN}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml
-
- - name: Build with Maven
- run: |
- cd authentication
- mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml
-
- - name: Publish the maven package
- run: |
- cd authentication && mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.OSSRH_SNAPSHOT_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml
- env:
- GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
- GPG_TTY: $(tty)
- # - uses: 8398a7/action-slack@v3
- # with:
- # status: ${{ job.status }}
- # fields: repo,message,commit,workflow,job # selectable (default: repo,message)
- # env:
- # SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
- # if: failure() # Pick up events even if the job fails or is canceled.
-
- docker-authentication-otp-service:
- needs: build
-
- runs-on: ubuntu-latest
- env:
- NAMESPACE: ${{ secrets.dev_namespace_docker_hub }}
- SERVICE_NAME: authentication-otp-service
- SERVICE_LOCATION: authentication/authentication-otp-service
-
- steps:
- - uses: actions/checkout@v2
- - uses: actions/download-artifact@v1
- with:
- name: release
- path: ./
-
- - name: Setup branch name
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
-
- - name: Get version info from pom
- id: getPomVersion
- uses: mavrosxristoforos/get-xml-info@1.0
- with:
- xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml
- xpath: /*[local-name()="project"]/*[local-name()="version"]
-
- - name: Unzip and extract the authentication-otp-service
- run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target"
- - name: Get current date
- id: date
- run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
-
- - name: Build image
- run: |
- cd "./${{env.SERVICE_LOCATION}}"
- docker build . --file Dockerfile --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --tag ${{ env.SERVICE_NAME }}
- - name: Log into registry
- run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin
-
- - name: Push image
- run: |
- IMAGE_ID=$NAMESPACE/$SERVICE_NAME
-
- # Change all uppercase to lowercase
- IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- echo "push version ${{steps.getPomVersion.outputs.info}}"
- if [[ $BRANCH_NAME == master ]]; then
- VERSION=latest
- else
- VERSION=$BRANCH_NAME
- fi
- echo IMAGE_ID=$IMAGE_ID
- echo VERSION=$VERSION
- docker tag $SERVICE_NAME $IMAGE_ID:$VERSION
- docker push $IMAGE_ID:$VERSION
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,workflow,job # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
- if: failure() # Pick up events even if the job fails or is canceled.
-
- docker-authentication-internal-service:
- needs: build
-
- runs-on: ubuntu-latest
- env:
- NAMESPACE: ${{ secrets.dev_namespace_docker_hub }}
- SERVICE_NAME: authentication-internal-service
- SERVICE_LOCATION: authentication/authentication-internal-service
-
- steps:
- - uses: actions/checkout@v2
- - uses: actions/download-artifact@v1
- with:
- name: release
- path: ./
-
- - name: Setup branch name
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
-
- - name: Get version info from pom
- id: getPomVersion
- uses: mavrosxristoforos/get-xml-info@1.0
- with:
- xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml
- xpath: /*[local-name()="project"]/*[local-name()="version"]
-
- - name: Unzip and extract the authentication-internal-service
- run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target"
- - name: Get current date
- id: date
- run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
-
- - name: Build image
- run: |
- cd "./${{env.SERVICE_LOCATION}}"
- docker build . --file Dockerfile --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --tag ${{ env.SERVICE_NAME }}
- - name: Log into registry
- run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin
-
- - name: Push image
- run: |
- IMAGE_ID=$NAMESPACE/$SERVICE_NAME
-
- # Change all uppercase to lowercase
- IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- echo "push version ${{steps.getPomVersion.outputs.info}}"
- if [[ $BRANCH_NAME == master ]]; then
- VERSION=latest
- else
- VERSION=$BRANCH_NAME
- fi
- echo IMAGE_ID=$IMAGE_ID
- echo VERSION=$VERSION
- docker tag $SERVICE_NAME $IMAGE_ID:$VERSION
- docker push $IMAGE_ID:$VERSION
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,workflow,job # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
- if: failure() # Pick up events even if the job fails or is canceled.
-
- docker-authentication-service:
- needs: build
-
- runs-on: ubuntu-latest
- env:
- NAMESPACE: ${{ secrets.dev_namespace_docker_hub }}
- SERVICE_NAME: authentication-service
- SERVICE_LOCATION: authentication/authentication-service
-
- steps:
- - uses: actions/checkout@v2
- - uses: actions/download-artifact@v1
- with:
- name: release
- path: ./
-
- - name: Setup branch name
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
-
- - name: Get version info from pom
- id: getPomVersion
- uses: mavrosxristoforos/get-xml-info@1.0
- with:
- xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml
- xpath: /*[local-name()="project"]/*[local-name()="version"]
-
- - name: Unzip and extract the authentication-service
- run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target"
- - name: Get current date
- id: date
- run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
-
- - name: Build image
- run: |
- cd "./${{env.SERVICE_LOCATION}}"
- docker build . --file Dockerfile --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --tag ${{ env.SERVICE_NAME }}
- - name: Log into registry
- run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin
-
- - name: Push image
- run: |
- IMAGE_ID=$NAMESPACE/$SERVICE_NAME
-
- # Change all uppercase to lowercase
- IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- echo "push version ${{steps.getPomVersion.outputs.info}}"
- if [[ $BRANCH_NAME == master ]]; then
- VERSION=latest
- else
- VERSION=$BRANCH_NAME
- fi
- echo IMAGE_ID=$IMAGE_ID
- echo VERSION=$VERSION
- docker tag $SERVICE_NAME $IMAGE_ID:$VERSION
- docker push $IMAGE_ID:$VERSION
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,workflow,job # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
- if: failure() # Pick up events even if the job fails or is canceled.
-
- sonar_analysis:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Set up JDK 11
- uses: actions/setup-java@v1
- with:
- ref: ${{ github.ref }}
- java-version: 11
- server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
- settings-path: ${{ github.workspace }} # location for the settings.xml file
-
- - name: Setup branch and env
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
- echo "GPG_TTY=$(tty)" >> $GITHUB_ENV
-
- - uses: actions/cache@v1
- with:
- path: ~/.m2/repository
- key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- ${{ runner.os }}-maven-${{ env.BRANCH_NAME }}
-
- - name: Setup the settings file for ossrh server
- run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml
-
- - name: Build with Maven
- run: |
- cd authentication
- mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml
-
- - name: Analyze with SonarCloud
- run: |
- cd authentication
- mvn -B -Dgpg.skip verify sonar:sonar -Dsonar.projectKey=mosip_${{ github.event.repository.name }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }}
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
- - uses: 8398a7/action-slack@v3
- with:
- status: ${{ job.status }}
- fields: repo,message,commit,workflow,job # selectable (default: repo,message)
- env:
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required
- if: failure() # Pick up events even if the job fails or is canceled.
diff --git a/.github/workflows/release-changes.yml b/.github/workflows/release-changes.yml
new file mode 100644
index 00000000000..783d4896a2a
--- /dev/null
+++ b/.github/workflows/release-changes.yml
@@ -0,0 +1,29 @@
+name: Release/pre-release Preparation.
+
+on:
+ workflow_dispatch:
+ inputs:
+ MESSAGE:
+ description: 'Triggered for release or pe-release'
+ required: false
+ default: 'Release Preparation'
+ RELEASE_TAG:
+ description: 'tag to update'
+ required: true
+ SNAPSHOT_TAG:
+ description: 'tag to be replaced'
+ required: true
+ BASE:
+ description: 'base branch for PR'
+ required: true
+jobs:
+ maven-release-preparation:
+ uses: mosip/kattu/.github/workflows/release-changes.yml@master
+ with:
+ MESSAGE: ${{ inputs.MESSAGE }}
+ RELEASE_TAG: ${{ inputs.RELEASE_TAG }}
+ SNAPSHOT_TAG: ${{ inputs.SNAPSHOT_TAG }}
+ BASE: ${{ inputs.BASE }}
+ secrets:
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
+ ACTION_PAT: ${{ secrets.ACTION_PAT }}
\ No newline at end of file
diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml
deleted file mode 100644
index 5d8e1a32989..00000000000
--- a/.github/workflows/release_changes.yml
+++ /dev/null
@@ -1,61 +0,0 @@
-name: Release/pre-release Preparation.
-
-on:
- workflow_dispatch:
- inputs:
- message:
- description: 'Triggered for release or pe-release'
- required: false
- default: 'Release Preparation'
- releaseTags:
- description: 'tag to update'
- required: true
- snapshotTags:
- description: 'tag to be replaced'
- required: true
- base:
- description: 'base branch for PR'
- required: true
-jobs:
- build:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Setup branch and env
- run: |
- # Strip git ref prefix from version
- echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV
- echo "GPG_TTY=$(tty)" >> $GITHUB_ENV
-
- - name: update Branch name in badges
- run: |
- sed -i 's/branch=.*)]/branch=${{ env.BRANCH_NAME }}\)]/g' README.md
- sed -i 's/branch=.*\&/branch=${{ env.BRANCH_NAME }}\&/g' README.md
-
- - name: Mannualy changing the pom versions
- run: find . -type f -name "*pom.xml" -print0 | xargs -0 sed -i "s/${{ github.event.inputs.snapshotTags }}/${{ github.event.inputs.releaseTags }}/g"
-
- - name: Updating the Release URL in POM
- run: |
- cd .github/workflows
- sed -i 's/OSSRH_SNAPSHOT_URL/RELEASE_URL/g' push_trigger.yml
-
- - name: Updating libs-snapshot-local to libs-release local for artifactory URL's.
- run: find . -type f -name "*Dockerfile" -print0 | xargs -0 sed -i "s/libs-snapshot-local/libs-release-local/g"
-
- - name: removing -DskipTests
- run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-DskipTests"//g"
-
-# - name: removing --Dgpg.skip
-# run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-Dgpg.skip"//g"
-
- - name: Create Pull Request
- uses: peter-evans/create-pull-request@v3
- with:
- token: ${{ secrets.ACTION_PAT }}
- commit-message: Release Bot Pre-release changes
- title: Release changes
- body: Automated PR for ${{ github.event.inputs.releaseTags }} release.
- branch: release-branch
- delete-branch: true
- base: ${{ github.event.inputs.base }}
diff --git a/.github/workflows/release_trigger.yml b/.github/workflows/release_trigger.yml
deleted file mode 100644
index d0f9da8d439..00000000000
--- a/.github/workflows/release_trigger.yml
+++ /dev/null
@@ -1,267 +0,0 @@
-name: Release maven packages and docker upon a release
-
-on:
- release:
- types: [published]
-
-jobs:
- build:
-
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v2
- - name: Set up JDK 11
- uses: actions/setup-java@v1
- with:
- ref: ${{ github.ref }}
- java-version: 11
- server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
- settings-path: ${{ github.workspace }} # location for the settings.xml file
-
- - name: Setup branch and GPG public key
- run: |
- # Strip git ref prefix from version
- echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')"
- echo ${{ env.BRANCH_NAME }}
- echo "::set-env name=GPG_TTY::$(tty)"
- echo ${{ env.GPG_TTY }}
- sudo apt-get --yes install gnupg2
- gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg
- gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg
-
- - uses: actions/cache@v1
- with:
- path: ~/.m2/repository
- key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- ${{ runner.os }}-maven-${{ env.BRANCH_NAME }}
-
- - name: Setup the settings file for ossrh server
- run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml
-
-
- - name: Build with Maven
- run: |
- cd authentication
- mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml
-
- - name: Ready the springboot artifacts
- run: find -name '*.jar' -executable -type f -exec zip release.zip {} +
-
- - name: Upload the springboot jars
- uses: actions/upload-artifact@v1
- with:
- name: release
- path: ./release.zip
-
- publish_to_nexus:
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v2
- - name: Set up JDK 11
- uses: actions/setup-java@v1
- with:
- ref: ${{ github.ref }}
- java-version: 11
- server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
- settings-path: ${{ github.workspace }} # location for the settings.xml file
-
- - name: Setup branch and GPG public key
- run: |
- # Strip git ref prefix from version
- echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')"
- echo ${{ env.BRANCH_NAME }}
- echo "::set-env name=GPG_TTY::$(tty)"
- echo ${{ env.GPG_TTY }}
- sudo apt-get --yes install gnupg2
- gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg
- gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg
-
- - uses: actions/cache@v1
- with:
- path: ~/.m2/repository
- key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- ${{ runner.os }}-maven-${{ env.BRANCH_NAME }}
-
- - name: Install xmllint
- run: |
- sudo apt-get update
- sudo apt-get install libxml2-utils
-
- - name: Setup the settings file for ossrh server
- run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml
-
- - name: Build with Maven
- run: |
- cd authentication
- mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml
-
- - name: Publish the maven package
- run: |
- chmod +x ./deploy.sh
- ./deploy.sh authentication $GITHUB_WORKSPACE/settings.xml .*
- env:
- GPG_TTY: $(tty)
- - name: Analyze with SonarCloud
- run: |
- cd authentication
- mvn -B verify sonar:sonar -Dsonar.projectKey=${{ secrets.PROJECT_KEY }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }}
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
- docker-authentication-otp-service:
- needs: build
-
- runs-on: ubuntu-latest
- env:
- NAMESPACE: ${{ secrets.dev_namespace_docker_hub }}
- SERVICE_NAME: authentication-otp-service
- SERVICE_LOCATION: authentication/authentication-otp-service
-
- steps:
- - uses: actions/checkout@v2
- - uses: actions/download-artifact@v1
- with:
- name: release
- path: ./
-
- - name: Setup branch name
- run: |
- # Strip git ref prefix from version
- echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')"
- echo ${{ env.BRANCH_NAME }}
-
- - name: Get version info from pom
- id: getPomVersion
- uses: mavrosxristoforos/get-xml-info@1.0
- with:
- xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml
- xpath: /*[local-name()="project"]/*[local-name()="version"]
-
- - name: Unzip and extract the authentication-otp-service
- run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target"
-
- - name: Build image
- run: |
- cd "./${{env.SERVICE_LOCATION}}"
- docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }}
- - name: Log into registry
- run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin
-
- - name: Push image
- run: |
- IMAGE_ID=$NAMESPACE/$SERVICE_NAME
-
- # Change all uppercase to lowercase
- IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- echo "push version ${{steps.getPomVersion.outputs.info}}"
- VERSION=$BRANCH_NAME
- echo IMAGE_ID=$IMAGE_ID
- echo VERSION=$VERSION
- docker tag $SERVICE_NAME $IMAGE_ID:$VERSION
- docker push $IMAGE_ID:$VERSION
- docker-authentication-internal-service:
- needs: build
-
- runs-on: ubuntu-latest
- env:
- NAMESPACE: ${{ secrets.dev_namespace_docker_hub }}
- SERVICE_NAME: authentication-internal-service
- SERVICE_LOCATION: authentication/authentication-internal-service
-
- steps:
- - uses: actions/checkout@v2
- - uses: actions/download-artifact@v1
- with:
- name: release
- path: ./
-
- - name: Setup branch name
- run: |
- # Strip git ref prefix from version
- echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')"
- echo ${{ env.BRANCH_NAME }}
-
- - name: Get version info from pom
- id: getPomVersion
- uses: mavrosxristoforos/get-xml-info@1.0
- with:
- xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml
- xpath: /*[local-name()="project"]/*[local-name()="version"]
-
- - name: Unzip and extract the authentication-internal-service
- run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target"
-
- - name: Build image
- run: |
- cd "./${{env.SERVICE_LOCATION}}"
- docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }}
- - name: Log into registry
- run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin
-
- - name: Push image
- run: |
- IMAGE_ID=$NAMESPACE/$SERVICE_NAME
-
- # Change all uppercase to lowercase
- IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- echo "push version ${{steps.getPomVersion.outputs.info}}"
- VERSION=$BRANCH_NAME
- echo IMAGE_ID=$IMAGE_ID
- echo VERSION=$VERSION
- docker tag $SERVICE_NAME $IMAGE_ID:$VERSION
- docker push $IMAGE_ID:$VERSION
- docker-authentication-service:
- needs: build
-
- runs-on: ubuntu-latest
- env:
- NAMESPACE: ${{ secrets.dev_namespace_docker_hub }}
- SERVICE_NAME: authentication-service
- SERVICE_LOCATION: authentication/authentication-service
-
- steps:
- - uses: actions/checkout@v2
- - uses: actions/download-artifact@v1
- with:
- name: release
- path: ./
-
- - name: Setup branch name
- run: |
- # Strip git ref prefix from version
- echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')"
- echo ${{ env.BRANCH_NAME }}
-
- - name: Get version info from pom
- id: getPomVersion
- uses: mavrosxristoforos/get-xml-info@1.0
- with:
- xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml
- xpath: /*[local-name()="project"]/*[local-name()="version"]
-
- - name: Unzip and extract the authentication-service
- run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target"
-
- - name: Build image
- run: |
- cd "./${{env.SERVICE_LOCATION}}"
- docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }}
- - name: Log into registry
- run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin
-
- - name: Push image
- run: |
- IMAGE_ID=$NAMESPACE/$SERVICE_NAME
-
- # Change all uppercase to lowercase
- IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- echo "push version ${{steps.getPomVersion.outputs.info}}"
- VERSION=$BRANCH_NAME
- echo IMAGE_ID=$IMAGE_ID
- echo VERSION=$VERSION
- docker tag $SERVICE_NAME $IMAGE_ID:$VERSION
- docker push $IMAGE_ID:$VERSION
diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml
index e9bba0e65a0..9a5b079ffdf 100644
--- a/.github/workflows/tag.yaml
+++ b/.github/workflows/tag.yaml
@@ -1,43 +1,35 @@
name: Tagging of repos
-env:
- tag: v1.2.3
-
on:
workflow_dispatch:
inputs:
- tag:
+ TAG:
description: 'Tag to be published'
required: true
- default: 'v1.2.3'
type: string
- body:
+ BODY:
description: 'Release body message'
required: true
default: 'Changes in this Release'
type: string
- pre-release:
+ PRE_RELEASE:
description: 'Pre-release? True/False'
required: true
default: False
type: string
+ DRAFT:
+ description: 'Draft? True/False'
+ required: false
+ default: False
+ type: string
jobs:
- build:
- name: Create Release
- runs-on: ubuntu-latest
- steps:
- - name: Checkout code
- uses: actions/checkout@v2
- - name: Create Release
- id: create_release
- uses: actions/create-release@v1
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
- with:
- tag_name: ${{ github.event.inputs.tag }}
- release_name: ${{ github.event.inputs.tag }}
- body: |
- ${{ github.event.inputs.body }}
- draft: false
- prerelease: ${{fromJSON(github.event.inputs.pre-release)}}
+ tag-branch:
+ uses: mosip/kattu/.github/workflows/tag.yml@master
+ with:
+ TAG: ${{ inputs.TAG }}
+ BODY: ${{ inputs.BODY }}
+ PRE_RELEASE: ${{ inputs.PRE_RELEASE }}
+ DRAFT: ${{ inputs.DRAFT }}
+ secrets:
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
\ No newline at end of file
diff --git a/README.md b/README.md
index 948c2591e96..9bcd1127f07 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-[](https://github.com/mosip/id-authentication/actions/workflows/push_trigger.yml)
+[](https://github.com/mosip/id-authentication/actions/workflows/push-trigger.yml)
[](https://sonarcloud.io/dashboard?id=mosip_id-authentication&branch=master)
# ID-Authentication
@@ -13,7 +13,7 @@ Refer to [SQL scripts](db_scripts).
The project requires JDK 1.11.
1. Build and install:
```
- $ cd kernel
+ $ cd authentication
$ mvn install -DskipTests=true -Dmaven.javadoc.skip=true -Dgpg.skip=true
```
1. Build Docker for a service:
diff --git a/authentication/authentication-authtypelockfilter-impl/pom.xml b/authentication/authentication-authtypelockfilter-impl/pom.xml
index 6c8e9f0653d..21915677850 100644
--- a/authentication/authentication-authtypelockfilter-impl/pom.xml
+++ b/authentication/authentication-authtypelockfilter-impl/pom.xml
@@ -4,9 +4,9 @@
io.mosip.authentication
authentication-parent
- 1.2.1-SNAPSHOT
+ 1.2.1.0
- 1.2.1-SNAPSHOT
+ 1.2.1.0
authentication-authtypelockfilter-impl
authentication-authtypelockfilter-impl
ID Authentication Filter Implementation for Auth Type Lock validation
@@ -74,8 +74,6 @@
1.7.25
- 2.9.5
- 2.9.8
20180130
2.2.10
20180813
@@ -244,6 +242,14 @@
com.fasterxml.jackson.core
jackson-databind
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+
@@ -260,6 +266,16 @@
io.mosip.authentication
authentication-common
${authentication-common.version}
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+
+
org.springdoc
@@ -270,6 +286,14 @@
com.fasterxml.jackson.core
jackson-databind
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+
@@ -281,6 +305,10 @@
com.fasterxml.jackson.core
jackson-databind
+
+ com.fasterxml.jackson.core
+ jackson-core
+
@@ -300,6 +328,55 @@
+
+ com.fasterxml.jackson.module
+ jackson-module-jaxb-annotations
+ ${jackson.version}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+
+
+
+
+ com.fasterxml.jackson.dataformat
+ jackson-dataformat-xml
+ ${jackson.version}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+
+
+
+
+ io.mosip.kernel
+ kernel-openid-bridge-api
+ ${kernel-openid-bridge-api.version}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+
+
+
diff --git a/authentication/authentication-common/pom.xml b/authentication/authentication-common/pom.xml
index d5f12f33836..fd2558c2cb8 100644
--- a/authentication/authentication-common/pom.xml
+++ b/authentication/authentication-common/pom.xml
@@ -6,9 +6,9 @@
io.mosip.authentication
authentication-parent
- 1.2.1-SNAPSHOT
+ 1.2.1.0
- 1.2.1-SNAPSHOT
+ 1.2.1.0
authentication-common
authentication-common
@@ -95,6 +95,12 @@
+
+
+ org.springframework.kafka
+ spring-kafka
+ 2.1.7.RELEASE
+
io.mosip.kernel
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthResponseBuilder.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthResponseBuilder.java
index 65fdb07d549..4bd2a2930d9 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthResponseBuilder.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthResponseBuilder.java
@@ -119,7 +119,9 @@ public AuthResponseDTO build(String tokenID) {
boolean status = !authStatusInfos.isEmpty() && authStatusInfos.stream().allMatch(AuthStatusInfo::isStatus);
ResponseDTO res = new ResponseDTO();
res.setAuthStatus(status);
- res.setAuthToken(tokenID);
+ if (status) {
+ res.setAuthToken(tokenID);
+ }
responseDTO.setResponse(res);
responseDTO.setResponseTime(DateUtils.getUTCCurrentDateTimeString(IdAuthCommonConstants.UTC_DATETIME_PATTERN));
AuthError[] authErrors = authStatusInfos.stream().flatMap(statusInfo -> Optional.ofNullable(statusInfo.getErr())
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthStatusInfoBuilder.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthStatusInfoBuilder.java
index ee69a663cdd..3c3ae83fe42 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthStatusInfoBuilder.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/builder/AuthStatusInfoBuilder.java
@@ -1,288 +1,318 @@
-package io.mosip.authentication.common.service.builder;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-
-import io.mosip.authentication.common.service.config.IDAMappingConfig;
-import io.mosip.authentication.common.service.impl.match.BioAuthType;
-import io.mosip.authentication.common.service.impl.match.DemoAuthType;
-import io.mosip.authentication.common.service.impl.match.DemoMatchType;
-import io.mosip.authentication.common.service.impl.match.IdaIdMapping;
-import io.mosip.authentication.common.service.impl.match.PinAuthType;
-import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
-import io.mosip.authentication.core.indauth.dto.ActionableAuthError;
-import io.mosip.authentication.core.indauth.dto.AuthError;
-import io.mosip.authentication.core.indauth.dto.AuthStatusInfo;
-import io.mosip.authentication.core.spi.indauth.match.AuthType;
-import io.mosip.authentication.core.spi.indauth.match.MatchInput;
-import io.mosip.authentication.core.spi.indauth.match.MatchOutput;
-import io.mosip.authentication.core.spi.indauth.match.MatchType.Category;
-
-/**
- * The builder class of AuthStatusInfo.
- *
- * @author Loganathan Sekar
- */
-
-public class AuthStatusInfoBuilder {
-
- private static final String ADDRESS_LINE_ITEMS = "address line item(s)";
-
- /** The built flag. */
- private boolean built;
-
- /** The auth status info. */
- private AuthStatusInfo authStatusInfo;
-
- /**
- * Instantiates a new AuthStatusInfoBuilder.
- */
- private AuthStatusInfoBuilder() {
- authStatusInfo = new AuthStatusInfo();
- }
-
- /**
- * Gets new instance of AuthStatusInfo.
- *
- * @return the auth status info builder
- */
- public static AuthStatusInfoBuilder newInstance() {
- return new AuthStatusInfoBuilder();
- }
-
- /**
- * Sets the status.
- *
- * @param status the status
- * @return the auth status info builder
- */
- public AuthStatusInfoBuilder setStatus(boolean status) {
- assertNotBuilt();
- authStatusInfo.setStatus(status);
- return this;
- }
-
- /**
- * Builds the status info.
- *
- * @param matched the demo matched
- * @param listMatchInputs the list match inputs
- * @param listMatchOutputs the list match outputs
- * @param authTypes the auth types
- * @param idMappingConfig the id mapping config
- * @return the auth status info
- */
- public static AuthStatusInfo buildStatusInfo(boolean matched, List listMatchInputs,
- List listMatchOutputs, AuthType[] authTypes, IDAMappingConfig idMappingConfig) {
- AuthStatusInfoBuilder statusInfoBuilder = AuthStatusInfoBuilder.newInstance();
- statusInfoBuilder.setStatus(matched);
- prepareErrorList(listMatchOutputs, statusInfoBuilder, idMappingConfig);
- return statusInfoBuilder.build();
- }
-
- /**
- * Builds the usage data bits.
- *
- * @param listMatchOutputs the list match outputs
- * @param statusInfoBuilder the status info builder
- * @param idaMappingConfig the ida mapping config
- */
- /**
- * prepares the list of errors if the authentication status got failed
- *
- * @param listMatchOutputs the list match outputs
- * @param statusInfoBuilder the status info builder
- */
- private static void prepareErrorList(List listMatchOutputs, AuthStatusInfoBuilder statusInfoBuilder,
- IDAMappingConfig idaMappingConfig) {
- listMatchOutputs.forEach((MatchOutput matchOutput) -> {
- if (!matchOutput.isMatched()) {
- prepareErrorList(matchOutput, statusInfoBuilder, idaMappingConfig);
- }
- });
- }
-
- /**
- * @param matchOutput
- * @param statusInfoBuilder
- */
- private static void prepareErrorList(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder,
- IDAMappingConfig idMappingConfig) {
-
- if (matchOutput != null && !matchOutput.isMatched()) {
- String category = matchOutput.getMatchType().getCategory().getType();
- if (category.equalsIgnoreCase(Category.BIO.getType())) {
- constructBioError(matchOutput, statusInfoBuilder);
- } else if (category.equalsIgnoreCase(Category.SPIN.getType())) {
- constructPinError(matchOutput, statusInfoBuilder);
- } else if (category.equalsIgnoreCase(Category.DEMO.getType())) {
- constructDemoError(matchOutput, statusInfoBuilder, idMappingConfig);
- } else if (category.equalsIgnoreCase(Category.OTP.getType())) {
- constructOTPError(matchOutput, statusInfoBuilder);
- }
- }
- }
-
- private static void constructDemoError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder,
- IDAMappingConfig idMappingConfig) {
- boolean multiLanguage = matchOutput.getMatchType().isMultiLanguage() && matchOutput.getLanguage() != null;
-
- Optional authTypeForMatchType;
- AuthType[] authTypes;
- authTypes = DemoAuthType.values();
- authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
- if (authTypeForMatchType.isPresent()) {
- AuthError errors = null;
- String idName = matchOutput.getIdName();
-
- //If name mapping contains the id Name the error message will not be checked for full address mapping condition
- List nameMapping = IdaIdMapping.NAME.getMappingFunction().apply(idMappingConfig,
- matchOutput.getMatchType());
- String idNameForErrorMessage;
- if(nameMapping.contains(idName)) {
- idNameForErrorMessage = idName;
- } else {
- // For Address line items, check if Full address mapping contains the id Name
- // the error message will be called as address line item(s)
- List fullAddressMappings = IdaIdMapping.FULLADDRESS.getMappingFunction().apply(idMappingConfig,
- matchOutput.getMatchType());
- if (fullAddressMappings.contains(idName)) {
- idNameForErrorMessage = ADDRESS_LINE_ITEMS;
- } else {
- idNameForErrorMessage = idName;
- }
- }
- //Need special handling for age since it is mapped to Date of Birth , but error should say about age only.
- if(matchOutput.getMatchType().equals(DemoMatchType.AGE)) {
- idNameForErrorMessage = IdaIdMapping.AGE.getIdname();
- }
-
- if (!multiLanguage) {
- errors = createActionableAuthError(IdAuthenticationErrorConstants.DEMO_DATA_MISMATCH, idNameForErrorMessage);
- } else {
- errors = createActionableAuthError(IdAuthenticationErrorConstants.DEMOGRAPHIC_DATA_MISMATCH_LANG, idNameForErrorMessage,
- matchOutput.getLanguage());
- }
-
- statusInfoBuilder.addErrors(errors);
- }
- }
-
- private static void constructOTPError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
- Optional authTypeForMatchType;
- AuthType[] authTypes;
- authTypes = PinAuthType.values();
- authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
-
- if (authTypeForMatchType.isPresent()) {
- AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.INVALID_OTP, "");
- statusInfoBuilder.addErrors(errors);
- }
- }
-
- /**
- * Construct pin error.
- *
- * @param matchOutput the match output
- * @param statusInfoBuilder the status info builder
- */
- private static void constructPinError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
- Optional authTypeForMatchType;
- AuthType authType;
- AuthType[] authTypes;
- authTypes = PinAuthType.values();
- authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
-
- if (authTypeForMatchType.isPresent()) {
- authType = authTypeForMatchType.get();
- if (authType.getDisplayName().equals(PinAuthType.SPIN.getDisplayName())) {
- AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.PIN_MISMATCH, "");
- statusInfoBuilder.addErrors(errors);
- }
- }
- }
-
- /**
- * Construct bio error.
- *
- * @param matchOutput the match output
- * @param statusInfoBuilder the status info builder
- */
- private static void constructBioError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
- Optional authTypeForMatchType;
- AuthType[] authTypes;
- authTypes = BioAuthType.values();
- authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
- if (authTypeForMatchType.isPresent()) {
- AuthType authType = authTypeForMatchType.get();
- String type;
- if(!authType.equals(BioAuthType.MULTI_MODAL)){
- type = " - " + authType.getType();
- } else {
- type = "";
- }
-
- AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.BIO_MISMATCH,
- type);
- statusInfoBuilder.addErrors(errors);
- }
- }
-
- /**
- * Construct Actionable Auth errors.
- *
- * @param idAuthenticationErrorConstants
- * @param paramName
- * @return
- */
- private static AuthError createActionableAuthError(IdAuthenticationErrorConstants idAuthenticationErrorConstants,
- Object... params) {
- String errorCode = idAuthenticationErrorConstants.getErrorCode();
- String errorMessage = String.format(idAuthenticationErrorConstants.getErrorMessage(), params);
- String actionMessage;
- if (idAuthenticationErrorConstants.getActionMessage() != null) {
- actionMessage = String.format(idAuthenticationErrorConstants.getActionMessage(), params);
- } else {
- actionMessage = null;
- }
- return new ActionableAuthError(errorCode, errorMessage, actionMessage);
- }
-
- /**
- * Adds the errors to the AuthStatusInfo.
- *
- * @param errors the errors
- * @return the auth status info builder
- */
- public AuthStatusInfoBuilder addErrors(AuthError... errors) {
- assertNotBuilt();
- if (authStatusInfo.getErr() == null) {
- authStatusInfo.setErr(new ArrayList<>());
- }
-
- authStatusInfo.getErr().addAll(Arrays.asList(errors));
- return this;
- }
-
- /**
- * Builds the AuthStatusInfo.
- *
- * @return the AuthStatusInfo instance
- */
- public AuthStatusInfo build() {
- assertNotBuilt();
- built = true;
- return authStatusInfo;
- }
-
- /**
- * Assert that AuthStatusInfo is not built.
- */
- private void assertNotBuilt() {
- if (built) {
- throw new IllegalStateException();
- }
- }
-}
+package io.mosip.authentication.common.service.builder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+import io.mosip.authentication.common.service.config.IDAMappingConfig;
+import io.mosip.authentication.common.service.impl.match.BioAuthType;
+import io.mosip.authentication.common.service.impl.match.DemoAuthType;
+import io.mosip.authentication.common.service.impl.match.DemoMatchType;
+import io.mosip.authentication.common.service.impl.match.IdaIdMapping;
+import io.mosip.authentication.common.service.impl.match.KeyBindedTokenAuthType;
+import io.mosip.authentication.common.service.impl.match.PasswordAuthType;
+import io.mosip.authentication.common.service.impl.match.PinAuthType;
+import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
+import io.mosip.authentication.core.indauth.dto.ActionableAuthError;
+import io.mosip.authentication.core.indauth.dto.AuthError;
+import io.mosip.authentication.core.indauth.dto.AuthStatusInfo;
+import io.mosip.authentication.core.spi.indauth.match.AuthType;
+import io.mosip.authentication.core.spi.indauth.match.MatchInput;
+import io.mosip.authentication.core.spi.indauth.match.MatchOutput;
+import io.mosip.authentication.core.spi.indauth.match.MatchType.Category;
+
+/**
+ * The builder class of AuthStatusInfo.
+ *
+ * @author Loganathan Sekar
+ */
+
+public class AuthStatusInfoBuilder {
+
+ private static final String ADDRESS_LINE_ITEMS = "address line item(s)";
+
+ /** The built flag. */
+ private boolean built;
+
+ /** The auth status info. */
+ private AuthStatusInfo authStatusInfo;
+
+ /**
+ * Instantiates a new AuthStatusInfoBuilder.
+ */
+ private AuthStatusInfoBuilder() {
+ authStatusInfo = new AuthStatusInfo();
+ }
+
+ /**
+ * Gets new instance of AuthStatusInfo.
+ *
+ * @return the auth status info builder
+ */
+ public static AuthStatusInfoBuilder newInstance() {
+ return new AuthStatusInfoBuilder();
+ }
+
+ /**
+ * Sets the status.
+ *
+ * @param status the status
+ * @return the auth status info builder
+ */
+ public AuthStatusInfoBuilder setStatus(boolean status) {
+ assertNotBuilt();
+ authStatusInfo.setStatus(status);
+ return this;
+ }
+
+ /**
+ * Builds the status info.
+ *
+ * @param matched the demo matched
+ * @param listMatchInputs the list match inputs
+ * @param listMatchOutputs the list match outputs
+ * @param authTypes the auth types
+ * @param idMappingConfig the id mapping config
+ * @return the auth status info
+ */
+ public static AuthStatusInfo buildStatusInfo(boolean matched, List listMatchInputs,
+ List listMatchOutputs, AuthType[] authTypes, IDAMappingConfig idMappingConfig) {
+ AuthStatusInfoBuilder statusInfoBuilder = AuthStatusInfoBuilder.newInstance();
+ statusInfoBuilder.setStatus(matched);
+ prepareErrorList(listMatchOutputs, statusInfoBuilder, idMappingConfig);
+ return statusInfoBuilder.build();
+ }
+
+ /**
+ * Builds the usage data bits.
+ *
+ * @param listMatchOutputs the list match outputs
+ * @param statusInfoBuilder the status info builder
+ * @param idaMappingConfig the ida mapping config
+ */
+ /**
+ * prepares the list of errors if the authentication status got failed
+ *
+ * @param listMatchOutputs the list match outputs
+ * @param statusInfoBuilder the status info builder
+ */
+ private static void prepareErrorList(List listMatchOutputs, AuthStatusInfoBuilder statusInfoBuilder,
+ IDAMappingConfig idaMappingConfig) {
+ listMatchOutputs.forEach((MatchOutput matchOutput) -> {
+ if (!matchOutput.isMatched()) {
+ prepareErrorList(matchOutput, statusInfoBuilder, idaMappingConfig);
+ }
+ });
+ }
+
+ /**
+ * @param matchOutput
+ * @param statusInfoBuilder
+ */
+ private static void prepareErrorList(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder,
+ IDAMappingConfig idMappingConfig) {
+
+ if (matchOutput != null && !matchOutput.isMatched()) {
+ String category = matchOutput.getMatchType().getCategory().getType();
+ if (category.equalsIgnoreCase(Category.BIO.getType())) {
+ constructBioError(matchOutput, statusInfoBuilder);
+ } else if (category.equalsIgnoreCase(Category.SPIN.getType())) {
+ constructPinError(matchOutput, statusInfoBuilder);
+ } else if (category.equalsIgnoreCase(Category.DEMO.getType())) {
+ constructDemoError(matchOutput, statusInfoBuilder, idMappingConfig);
+ } else if (category.equalsIgnoreCase(Category.OTP.getType())) {
+ constructOTPError(matchOutput, statusInfoBuilder);
+ } else if (category.equalsIgnoreCase(Category.PWD.getType())) {
+ constructPWDError(matchOutput, statusInfoBuilder);
+ } else if (category.equalsIgnoreCase(Category.KBT.getType())) {
+ constructKBTError(matchOutput, statusInfoBuilder);
+ }
+ }
+ }
+
+ private static void constructDemoError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder,
+ IDAMappingConfig idMappingConfig) {
+ boolean multiLanguage = matchOutput.getMatchType().isMultiLanguage() && matchOutput.getLanguage() != null;
+
+ Optional authTypeForMatchType;
+ AuthType[] authTypes;
+ authTypes = DemoAuthType.values();
+ authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
+ if (authTypeForMatchType.isPresent()) {
+ AuthError errors = null;
+ String idName = matchOutput.getIdName();
+
+ //If name mapping contains the id Name the error message will not be checked for full address mapping condition
+ List nameMapping = IdaIdMapping.NAME.getMappingFunction().apply(idMappingConfig,
+ matchOutput.getMatchType());
+ String idNameForErrorMessage;
+ if(nameMapping.contains(idName)) {
+ idNameForErrorMessage = idName;
+ } else {
+ // For Address line items, check if Full address mapping contains the id Name
+ // the error message will be called as address line item(s)
+ List fullAddressMappings = IdaIdMapping.FULLADDRESS.getMappingFunction().apply(idMappingConfig,
+ matchOutput.getMatchType());
+ if (fullAddressMappings.contains(idName)) {
+ idNameForErrorMessage = ADDRESS_LINE_ITEMS;
+ } else {
+ idNameForErrorMessage = idName;
+ }
+ }
+ //Need special handling for age since it is mapped to Date of Birth , but error should say about age only.
+ if(matchOutput.getMatchType().equals(DemoMatchType.AGE)) {
+ idNameForErrorMessage = IdaIdMapping.AGE.getIdname();
+ }
+
+ if (!multiLanguage) {
+ errors = createActionableAuthError(IdAuthenticationErrorConstants.DEMO_DATA_MISMATCH, idNameForErrorMessage);
+ } else {
+ errors = createActionableAuthError(IdAuthenticationErrorConstants.DEMOGRAPHIC_DATA_MISMATCH_LANG, idNameForErrorMessage,
+ matchOutput.getLanguage());
+ }
+
+ statusInfoBuilder.addErrors(errors);
+ }
+ }
+
+ private static void constructOTPError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
+ Optional authTypeForMatchType;
+ AuthType[] authTypes;
+ authTypes = PinAuthType.values();
+ authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
+
+ if (authTypeForMatchType.isPresent()) {
+ AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.INVALID_OTP, "");
+ statusInfoBuilder.addErrors(errors);
+ }
+ }
+
+ private static void constructPWDError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
+ Optional authTypeForMatchType;
+ AuthType[] authTypes;
+ authTypes = PasswordAuthType.values();
+ authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
+
+ if (authTypeForMatchType.isPresent()) {
+ AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.PASSWORD_MISMATCH, "");
+ statusInfoBuilder.addErrors(errors);
+ }
+ }
+
+ private static void constructKBTError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
+ Optional authTypeForMatchType;
+ AuthType[] authTypes;
+ authTypes = KeyBindedTokenAuthType.values();
+ authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
+
+ if (authTypeForMatchType.isPresent()) {
+ AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.ERROR_TOKEN_VERIFICATION, "");
+ statusInfoBuilder.addErrors(errors);
+ }
+ }
+
+ /**
+ * Construct pin error.
+ *
+ * @param matchOutput the match output
+ * @param statusInfoBuilder the status info builder
+ */
+ private static void constructPinError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
+ Optional authTypeForMatchType;
+ AuthType authType;
+ AuthType[] authTypes;
+ authTypes = PinAuthType.values();
+ authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
+
+ if (authTypeForMatchType.isPresent()) {
+ authType = authTypeForMatchType.get();
+ if (authType.getDisplayName().equals(PinAuthType.SPIN.getDisplayName())) {
+ AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.PIN_MISMATCH, "");
+ statusInfoBuilder.addErrors(errors);
+ }
+ }
+ }
+
+ /**
+ * Construct bio error.
+ *
+ * @param matchOutput the match output
+ * @param statusInfoBuilder the status info builder
+ */
+ private static void constructBioError(MatchOutput matchOutput, AuthStatusInfoBuilder statusInfoBuilder) {
+ Optional authTypeForMatchType;
+ AuthType[] authTypes;
+ authTypes = BioAuthType.values();
+ authTypeForMatchType = AuthType.getAuthTypeForMatchType(matchOutput.getMatchType(), authTypes);
+ if (authTypeForMatchType.isPresent()) {
+ AuthType authType = authTypeForMatchType.get();
+ String type;
+ if(!authType.equals(BioAuthType.MULTI_MODAL)){
+ type = " - " + authType.getType();
+ } else {
+ type = "";
+ }
+
+ AuthError errors = createActionableAuthError(IdAuthenticationErrorConstants.BIO_MISMATCH,
+ type);
+ statusInfoBuilder.addErrors(errors);
+ }
+ }
+
+ /**
+ * Construct Actionable Auth errors.
+ *
+ * @param idAuthenticationErrorConstants
+ * @param paramName
+ * @return
+ */
+ private static AuthError createActionableAuthError(IdAuthenticationErrorConstants idAuthenticationErrorConstants,
+ Object... params) {
+ String errorCode = idAuthenticationErrorConstants.getErrorCode();
+ String errorMessage = String.format(idAuthenticationErrorConstants.getErrorMessage(), params);
+ String actionMessage;
+ if (idAuthenticationErrorConstants.getActionMessage() != null) {
+ actionMessage = String.format(idAuthenticationErrorConstants.getActionMessage(), params);
+ } else {
+ actionMessage = null;
+ }
+ return new ActionableAuthError(errorCode, errorMessage, actionMessage);
+ }
+
+ /**
+ * Adds the errors to the AuthStatusInfo.
+ *
+ * @param errors the errors
+ * @return the auth status info builder
+ */
+ public AuthStatusInfoBuilder addErrors(AuthError... errors) {
+ assertNotBuilt();
+ if (authStatusInfo.getErr() == null) {
+ authStatusInfo.setErr(new ArrayList<>());
+ }
+
+ authStatusInfo.getErr().addAll(Arrays.asList(errors));
+ return this;
+ }
+
+ /**
+ * Builds the AuthStatusInfo.
+ *
+ * @return the AuthStatusInfo instance
+ */
+ public AuthStatusInfo build() {
+ assertNotBuilt();
+ built = true;
+ return authStatusInfo;
+ }
+
+ /**
+ * Assert that AuthStatusInfo is not built.
+ */
+ private void assertNotBuilt() {
+ if (built) {
+ throw new IllegalStateException();
+ }
+ }
+}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java
index b2f00b47101..59d3ca494a9 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/IDAMappingConfig.java
@@ -8,6 +8,7 @@
import org.springframework.context.annotation.PropertySource;
import io.mosip.authentication.common.service.factory.IDAMappingFactory;
+import io.mosip.authentication.core.indauth.dto.KeyBindedTokenDTO;
import io.mosip.authentication.core.spi.indauth.match.MappingConfig;
import lombok.Data;
@@ -126,4 +127,6 @@ public class IDAMappingConfig implements MappingConfig {
/** The dynamic attributes. */
private Map> dynamicAttributes;
+ /** The password. */
+ private List password;
}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/KafkaProducerConfig.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/KafkaProducerConfig.java
new file mode 100644
index 00000000000..7612dc557d1
--- /dev/null
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/config/KafkaProducerConfig.java
@@ -0,0 +1,44 @@
+package io.mosip.authentication.common.service.config;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.kafka.core.DefaultKafkaProducerFactory;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.kafka.core.ProducerFactory;
+import org.springframework.kafka.support.serializer.JsonSerializer;
+import static io.mosip.authentication.core.constant.IdAuthConfigKeyConstants.AUTHENTICATION_ERROR_EVENTING_ENABLED;
+
+/**
+ * The Class KafkaProducerConfig.
+ *
+ * @author Neha
+ */
+
+@Configuration
+@ConditionalOnProperty(value = AUTHENTICATION_ERROR_EVENTING_ENABLED, havingValue = "true", matchIfMissing = false)
+public class KafkaProducerConfig {
+
+ @Value(value = "${mosip.ida.kafka.bootstrap.servers}")
+ private String bootstrapAddress;
+
+ @Bean
+ public ProducerFactory producerFactory() {
+ Map configProps = new HashMap<>();
+ configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
+ configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
+ configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
+ return new DefaultKafkaProducerFactory<>(configProps);
+ }
+
+ @Bean
+ public KafkaTemplate kafkaTemplate() {
+ return new KafkaTemplate<>(producerFactory());
+ }
+}
\ No newline at end of file
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/CredSubjectIdStore.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/CredSubjectIdStore.java
new file mode 100644
index 00000000000..d0a8a9eab82
--- /dev/null
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/CredSubjectIdStore.java
@@ -0,0 +1,68 @@
+package io.mosip.authentication.common.service.entity;
+
+import java.time.LocalDateTime;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.validation.constraints.NotNull;
+
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@NoArgsConstructor
+@Data
+@Table(name = "cred_subject_id_store", schema = "ida")
+@Entity
+public class CredSubjectIdStore {
+
+ @Id
+ @NotNull
+ @Column(name = "id")
+ private String id;
+
+ @NotNull
+ @Column(name = "id_vid_hash")
+ private String idVidHash;
+
+ @NotNull
+ @Column(name = "token_id")
+ private String tokenId;
+
+ @NotNull
+ @Column(name = "cred_subject_id")
+ private String credSubjectId;
+
+ @NotNull
+ @Column(name = "csid_key_hash")
+ private String csidKeyHash;
+
+ @NotNull
+ @Column(name = "oidc_client_id")
+ private String oidcClientId;
+
+ @NotNull
+ @Column(name = "csid_status")
+ private String csidStatus;
+
+ @NotNull
+ @Column(name = "cr_by")
+ private String createdBy;
+
+ @NotNull
+ @Column(name = "cr_dtimes")
+ private LocalDateTime crDTimes;
+
+ @Column(name = "upd_by")
+ private String updatedBy;
+
+ @Column(name = "upd_dtimes")
+ private LocalDateTime updDTimes;
+
+ @Column(name = "is_deleted")
+ private boolean isDeleted;
+
+ @Column(name = "del_dtimes")
+ private LocalDateTime delDTimes;
+}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/PolicyData.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/PolicyData.java
index 5898b958ecb..358b121a066 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/PolicyData.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/entity/PolicyData.java
@@ -97,7 +97,7 @@ public JSONObject getPolicy() {
return OBJECT_MAPPER.readValue(CryptoUtil.decodeBase64Url(new String(this.policy)), JSONObject.class);
} catch (IOException e) {
// This block will never be executed
- e.printStackTrace();
+ //e.printStackTrace();
return null;
}
}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/exception/IdAuthExceptionHandler.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/exception/IdAuthExceptionHandler.java
index c98bd7d787e..6a01b5a226a 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/exception/IdAuthExceptionHandler.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/exception/IdAuthExceptionHandler.java
@@ -46,6 +46,8 @@
import io.mosip.authentication.core.indauth.dto.EncryptedKycRespDTO;
import io.mosip.authentication.core.indauth.dto.KycExchangeResponseDTO;
import io.mosip.authentication.core.indauth.dto.ResponseDTO;
+import io.mosip.authentication.core.indauth.dto.VCResponseDTO;
+import io.mosip.authentication.core.indauth.dto.VciExchangeResponseDTO;
import io.mosip.authentication.core.logger.IdaLogger;
import io.mosip.authentication.core.otp.dto.OtpResponseDTO;
import io.mosip.idrepository.core.exception.RestServiceException;
@@ -382,6 +384,13 @@ private static Object frameErrorResponse(String requestReceived, String type, Li
EncryptedKycRespDTO encryptedKycRespDTO = new EncryptedKycRespDTO();
kycExchangeResponseDTO.setResponse(encryptedKycRespDTO);
return kycExchangeResponseDTO;
+ case "vci-exchange":
+ VciExchangeResponseDTO vciExchangeResponseDTO = new VciExchangeResponseDTO();
+ vciExchangeResponseDTO.setErrors(errors);
+ vciExchangeResponseDTO.setResponseTime(responseTime);
+ VCResponseDTO> vcResponseDTO = null;
+ vciExchangeResponseDTO.setResponse(vcResponseDTO);
+ return vciExchangeResponseDTO;
case "internal":
if (Objects.nonNull(type) && type.equalsIgnoreCase(IdAuthCommonConstants.OTP)) {
OtpResponseDTO internalotpresponsedto = new OtpResponseDTO();
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java
index e215a10e3a8..3a3b27878cf 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/facade/AuthFacadeImpl.java
@@ -29,6 +29,7 @@
import io.mosip.authentication.common.service.helper.AuditHelper;
import io.mosip.authentication.common.service.helper.AuthTransactionHelper;
import io.mosip.authentication.common.service.helper.IdInfoHelper;
+import io.mosip.authentication.common.service.impl.match.IdaIdMapping;
import io.mosip.authentication.common.service.integration.TokenIdManager;
import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
import io.mosip.authentication.common.service.util.AuthTypeUtil;
@@ -47,6 +48,7 @@
import io.mosip.authentication.core.indauth.dto.AuthStatusInfo;
import io.mosip.authentication.core.indauth.dto.IdType;
import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO;
+import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO;
import io.mosip.authentication.core.indauth.dto.EkycAuthRequestDTO;
import io.mosip.authentication.core.logger.IdaLogger;
import io.mosip.authentication.core.partner.dto.PartnerPolicyResponseDTO;
@@ -58,6 +60,7 @@
import io.mosip.authentication.core.spi.indauth.service.BioAuthService;
import io.mosip.authentication.core.spi.indauth.service.DemoAuthService;
import io.mosip.authentication.core.spi.indauth.service.OTPAuthService;
+import io.mosip.authentication.core.spi.indauth.service.PasswordAuthService;
import io.mosip.authentication.core.spi.notification.service.NotificationService;
import io.mosip.authentication.core.spi.partner.service.PartnerService;
import io.mosip.kernel.core.logger.spi.Logger;
@@ -129,6 +132,9 @@ public class AuthFacadeImpl implements AuthFacade {
@Autowired
private KeyBindedTokenAuthService keyBindedTokenAuthService;
+
+ @Autowired
+ private PasswordAuthService passwordAuthService;
/*
* (non-Javadoc)
@@ -161,6 +167,14 @@ public AuthResponseDTO authenticateIndividual(AuthRequestDTO authRequestDTO, boo
addKycPolicyAttributes(filterAttributes, kycAuthRequestDTO);
}
+
+ if(authRequestDTO instanceof KycAuthRequestDTO) {
+ KycAuthRequestDTO kycAuthRequestDTO = (KycAuthRequestDTO) authRequestDTO;
+ // In case of kyc-auth request and password auth is requested
+ if(AuthTypeUtil.isPassword(kycAuthRequestDTO)) {
+ filterAttributes.add(IdaIdMapping.PASSWORD.getIdname());
+ }
+ }
Map idResDTO = idService.processIdType(idvIdType, idvid, idInfoHelper.isBiometricDataNeeded(authRequestDTO),
markVidConsumed, filterAttributes);
@@ -312,6 +326,11 @@ private List processAuthType(AuthRequestDTO authRequestDTO,
authTxnBuilder, idvidHash);
}
+ if (!isMatchFailed(authStatusList)) {
+ processPasswordAuth(authRequestDTO, idInfo, token, isAuth, authStatusList, idType, authTokenId, partnerId,
+ authTxnBuilder, idvidHash);
+ }
+
return authStatusList;
}
@@ -383,7 +402,7 @@ private void processDemoAuth(AuthRequestDTO authRequestDTO, Map> idInfo, String token,
+ boolean isAuth, List authStatusList, IdType idType, String authTokenId, String partnerId,
+ AuthTransactionBuilder authTxnBuilder, String idvidHash) throws IdAuthenticationBusinessException {
+ if (AuthTypeUtil.isPassword(authRequestDTO)) {
+ AuthStatusInfo passwordMatchStatus = null;
+ try {
+ passwordMatchStatus = passwordAuthService.authenticate(authRequestDTO, token, idInfo, partnerId);
+ authStatusList.add(passwordMatchStatus);
+
+ boolean isStatus = passwordMatchStatus != null && passwordMatchStatus.isStatus();
+ auditHelper.audit(AuditModules.PASSWORD_AUTH, AuditEvents.PASSWORD_BASED_AUTH_REQUEST, authRequestDTO.getTransactionID(),
+ idType, "authenticateApplicant status(Password) : " + isStatus);
+ } finally {
+ boolean isStatus = passwordMatchStatus != null && passwordMatchStatus.isStatus();
+ logger.info(IdAuthCommonConstants.SESSION_ID, EnvUtil.getAppId(),
+ AUTH_FACADE, "Password Authentication status : " + isStatus);
+ authTxnBuilder.addRequestType(RequestType.PASSWORD_AUTH);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java
index 55bf6f085b6..f74ad9f18d8 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/BaseIDAFilter.java
@@ -465,6 +465,12 @@ protected String consumeResponse(ResettableStreamHttpServletRequest requestWrapp
String requestSignature = requestWrapper.getHeader(SIGNATURE);
String responseSignature = null;
if(isSigningRequired()) {
+ if (Objects.isNull(responseAsString) || responseAsString.trim().length() == 0) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, EVENT_FILTER, BASE_IDA_FILTER,
+ " Response String is null or empty for response (JWT) signing");
+ throw new IdAuthenticationAppException(IdAuthenticationErrorConstants.UNABLE_TO_PROCESS.getErrorCode(),
+ IdAuthenticationErrorConstants.UNABLE_TO_PROCESS.getErrorMessage());
+ }
responseSignature = keyManager.signResponse(responseAsString);
responseWrapper.setHeader(EnvUtil.getSignResponse(), responseSignature);
}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java
index 10b4c712394..e9a162fac2c 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/filter/IdAuthFilter.java
@@ -28,6 +28,8 @@
import javax.servlet.ServletException;
import io.mosip.authentication.core.indauth.dto.KeyBindedTokenDTO;
+import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO;
+
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@@ -843,6 +845,7 @@ protected void checkAllowedAuthTypeForKeyBindedToken(Map request
Object value = Optional.ofNullable(requestBody.get(IdAuthCommonConstants.REQUEST))
.filter(obj -> obj instanceof Map).map(obj -> ((Map) obj).get(KEY_BINDED_TOKEN))
.filter(obj -> obj instanceof List).orElse(Collections.emptyMap());
+
List list = mapper.readValue(mapper.writeValueAsBytes(value),
new TypeReference>() {
});
@@ -861,6 +864,19 @@ protected void checkAllowedAuthTypeForKeyBindedToken(Map request
}
}
+ protected void checkAllowedAuthTypeForPassword(Map requestBody, List authPolicies)
+ throws IdAuthenticationAppException, IOException {
+ KycAuthRequestDTO authRequestDTO = mapper.readValue(mapper.writeValueAsBytes(requestBody),
+ KycAuthRequestDTO.class);
+
+ if (AuthTypeUtil.isPassword(authRequestDTO) && !isAllowedAuthType(MatchType.Category.PWD.getType(), authPolicies)) {
+ throw new IdAuthenticationAppException(
+ IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorCode(),
+ String.format(IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorMessage(),
+ MatchType.Category.PWD.name()));
+ }
+ }
+
/**
* Check allowed auth type for bio.
*
@@ -1042,16 +1058,25 @@ private void checkAllowedAMRBasedOnClientConfig(Map requestBody,
if (AuthTypeUtil.isPin(authRequestDTO) && !allowedAMRs.contains(MatchType.Category.SPIN.getType())) {
throw new IdAuthenticationAppException(
- IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorCode(),
- String.format(IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorMessage(),
+ IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorCode(),
+ String.format(IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorMessage(),
MatchType.Category.SPIN.name()));
}
if (AuthTypeUtil.isOtp(authRequestDTO) && !allowedAMRs.contains(MatchType.Category.OTP.getType())) {
throw new IdAuthenticationAppException(
- IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorCode(),
- String.format(IdAuthenticationErrorConstants.AUTHTYPE_NOT_ALLOWED.getErrorMessage(),
+ IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorCode(),
+ String.format(IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorMessage(),
MatchType.Category.OTP.name()));
}
+
+ KycAuthRequestDTO kycAuthRequestDTO = mapper.readValue(mapper.writeValueAsBytes(requestBody),
+ KycAuthRequestDTO.class);
+ if (AuthTypeUtil.isPassword(kycAuthRequestDTO) && !allowedAMRs.contains(MatchType.Category.PWD.getType())) {
+ throw new IdAuthenticationAppException(
+ IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorCode(),
+ String.format(IdAuthenticationErrorConstants.OIDC_CLIENT_AUTHTYPE_NOT_ALLOWED.getErrorMessage(),
+ MatchType.Category.PWD.name()));
+ }
checkAllowedAMRForKBT(requestBody, allowedAMRs);
}
} catch (IOException e) {
@@ -1119,19 +1144,28 @@ private Set getAuthenticationFactors(PartnerPolicyResponseDTO partnerPol
* @param requestWrapper the request wrapper
* @return the auth part
*/
- protected Map getAuthPart(ResettableStreamHttpServletRequest requestWrapper) {
+ protected Map getAuthPart(ResettableStreamHttpServletRequest requestWrapper) throws IdAuthenticationAppException{
Map params = new HashMap<>();
String url = requestWrapper.getRequestURL().toString();
String contextPath = requestWrapper.getContextPath();
if ((Objects.nonNull(url) && !url.isEmpty()) && (Objects.nonNull(contextPath) && !contextPath.isEmpty())) {
String[] splitedUrlByContext = url.split(contextPath);
String[] paramsArray = Stream.of(splitedUrlByContext[1].split("/")).filter(str -> !str.isEmpty())
- .toArray(size -> new String[size]);
+ .toArray(size -> new String[size]);
+ mosipLogger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getCanonicalName(), "getAuthPart",
+ "List of Path Parameters received in url: " + Stream.of(paramsArray).collect(Collectors.joining(", ")));
if (paramsArray.length >= 3) {
params.put(MISPLICENSE_KEY, paramsArray[paramsArray.length - 3]);
params.put(PARTNER_ID, paramsArray[paramsArray.length - 2]);
params.put(API_KEY, paramsArray[paramsArray.length - 1]);
+ } else {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getCanonicalName(), "getAuthPart",
+ "Required Number of Path Parameters are not available in URL.");
+ throw new IdAuthenticationAppException(
+ IdAuthenticationErrorConstants.URI_PATH_PARAMS_MISSING.getErrorCode(),
+ IdAuthenticationErrorConstants.URI_PATH_PARAMS_MISSING.getErrorMessage());
+
}
}
return params;
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java
index 55c9edc9189..bb22b52a9db 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuditHelper.java
@@ -1,188 +1,196 @@
-package io.mosip.authentication.common.service.helper;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Component;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.mosip.authentication.common.service.exception.IdAuthExceptionHandler;
-import io.mosip.authentication.common.service.factory.AuditRequestFactory;
-import io.mosip.authentication.common.service.factory.RestRequestFactory;
-import io.mosip.authentication.common.service.impl.match.BioAuthType;
-import io.mosip.authentication.common.service.util.AuthTypeUtil;
-import io.mosip.authentication.common.service.util.EnvUtil;
-import io.mosip.authentication.core.constant.AuditEvents;
-import io.mosip.authentication.core.constant.AuditModules;
-import io.mosip.authentication.core.constant.RestServicesConstants;
-import io.mosip.authentication.core.dto.AuditRequestDto;
-import io.mosip.authentication.core.exception.IDDataValidationException;
-import io.mosip.authentication.core.exception.IdAuthenticationBaseException;
-import io.mosip.authentication.core.indauth.dto.AuthError;
-import io.mosip.authentication.core.indauth.dto.AuthRequestDTO;
-import io.mosip.authentication.core.indauth.dto.BioIdentityInfoDTO;
-import io.mosip.authentication.core.indauth.dto.IdType;
-import io.mosip.idrepository.core.dto.RestRequestDTO;
-import io.mosip.idrepository.core.helper.RestHelper;
-import io.mosip.kernel.core.http.RequestWrapper;
-
-/**
- * The Class AuditHelper - build audit requests and send it to audit service.
- *
- * @author Manoj SP
- */
-@Component
-public class AuditHelper {
-
- /** The rest helper. */
- @Autowired
- @Qualifier("withSelfTokenWebclient")
- private RestHelper restHelper;
-
- /** The audit factory. */
- @Autowired
- private AuditRequestFactory auditFactory;
-
- /** The rest factory. */
- @Autowired
- private RestRequestFactory restFactory;
-
- @Autowired
- private ObjectMapper mapper;
-
- /** The EnvPropertyResolver */
- @Autowired
- private EnvUtil env;
-
-
- /**
- * Method to build audit requests and send it to audit service.
- *
- * @param module {@link AuditModules}
- * @param event {@link AuditEvents}
- * @param id UIN/VID
- * @param idType {@link IdType} enum
- * @param desc the desc
- * @throws IDDataValidationException the ID data validation exception
- */
- public void audit(AuditModules module, AuditEvents event, String id, IdType idType, String desc)
- throws IDDataValidationException {
- audit(module, event, id, idType.name(), desc);
- }
-
- /**
- * Method to build audit requests and send it to audit service.
- *
- * @param module {@link AuditModules}
- * @param event {@link AuditEvents}
- * @param id UIN/VID
- * @param idType {@link IdType} name
- * @param desc the desc
- * @throws IDDataValidationException the ID data validation exception
- */
- public void audit(AuditModules module, AuditEvents event, String id, String idType, String desc)
- throws IDDataValidationException {
- RequestWrapper auditRequest = auditFactory.buildRequest(module, event, id, idType, desc);
- RestRequestDTO restRequest = restFactory.buildRequest(RestServicesConstants.AUDIT_MANAGER_SERVICE, auditRequest,
- Map.class);
- restHelper.requestAsync(restRequest);
- }
-
- /**
- * Method to build audit error scenarios and send it to audit service.
- *
- * @param module {@link AuditModules}
- * @param event {@link AuditEvents}
- * @param id UIN/VID
- * @param idType {@link IdType} enum
- * @param desc the desc
- * @throws IDDataValidationException the ID data validation exception
- */
- public void audit(AuditModules module, AuditEvents event, String id, IdType idType, IdAuthenticationBaseException e)
- throws IDDataValidationException {
- audit(module, event, id, idType.name(), e);
- }
-
- /**
- * Method to build audit error scenarios and send it to audit service.
- *
- * @param module {@link AuditModules}
- * @param event {@link AuditEvents}
- * @param id UIN/VID
- * @param idType {@link IdType} name
- * @param desc the desc
- * @throws IDDataValidationException the ID data validation exception
- */
- public void audit(AuditModules module, AuditEvents event, String id, String idType, IdAuthenticationBaseException e)
- throws IDDataValidationException {
- List errorList = IdAuthExceptionHandler.getAuthErrors(e);
- String error;
- try {
- error = mapper.writeValueAsString(errorList);
- } catch (JsonProcessingException e1) {
- //Probably will not occur
- error = "Error : " + e.getErrorCode() + " - " + e.getErrorText();
- }
- audit(module, event, id, idType, error);
- }
-
- public void auditExceptionForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO,
- IdAuthenticationBaseException e) throws IDDataValidationException {
- List auditModules = getAuditModules(authRequestDTO);
- for (AuditModules auditModule : auditModules) {
- audit(auditModule, authAuditEvent, authRequestDTO.getIndividualId(), authRequestDTO.getIndividualIdType(),
- e);
- }
- }
-
- public void auditStatusForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO,
- String status) throws IDDataValidationException {
- List auditModules = getAuditModules(authRequestDTO);
- for (AuditModules auditModule : auditModules) {
- audit(auditModule, authAuditEvent, authRequestDTO.getIndividualId(), authRequestDTO.getIndividualIdType(),
- status);
- }
- }
-
- private List getAuditModules(AuthRequestDTO authRequestDTO) {
- List auditModules = new ArrayList<>(5);
- if (AuthTypeUtil.isOtp(authRequestDTO)) {
- auditModules.add(AuditModules.OTP_AUTH);
- }
-
- if (AuthTypeUtil.isDemo(authRequestDTO)) {
- auditModules.add(AuditModules.DEMO_AUTH);
- }
-
- if (AuthTypeUtil.isPin(authRequestDTO)) {
- auditModules.add(AuditModules.PIN_AUTH);
- }
-
- if (AuthTypeUtil.isBio(authRequestDTO)) {
- if (authRequestDTO.getRequest() != null && authRequestDTO.getRequest().getBiometrics() != null) {
- if ((authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData).anyMatch(
- bioInfo -> BioAuthType.FGR_IMG.getType().equals(bioInfo.getBioType()) || (EnvUtil.getIsFmrEnabled()
- && BioAuthType.FGR_MIN.getType().equals(bioInfo.getBioType()))))) {
- auditModules.add(AuditModules.FINGERPRINT_AUTH);
- }
-
- if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData)
- .anyMatch(bioInfo -> BioAuthType.IRIS_IMG.getType().equals(bioInfo.getBioType()))) {
- auditModules.add(AuditModules.IRIS_AUTH);
- }
-
- if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData)
- .anyMatch(bioInfo -> BioAuthType.FACE_IMG.getType().equals(bioInfo.getBioType()))) {
- auditModules.add(AuditModules.FACE_AUTH);
- }
- }
- }
- return auditModules;
- }
-
-}
+package io.mosip.authentication.common.service.helper;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import io.mosip.authentication.common.service.exception.IdAuthExceptionHandler;
+import io.mosip.authentication.common.service.factory.AuditRequestFactory;
+import io.mosip.authentication.common.service.factory.RestRequestFactory;
+import io.mosip.authentication.common.service.impl.match.BioAuthType;
+import io.mosip.authentication.common.service.util.AuthTypeUtil;
+import io.mosip.authentication.common.service.util.EnvUtil;
+import io.mosip.authentication.core.constant.AuditEvents;
+import io.mosip.authentication.core.constant.AuditModules;
+import io.mosip.authentication.core.constant.RestServicesConstants;
+import io.mosip.authentication.core.dto.AuditRequestDto;
+import io.mosip.authentication.core.exception.IDDataValidationException;
+import io.mosip.authentication.core.exception.IdAuthenticationBaseException;
+import io.mosip.authentication.core.indauth.dto.AuthError;
+import io.mosip.authentication.core.indauth.dto.AuthRequestDTO;
+import io.mosip.authentication.core.indauth.dto.BioIdentityInfoDTO;
+import io.mosip.authentication.core.indauth.dto.IdType;
+import io.mosip.idrepository.core.dto.RestRequestDTO;
+import io.mosip.idrepository.core.helper.RestHelper;
+import io.mosip.kernel.core.http.RequestWrapper;
+
+/**
+ * The Class AuditHelper - build audit requests and send it to audit service.
+ *
+ * @author Manoj SP
+ */
+@Component
+public class AuditHelper {
+
+ /** The rest helper. */
+ @Autowired
+ @Qualifier("withSelfTokenWebclient")
+ private RestHelper restHelper;
+
+ /** The audit factory. */
+ @Autowired
+ private AuditRequestFactory auditFactory;
+
+ /** The rest factory. */
+ @Autowired
+ private RestRequestFactory restFactory;
+
+ @Autowired
+ private ObjectMapper mapper;
+
+ /** The EnvPropertyResolver */
+ @Autowired
+ private EnvUtil env;
+
+
+ /**
+ * Method to build audit requests and send it to audit service.
+ *
+ * @param module {@link AuditModules}
+ * @param event {@link AuditEvents}
+ * @param id UIN/VID
+ * @param idType {@link IdType} enum
+ * @param desc the desc
+ * @throws IDDataValidationException the ID data validation exception
+ */
+ public void audit(AuditModules module, AuditEvents event, String id, IdType idType, String desc)
+ throws IDDataValidationException {
+ audit(module, event, id, idType.name(), desc);
+ }
+
+ /**
+ * Method to build audit requests and send it to audit service.
+ *
+ * @param module {@link AuditModules}
+ * @param event {@link AuditEvents}
+ * @param id UIN/VID
+ * @param idType {@link IdType} name
+ * @param desc the desc
+ * @throws IDDataValidationException the ID data validation exception
+ */
+ public void audit(AuditModules module, AuditEvents event, String id, String idType, String desc)
+ throws IDDataValidationException {
+ RequestWrapper auditRequest = auditFactory.buildRequest(module, event, id, idType, desc);
+ RestRequestDTO restRequest = restFactory.buildRequest(RestServicesConstants.AUDIT_MANAGER_SERVICE, auditRequest,
+ Map.class);
+ restHelper.requestAsync(restRequest);
+ }
+
+ /**
+ * Method to build audit error scenarios and send it to audit service.
+ *
+ * @param module {@link AuditModules}
+ * @param event {@link AuditEvents}
+ * @param id UIN/VID
+ * @param idType {@link IdType} enum
+ * @param desc the desc
+ * @throws IDDataValidationException the ID data validation exception
+ */
+ public void audit(AuditModules module, AuditEvents event, String id, IdType idType, IdAuthenticationBaseException e)
+ throws IDDataValidationException {
+ audit(module, event, id, idType.name(), e);
+ }
+
+ /**
+ * Method to build audit error scenarios and send it to audit service.
+ *
+ * @param module {@link AuditModules}
+ * @param event {@link AuditEvents}
+ * @param id UIN/VID
+ * @param idType {@link IdType} name
+ * @param desc the desc
+ * @throws IDDataValidationException the ID data validation exception
+ */
+ public void audit(AuditModules module, AuditEvents event, String id, String idType, IdAuthenticationBaseException e)
+ throws IDDataValidationException {
+ List errorList = IdAuthExceptionHandler.getAuthErrors(e);
+ String error;
+ try {
+ error = mapper.writeValueAsString(errorList);
+ } catch (JsonProcessingException e1) {
+ //Probably will not occur
+ error = "Error : " + e.getErrorCode() + " - " + e.getErrorText();
+ }
+ audit(module, event, id, idType, error);
+ }
+
+ public void auditExceptionForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO,
+ IdAuthenticationBaseException e) throws IDDataValidationException {
+ List auditModules = getAuditModules(authRequestDTO);
+ for (AuditModules auditModule : auditModules) {
+ audit(auditModule, authAuditEvent, authRequestDTO.getTransactionID(), authRequestDTO.getIndividualIdType(),
+ e);
+ }
+ }
+
+ public void auditStatusForAuthRequestedModules(AuditEvents authAuditEvent, AuthRequestDTO authRequestDTO,
+ String status) throws IDDataValidationException {
+ List auditModules = getAuditModules(authRequestDTO);
+ for (AuditModules auditModule : auditModules) {
+ audit(auditModule, authAuditEvent, authRequestDTO.getTransactionID(), authRequestDTO.getIndividualIdType(),
+ status);
+ }
+ }
+
+ private List getAuditModules(AuthRequestDTO authRequestDTO) {
+ List auditModules = new ArrayList<>(5);
+ if (AuthTypeUtil.isOtp(authRequestDTO)) {
+ auditModules.add(AuditModules.OTP_AUTH);
+ }
+
+ if (AuthTypeUtil.isDemo(authRequestDTO)) {
+ auditModules.add(AuditModules.DEMO_AUTH);
+ }
+
+ if (AuthTypeUtil.isPin(authRequestDTO)) {
+ auditModules.add(AuditModules.PIN_AUTH);
+ }
+
+ if (AuthTypeUtil.isBio(authRequestDTO)) {
+ if (authRequestDTO.getRequest() != null && authRequestDTO.getRequest().getBiometrics() != null) {
+ if ((authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData).anyMatch(
+ bioInfo -> BioAuthType.FGR_IMG.getType().equals(bioInfo.getBioType()) || (EnvUtil.getIsFmrEnabled()
+ && BioAuthType.FGR_MIN.getType().equals(bioInfo.getBioType()))))) {
+ auditModules.add(AuditModules.FINGERPRINT_AUTH);
+ }
+
+ if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData)
+ .anyMatch(bioInfo -> BioAuthType.IRIS_IMG.getType().equals(bioInfo.getBioType()))) {
+ auditModules.add(AuditModules.IRIS_AUTH);
+ }
+
+ if (authRequestDTO.getRequest().getBiometrics().stream().map(BioIdentityInfoDTO::getData)
+ .anyMatch(bioInfo -> BioAuthType.FACE_IMG.getType().equals(bioInfo.getBioType()))) {
+ auditModules.add(AuditModules.FACE_AUTH);
+ }
+ }
+ }
+
+ if (AuthTypeUtil.isKeyBindedToken(authRequestDTO)) {
+ auditModules.add(AuditModules.TOKEN_AUTH);
+ }
+
+ if (AuthTypeUtil.isPassword(authRequestDTO)) {
+ auditModules.add(AuditModules.PASSWORD_AUTH);
+ }
+ return auditModules;
+ }
+
+}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuthTransactionHelper.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuthTransactionHelper.java
index e5572cd6ee2..99e2b2675ba 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuthTransactionHelper.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/AuthTransactionHelper.java
@@ -36,6 +36,7 @@
import io.mosip.authentication.core.indauth.dto.IdType;
import io.mosip.authentication.core.indauth.dto.IdentityKeyBindingRequestDTO;
import io.mosip.authentication.core.indauth.dto.KycExchangeRequestDTO;
+import io.mosip.authentication.core.indauth.dto.VciExchangeRequestDTO;
import io.mosip.authentication.core.logger.IdaLogger;
import io.mosip.authentication.core.otp.dto.OtpRequestDTO;
import io.mosip.authentication.core.partner.dto.PartnerDTO;
@@ -268,7 +269,12 @@ private AuthTransactionBuilder createAuthTxnBuilder(ObjectWithMetadata requestDT
IdentityKeyBindingRequestDTO keyBindingRequestDTO = (IdentityKeyBindingRequestDTO) requestDTO;
authTransactionBuilder.withRequest(keyBindingRequestDTO);
authTransactionBuilder.addRequestType(RequestType.IDENTITY_KEY_BINDING);
- }
+ } else if(requestDTO instanceof VciExchangeRequestDTO) {
+ VciExchangeRequestDTO vciExchangeRequestDTO = (VciExchangeRequestDTO) requestDTO;
+ authTransactionBuilder.withRequest(vciExchangeRequestDTO);
+ authTransactionBuilder.addRequestType(RequestType.VCI_EXCHANGE_REQUEST);
+ }
+
return authTransactionBuilder;
}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java
index c7293860059..21fdcda6afa 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/IdInfoHelper.java
@@ -535,6 +535,12 @@ private Map getEntityInfo(Map> idE
IdAuthenticationErrorConstants.KEY_BINDING_MISSING.getErrorCode(),
String.format(IdAuthenticationErrorConstants.KEY_BINDING_MISSING.getErrorMessage(),
input.getAuthType().getType()));
+
+ case PWD:
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.PASSWORD_MISSING.getErrorCode(),
+ String.format(IdAuthenticationErrorConstants.PASSWORD_MISSING.getErrorMessage(),
+ input.getAuthType().getType()));
}
}
return entityInfo;
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/TokenValidationHelper.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/TokenValidationHelper.java
new file mode 100644
index 00000000000..49cf16533ac
--- /dev/null
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/helper/TokenValidationHelper.java
@@ -0,0 +1,115 @@
+package io.mosip.authentication.common.service.helper;
+
+import java.time.LocalDateTime;
+import java.util.Optional;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import io.mosip.authentication.common.service.entity.KycTokenData;
+import io.mosip.authentication.common.service.repository.KycTokenDataRepository;
+import io.mosip.authentication.core.constant.IdAuthCommonConstants;
+import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
+import io.mosip.authentication.core.constant.KycTokenStatusType;
+import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
+import io.mosip.authentication.core.logger.IdaLogger;
+import io.mosip.authentication.core.spi.indauth.service.KycService;
+import io.mosip.kernel.core.logger.spi.Logger;
+
+/**
+ * Helper class to Validate Token returned in kyc-auth.
+ *
+ * @author Mahammed Taheer
+ */
+
+@Component
+public class TokenValidationHelper {
+
+ /** The mosip logger. */
+ private static Logger mosipLogger = IdaLogger.getLogger(TokenValidationHelper.class);
+
+ /** The Kyc Service */
+ @Autowired
+ private KycService kycService;
+
+ @Autowired
+ private KycTokenDataRepository kycTokenDataRepo;
+
+ public KycTokenData findAndValidateIssuedToken(String tokenData, String oidcClientId, String reqTransactionId,
+ String idvidHash) throws IdAuthenticationBusinessException {
+
+ mosipLogger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "Check Token Exists or not, associated with oidc client and active status.");
+
+ Optional tokenDataOpt = kycTokenDataRepo.findByKycToken(tokenData);
+ if (!tokenDataOpt.isPresent()) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token not found: " + tokenData);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_NOT_FOUND.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_NOT_FOUND.getErrorMessage());
+ }
+ KycTokenData tokenDataObj = tokenDataOpt.get();
+ validateToken(tokenDataObj, oidcClientId, reqTransactionId, idvidHash);
+ return tokenDataObj;
+ }
+
+ private void validateToken(KycTokenData kycTokenData, String oidcClientId, String reqTransactionId, String idvidHash)
+ throws IdAuthenticationBusinessException {
+ String kycToken = kycTokenData.getKycToken();
+ if (kycTokenData.getKycTokenStatus().equals(KycTokenStatusType.PROCESSED.getStatus())) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token already processed: " + kycToken);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_ALREADY_PROCESSED.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_ALREADY_PROCESSED.getErrorMessage());
+ }
+
+ if (kycTokenData.getKycTokenStatus().equals(KycTokenStatusType.EXPIRED.getStatus())) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token expired: " + kycToken);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_EXPIRED.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_EXPIRED.getErrorMessage());
+ }
+
+ if (!kycTokenData.getOidcClientId().equals(oidcClientId)) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token does not belongs to the provided OIDC Client Id: " + kycToken);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_INVALID_OIDC_CLIENT_ID.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_INVALID_OIDC_CLIENT_ID.getErrorMessage());
+ }
+
+ if (!kycTokenData.getIdVidHash().equals(idvidHash)) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token does not belongs to the provided UIN/VID: " + kycToken);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_INVALID_UIN_VID.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_INVALID_UIN_VID.getErrorMessage());
+ }
+
+ if (!kycTokenData.getRequestTransactionId().equals(reqTransactionId)) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Auth & KYC Exchange Transaction Ids are not same: " + kycToken);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_INVALID_TRANSACTION_ID.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_INVALID_TRANSACTION_ID.getErrorMessage());
+ }
+
+ mosipLogger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token found, Check Token expire.");
+ LocalDateTime tokenIssuedDateTime = kycTokenData.getTokenIssuedDateTime();
+ boolean isExpired = kycService.isKycTokenExpire(tokenIssuedDateTime, kycToken);
+
+ if (isExpired) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "findAndValidateIssuedToken",
+ "KYC Token expired.");
+ kycTokenData.setKycTokenStatus(KycTokenStatusType.EXPIRED.getStatus());
+ kycTokenDataRepo.saveAndFlush(kycTokenData);
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.KYC_TOKEN_EXPIRED.getErrorCode(),
+ IdAuthenticationErrorConstants.KYC_TOKEN_EXPIRED.getErrorMessage());
+ }
+ }
+}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/AuthContextClazzRefProvider.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/AuthContextClazzRefProvider.java
index d7927ba0b3a..dde443ae234 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/AuthContextClazzRefProvider.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/AuthContextClazzRefProvider.java
@@ -80,7 +80,7 @@ private AuthMethodsRefValues createAuthMethodsRefValuesObject() throws IdAuthent
logger.error(IdAuthCommonConstants.IDA, this.getClass().getSimpleName(), "createAuthMethodsRefValuesObject",
"Not able to download the AMR-ACR Json config file. URI: " + amracrMappingUri, e);
throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.DOWNLOAD_ERROR.getErrorCode(),
- IdAuthenticationErrorConstants.DOWNLOAD_ERROR.getErrorMessage());
+ IdAuthenticationErrorConstants.DOWNLOAD_ERROR.getErrorMessage());
}
/* ClientResponse clientResponse = webClient.get().uri(amracrMappingUri).accept(MediaType.APPLICATION_JSON).exchange().block();
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java
index be8c0aa7aea..89ecc0d8b1c 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdInfoFetcherImpl.java
@@ -26,6 +26,7 @@
import io.mosip.authentication.common.service.impl.match.IdaIdMapping;
import io.mosip.authentication.common.service.integration.MasterDataManager;
import io.mosip.authentication.common.service.integration.OTPManager;
+import io.mosip.authentication.common.service.integration.PasswordComparator;
import io.mosip.authentication.common.service.util.BioMatcherUtil;
import io.mosip.authentication.common.service.util.EnvUtil;
import io.mosip.authentication.core.constant.IdAuthCommonConstants;
@@ -37,6 +38,7 @@
import io.mosip.authentication.core.indauth.dto.RequestDTO;
import io.mosip.authentication.core.spi.bioauth.CbeffDocType;
import io.mosip.authentication.core.spi.indauth.match.AuthType;
+import io.mosip.authentication.core.spi.indauth.match.ComparePasswordFunction;
import io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher;
import io.mosip.authentication.core.spi.indauth.match.IdMapping;
import io.mosip.authentication.core.spi.indauth.match.MappingConfig;
@@ -96,6 +98,9 @@ public class IdInfoFetcherImpl implements IdInfoFetcher {
@Autowired(required = false)
private KeyBindedTokenMatcherUtil keyBindedTokenMatcherUtil;
+
+ @Autowired(required = false)
+ private PasswordComparator passwordComparator;
/**
* Gets the demo normalizer.
@@ -566,10 +571,23 @@ public List getUserPreferredLanguages(Map>
if (userPreferredLangAttribute != null) {
List identityInfoList = idInfo.get(userPreferredLangAttribute);
if (identityInfoList != null) {
- return identityInfoList.stream().map(IdentityInfoDTO::getValue).collect(Collectors.toList());
+ return identityInfoList.stream().map(info -> info.getValue().split(","))
+ .flatMap(java.util.Arrays::stream)
+ .collect(Collectors.toList());
}
return Collections.emptyList();
}
return Collections.emptyList();
}
+
+ /*
+ * Get Match password Function
+ *
+ * @see io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher#
+ * getMatchPasswordFunction()
+ */
+ @Override
+ public ComparePasswordFunction getMatchPasswordFunction() {
+ return passwordComparator::matchPasswordFunction;
+ }
}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java
index fb5949bcd68..452a1c30d14 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/IdServiceImpl.java
@@ -118,7 +118,7 @@ public Map getIdByVid(String vid, boolean isBio, Set fil
public Map processIdType(String idvIdType, String idvId, boolean isBio, boolean markVidConsumed, Set filterAttributes)
throws IdAuthenticationBusinessException {
Map idResDTO = null;
- if (idvIdType.equals(IdType.UIN.getType())) {
+ if (idvIdType.equals(IdType.UIN.getType()) || idvIdType.equals(IdType.HANDLE.getType())) {
try {
idResDTO = getIdByUin(idvId, isBio, filterAttributes);
} catch (IdAuthenticationBusinessException e) {
@@ -205,6 +205,9 @@ public Map getIdentity(String id, boolean isBio, IdType idType,
idType.getType()));
}
+ logger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "getIdentity",
+ "Generated HASHID >> " + hashedId);
+
if (isBio) {
entity = identityRepo.getOne(hashedId);
} else {
@@ -254,6 +257,8 @@ public Map getIdentity(String id, boolean isBio, IdType idType,
}
responseMap.put(TOKEN, entity.getToken());
responseMap.put(ID_HASH, hashedId);
+ logger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "getIdentity",
+ "TOKEN in responseMap >> " + entity.getToken());
return responseMap;
} catch (IOException | DataAccessException | TransactionException | JDBCConnectionException e) {
logger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getSimpleName(), "getIdentity",
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/OTPServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/OTPServiceImpl.java
index 905d2b5371c..345367b2ee1 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/OTPServiceImpl.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/OTPServiceImpl.java
@@ -1,377 +1,414 @@
-package io.mosip.authentication.common.service.impl;
-
-import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.time.temporal.ChronoUnit;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import io.mosip.authentication.authfilter.exception.IdAuthenticationFilterException;
-import io.mosip.authentication.common.service.entity.AuthtypeLock;
-import io.mosip.authentication.common.service.repository.AuthLockRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Service;
-
-import io.mosip.authentication.common.manager.IdAuthFraudAnalysisEventManager;
-import io.mosip.authentication.common.service.builder.AuthTransactionBuilder;
-import io.mosip.authentication.common.service.entity.AutnTxn;
-import io.mosip.authentication.common.service.helper.IdInfoHelper;
-import io.mosip.authentication.common.service.impl.match.DemoMatchType;
-import io.mosip.authentication.common.service.integration.OTPManager;
-import io.mosip.authentication.common.service.integration.TokenIdManager;
-import io.mosip.authentication.common.service.repository.AutnTxnRepository;
-import io.mosip.authentication.common.service.repository.IdaUinHashSaltRepo;
-import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
-import io.mosip.authentication.common.service.util.EnvUtil;
-import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
-import io.mosip.authentication.core.constant.IdAuthCommonConstants;
-import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
-import io.mosip.authentication.core.constant.RequestType;
-import io.mosip.authentication.core.dto.ObjectWithMetadata;
-import io.mosip.authentication.core.exception.IDDataValidationException;
-import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
-import io.mosip.authentication.core.indauth.dto.IdType;
-import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO;
-import io.mosip.authentication.core.indauth.dto.NotificationType;
-import io.mosip.authentication.core.logger.IdaLogger;
-import io.mosip.authentication.core.otp.dto.MaskedResponseDTO;
-import io.mosip.authentication.core.otp.dto.OtpRequestDTO;
-import io.mosip.authentication.core.otp.dto.OtpResponseDTO;
-import io.mosip.authentication.core.partner.dto.PartnerDTO;
-import io.mosip.authentication.core.spi.id.service.IdService;
-import io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher;
-import io.mosip.authentication.core.spi.otp.service.OTPService;
-import io.mosip.authentication.core.spi.partner.service.PartnerService;
-import io.mosip.authentication.core.util.LanguageComparator;
-import io.mosip.authentication.core.util.MaskUtil;
-import io.mosip.kernel.core.exception.ParseException;
-import io.mosip.kernel.core.logger.spi.Logger;
-import io.mosip.kernel.core.util.DateUtils;
-
-/**
- * Service implementation of OtpTriggerService.
- *
- * @author Rakesh Roshan
- * @author Dinesh Karuppiah.T
- */
-@Service
-public class OTPServiceImpl implements OTPService {
-
- /** The Constant NAME. */
- private static final String NAME = "name";
- private static final String OTP = "otp";
- private static final String PHONE = "PHONE";
- private static final String EMAIL = "EMAIL";
- private static final String OTP_SMS = "otp-sms";
- private static final String OTP_EMAIL = "otp-email";
-
-
- /** The id auth service. */
- @Autowired
- private IdService idAuthService;
-
- /** The autntxnrepository. */
- @Autowired
- private AutnTxnRepository autntxnrepository;
-
- /** The auth lock repository. */
- @Autowired
- AuthLockRepository authLockRepository;
-
- /** The env. */
- @Autowired
- private EnvUtil env;
-
- @Autowired
- private IdInfoHelper idInfoHelper;
-
- @Autowired
- private IdInfoFetcher idInfoFetcher;
-
- /** The otp manager. */
- @Autowired
- private OTPManager otpManager;
-
- /** The TokenId manager */
- @Autowired
- private TokenIdManager tokenIdManager;
-
- @Autowired
- private IdaUinHashSaltRepo uinHashSaltRepo;
-
- @Autowired
- private IdAuthSecurityManager securityManager;
-
- @Autowired
- private PartnerService partnerService;
-
- @Autowired
- private IdAuthFraudAnalysisEventManager fraudEventManager;
-
- @Autowired
- @Qualifier("NotificationLangComparator")
- private LanguageComparator languageComparator;
-
- /** The mosip logger. */
- private static Logger mosipLogger = IdaLogger.getLogger(OTPServiceImpl.class);
-
- /**
- * Generate OTP, store the OTP request details for success/failure. And send OTP
- * notification by sms(on mobile)/mail(on email-id).
- *
- * @param otpRequestDto the otp request dto
- * @return otpResponseDTO
- * @throws IdAuthenticationBusinessException the id authentication business
- * exception
- */
- @Override
- public OtpResponseDTO generateOtp(OtpRequestDTO otpRequestDto, String partnerId, ObjectWithMetadata requestWithMetadata)
- throws IdAuthenticationBusinessException {
- boolean isInternal = partnerId != null && partnerId.equalsIgnoreCase(IdAuthCommonConstants.INTERNAL);
- boolean status;
- String token = null;
- try {
- String individualIdType = IdType.getIDTypeStrOrDefault(otpRequestDto.getIndividualIdType());
- String individualId = otpRequestDto.getIndividualId();
-
- Map idResDTO = idAuthService.processIdType(individualIdType, individualId, false, false,
- idInfoHelper.getDefaultFilterAttributes());
-
- token = idAuthService.getToken(idResDTO);
-
- validateAllowedOtpChannles(token, otpRequestDto.getOtpChannel());
-
- OtpResponseDTO otpResponseDTO = doGenerateOTP(otpRequestDto, partnerId, isInternal, token, individualIdType, idResDTO);
- IdaRequestResponsConsumerUtil.setIdVersionToResponse(requestWithMetadata, otpResponseDTO);
-
- status = otpResponseDTO.getErrors() == null || otpResponseDTO.getErrors().isEmpty();
- saveToTxnTable(otpRequestDto, isInternal, status, partnerId, token, otpResponseDTO, requestWithMetadata);
-
- return otpResponseDTO;
-
- } catch(IdAuthenticationBusinessException e) {
- status = false;
- //FIXME check if for this condition auth transaction is stored, then remove below code
- //saveToTxnTable(otpRequestDto, isInternal, status, partnerId, token, null, null);
- throw e;
- }
-
-
- }
-
- private void validateAllowedOtpChannles(String token, List otpChannel) throws IdAuthenticationFilterException {
-
- if(otpChannel.stream().anyMatch(channel -> OTP.equalsIgnoreCase(channel))) {
- checkAuthLock(token, OTP);
- }
- else if(otpChannel.stream().anyMatch(channel -> PHONE.equalsIgnoreCase(channel))) {
- checkAuthLock(token, OTP_SMS);
- }
- else if(otpChannel.stream().anyMatch(channel -> EMAIL.equalsIgnoreCase(channel))) {
- checkAuthLock(token, OTP_EMAIL);
- }
- }
-
- private void checkAuthLock(String token, String authTypeCode) throws IdAuthenticationFilterException {
- List authTypeLocks = authLockRepository.findByTokenAndAuthtypecode(token, authTypeCode);
- for(AuthtypeLock authtypeLock : authTypeLocks) {
- if(authtypeLock.getStatuscode().equalsIgnoreCase("true")){
- throw new IdAuthenticationFilterException(
- IdAuthenticationErrorConstants.AUTH_TYPE_LOCKED.getErrorCode(),
- String.format(IdAuthenticationErrorConstants.AUTH_TYPE_LOCKED.getErrorMessage(),
- authTypeCode));
- }
- }
- }
-
- private void saveToTxnTable(OtpRequestDTO otpRequestDto, boolean isInternal, boolean status, String partnerId, String token, OtpResponseDTO otpResponseDTO, ObjectWithMetadata requestWithMetadata)
- throws IdAuthenticationBusinessException {
- if (token != null) {
- boolean authTokenRequired = !isInternal
- && EnvUtil.getAuthTokenRequired();
- String authTokenId = authTokenRequired ? tokenIdManager.generateTokenId(token, partnerId) : null;
- saveTxn(otpRequestDto, token, authTokenId, status, partnerId, isInternal, otpResponseDTO, requestWithMetadata);
- }
- }
-
- private OtpResponseDTO doGenerateOTP(OtpRequestDTO otpRequestDto, String partnerId, boolean isInternal, String token, String individualIdType, Map idResDTO)
- throws IdAuthenticationBusinessException, IDDataValidationException {
- String individualId = otpRequestDto.getIndividualId();
- String requestTime = otpRequestDto.getRequestTime();
- OtpResponseDTO otpResponseDTO = new OtpResponseDTO();
-
- if (isOtpFlooded(token, requestTime)) {
- throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.OTP_REQUEST_FLOODED);
- } else {
- String transactionId = otpRequestDto.getTransactionID();
- otpResponseDTO.setId(otpRequestDto.getId());
- otpResponseDTO.setTransactionID(transactionId);
-
- Map> idInfo = IdInfoFetcher.getIdInfo(idResDTO);
- Map valueMap = new HashMap<>();
-
- List templateLanguages = getTemplateLanguages(idInfo);
- for (String lang : templateLanguages) {
- valueMap.put(NAME + "_" + lang, getName(lang, idInfo));
- }
-
- String email = getEmail(idInfo);
- String phoneNumber = getPhoneNumber(idInfo);
- valueMap.put(IdAuthCommonConstants.PHONE_NUMBER, phoneNumber);
- valueMap.put(IdAuthCommonConstants.EMAIL, email);
-
- boolean isOtpGenerated = otpManager.sendOtp(otpRequestDto, individualId, individualIdType, valueMap,
- templateLanguages);
-
- if (isOtpGenerated) {
- otpResponseDTO.setErrors(null);
- String responseTime = IdaRequestResponsConsumerUtil.getResponseTime(otpRequestDto.getRequestTime(),
- EnvUtil.getDateTimePattern());
- otpResponseDTO.setResponseTime(responseTime);
- MaskedResponseDTO maskedResponseDTO = new MaskedResponseDTO();
- List otpChannels = otpRequestDto.getOtpChannel();
- for (String channel : otpChannels) {
- processChannel(channel, phoneNumber, email, maskedResponseDTO);
- }
- otpResponseDTO.setResponse(maskedResponseDTO);
-
- mosipLogger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(), this.getClass().getName(),
- " is OTP generated: " + isOtpGenerated);
- } else {
- mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(),
- this.getClass().getName(), "OTP Generation failed");
- throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.OTP_GENERATION_FAILED);
- }
-
- }
- return otpResponseDTO;
- }
-
- /**
- * Audit txn.
- *
- * @param otpRequestDto the otp request dto
- * @param token the uin
- * @param authTokenId the auth token id
- * @param status the status
- * @param otpResponseDTO
- * @param requestWithMetadata
- * @throws IdAuthenticationBusinessException the id authentication business
- * exception
- */
- private void saveTxn(OtpRequestDTO otpRequestDto, String token, String authTokenId, boolean status, String partnerId, boolean isInternal, OtpResponseDTO otpResponseDTO, ObjectWithMetadata requestWithMetadata)
- throws IdAuthenticationBusinessException {
- Optional partner = isInternal ? Optional.empty() : partnerService.getPartner(partnerId, otpRequestDto.getMetadata());
- AutnTxn authTxn = AuthTransactionBuilder.newInstance()
- .withRequest(otpRequestDto)
- .addRequestType(RequestType.OTP_REQUEST)
- .withAuthToken(authTokenId)
- .withStatus(status)
- .withToken(token)
- .withPartner(partner)
- .withInternal(isInternal)
- .build(env,uinHashSaltRepo,securityManager);
- fraudEventManager.analyseEvent(authTxn);
- if(requestWithMetadata != null) {
- requestWithMetadata.setMetadata(Map.of(AutnTxn.class.getSimpleName(), authTxn));
- } else {
- idAuthService.saveAutnTxn(authTxn);
- }
- }
-
- private String getName(String language, Map> idInfo)
- throws IdAuthenticationBusinessException {
- return idInfoHelper.getEntityInfoAsString(DemoMatchType.NAME, language, idInfo);
-
- }
-
- /**
- * Validate the number of request for OTP generation. Limit for the number of
- * request for OTP is should not exceed 3 in 60sec.
- *
- * @return true, if is otp flooded
- * @throws IdAuthenticationBusinessException
- */
- private boolean isOtpFlooded(String token, String requestTime) throws IdAuthenticationBusinessException {
- boolean isOtpFlooded = false;
- LocalDateTime reqTime;
- try {
- String strUTCDate = DateUtils.getUTCTimeFromDate(
- DateUtils.parseToDate(requestTime, EnvUtil.getDateTimePattern()));
- reqTime = LocalDateTime.parse(strUTCDate,
- DateTimeFormatter.ofPattern(EnvUtil.getDateTimePattern()));
-
- } catch (ParseException e) {
- mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(), e.getClass().getName(),
- e.getMessage());
- throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.UNABLE_TO_PROCESS, e);
- }
- int addMinutes = EnvUtil.getOtpRequestFloodingDuration();
- LocalDateTime addMinutesInOtpRequestDTimes = reqTime.minus(addMinutes, ChronoUnit.MINUTES);
- int maxCount = EnvUtil.getOtpRequestFloodingMaxCount();
- if (autntxnrepository.countRequestDTime(reqTime, addMinutesInOtpRequestDTimes, token) > maxCount) {
- isOtpFlooded = true;
- }
- return isOtpFlooded;
- }
-
- private void processChannel(String value, String phone, String email, MaskedResponseDTO maskedResponseDTO) throws IdAuthenticationBusinessException {
- if (value.equalsIgnoreCase(NotificationType.SMS.getChannel())) {
- maskedResponseDTO.setMaskedMobile(MaskUtil.maskMobile(phone));
- } else if (value.equalsIgnoreCase(NotificationType.EMAIL.getChannel())) {
- maskedResponseDTO.setMaskedEmail(MaskUtil.maskEmail(email));
- }
-
- }
-
- /**
- * Get Mail.
- *
- * @param idInfo List of IdentityInfoDTO
- * @return mail
- * @throws IdAuthenticationBusinessException
- */
- private String getEmail(Map> idInfo) throws IdAuthenticationBusinessException {
- return idInfoHelper.getEntityInfoAsString(DemoMatchType.EMAIL, idInfo);
- }
-
- /**
- * Get Mobile number.
- *
- * @param idInfo List of IdentityInfoDTO
- * @return Mobile number
- * @throws IdAuthenticationBusinessException
- */
- private String getPhoneNumber(Map> idInfo) throws IdAuthenticationBusinessException {
- return idInfoHelper.getEntityInfoAsString(DemoMatchType.PHONE, idInfo);
- }
-
- /**
- * This method gets the template languages in following order.
- * 1. Gets user preferred languages if not
- * 2. Gets default template languages from configuration if not
- * 3. Gets the data capture languages
- * @param idInfo
- * @return
- * @throws IdAuthenticationBusinessException
- */
- private List getTemplateLanguages(Map> idInfo)
- throws IdAuthenticationBusinessException {
- List userPreferredLangs = idInfoFetcher.getUserPreferredLanguages(idInfo);
- List defaultTemplateLanguges = userPreferredLangs.isEmpty()
- ? idInfoFetcher.getTemplatesDefaultLanguageCodes()
- : userPreferredLangs;
- if (defaultTemplateLanguges.isEmpty()) {
- List dataCaptureLanguages = idInfoHelper.getDataCapturedLanguages(DemoMatchType.NAME, idInfo);
- Collections.sort(dataCaptureLanguages, languageComparator);
- return dataCaptureLanguages;
- }
-
- return defaultTemplateLanguges;
-
- }
+package io.mosip.authentication.common.service.impl;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import io.mosip.authentication.authfilter.exception.IdAuthenticationFilterException;
+import io.mosip.authentication.common.service.entity.AuthtypeLock;
+import io.mosip.authentication.common.service.repository.AuthLockRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Service;
+
+import io.mosip.authentication.common.manager.IdAuthFraudAnalysisEventManager;
+import io.mosip.authentication.common.service.builder.AuthTransactionBuilder;
+import io.mosip.authentication.common.service.entity.AutnTxn;
+import io.mosip.authentication.common.service.helper.IdInfoHelper;
+import io.mosip.authentication.common.service.impl.match.DemoMatchType;
+import io.mosip.authentication.common.service.integration.OTPManager;
+import io.mosip.authentication.common.service.integration.TokenIdManager;
+import io.mosip.authentication.common.service.repository.AutnTxnRepository;
+import io.mosip.authentication.common.service.repository.IdaUinHashSaltRepo;
+import io.mosip.authentication.common.service.transaction.manager.IdAuthSecurityManager;
+import io.mosip.authentication.common.service.util.EnvUtil;
+import io.mosip.authentication.common.service.util.IdaRequestResponsConsumerUtil;
+import io.mosip.authentication.core.constant.IdAuthCommonConstants;
+import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
+import io.mosip.authentication.core.constant.RequestType;
+import io.mosip.authentication.core.dto.ObjectWithMetadata;
+import io.mosip.authentication.core.exception.IDDataValidationException;
+import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
+import io.mosip.authentication.core.indauth.dto.IdType;
+import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO;
+import io.mosip.authentication.core.indauth.dto.NotificationType;
+import io.mosip.authentication.core.logger.IdaLogger;
+import io.mosip.authentication.core.otp.dto.MaskedResponseDTO;
+import io.mosip.authentication.core.otp.dto.OtpRequestDTO;
+import io.mosip.authentication.core.otp.dto.OtpResponseDTO;
+import io.mosip.authentication.core.partner.dto.PartnerDTO;
+import io.mosip.authentication.core.spi.id.service.IdService;
+import io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher;
+import io.mosip.authentication.core.spi.otp.service.OTPService;
+import io.mosip.authentication.core.spi.partner.service.PartnerService;
+import io.mosip.authentication.core.util.LanguageComparator;
+import io.mosip.authentication.core.util.MaskUtil;
+import io.mosip.kernel.core.exception.ParseException;
+import io.mosip.kernel.core.logger.spi.Logger;
+import io.mosip.kernel.core.util.DateUtils;
+import io.mosip.kernel.core.util.StringUtils;
+
+/**
+ * Service implementation of OtpTriggerService.
+ *
+ * @author Rakesh Roshan
+ * @author Dinesh Karuppiah.T
+ */
+@Service
+public class OTPServiceImpl implements OTPService {
+
+ /** The Constant NAME. */
+ private static final String NAME = "name";
+ private static final String OTP = "otp";
+ private static final String PHONE = "PHONE";
+ private static final String EMAIL = "EMAIL";
+ private static final String OTP_SMS = "otp-sms";
+ private static final String OTP_EMAIL = "otp-email";
+
+
+ /** The id auth service. */
+ @Autowired
+ private IdService idAuthService;
+
+ /** The autntxnrepository. */
+ @Autowired
+ private AutnTxnRepository autntxnrepository;
+
+ /** The auth lock repository. */
+ @Autowired
+ AuthLockRepository authLockRepository;
+
+ /** The env. */
+ @Autowired
+ private EnvUtil env;
+
+ @Autowired
+ private IdInfoHelper idInfoHelper;
+
+ @Autowired
+ private IdInfoFetcher idInfoFetcher;
+
+ /** The otp manager. */
+ @Autowired
+ private OTPManager otpManager;
+
+ /** The TokenId manager */
+ @Autowired
+ private TokenIdManager tokenIdManager;
+
+ @Autowired
+ private IdaUinHashSaltRepo uinHashSaltRepo;
+
+ @Autowired
+ private IdAuthSecurityManager securityManager;
+
+ @Autowired
+ private PartnerService partnerService;
+
+ @Autowired
+ private IdAuthFraudAnalysisEventManager fraudEventManager;
+
+ @Autowired
+ @Qualifier("NotificationLangComparator")
+ private LanguageComparator languageComparator;
+
+ /** The mosip logger. */
+ private static Logger mosipLogger = IdaLogger.getLogger(OTPServiceImpl.class);
+
+ /**
+ * Generate OTP, store the OTP request details for success/failure. And send OTP
+ * notification by sms(on mobile)/mail(on email-id).
+ *
+ * @param otpRequestDto the otp request dto
+ * @return otpResponseDTO
+ * @throws IdAuthenticationBusinessException the id authentication business
+ * exception
+ */
+ @Override
+ public OtpResponseDTO generateOtp(OtpRequestDTO otpRequestDto, String partnerId, ObjectWithMetadata requestWithMetadata)
+ throws IdAuthenticationBusinessException {
+ boolean isInternal = partnerId != null && partnerId.equalsIgnoreCase(IdAuthCommonConstants.INTERNAL);
+ boolean status;
+ String token = null;
+ try {
+ String individualIdType = IdType.getIDTypeStrOrDefault(otpRequestDto.getIndividualIdType());
+ String individualId = otpRequestDto.getIndividualId();
+
+ Map idResDTO = idAuthService.processIdType(individualIdType, individualId, false, false,
+ idInfoHelper.getDefaultFilterAttributes());
+
+ token = idAuthService.getToken(idResDTO);
+
+ validateAllowedOtpChannles(token, otpRequestDto.getOtpChannel());
+
+ OtpResponseDTO otpResponseDTO = doGenerateOTP(otpRequestDto, partnerId, isInternal, token, individualIdType, idResDTO);
+ IdaRequestResponsConsumerUtil.setIdVersionToResponse(requestWithMetadata, otpResponseDTO);
+
+ status = otpResponseDTO.getErrors() == null || otpResponseDTO.getErrors().isEmpty();
+ saveToTxnTable(otpRequestDto, isInternal, status, partnerId, token, otpResponseDTO, requestWithMetadata);
+
+ return otpResponseDTO;
+
+ } catch(IdAuthenticationBusinessException e) {
+ status = false;
+ //FIXME check if for this condition auth transaction is stored, then remove below code
+ //saveToTxnTable(otpRequestDto, isInternal, status, partnerId, token, null, null);
+ throw e;
+ }
+
+
+ }
+
+ private void validateAllowedOtpChannles(String token, List otpChannel) throws IdAuthenticationFilterException {
+
+ if(containsChannel(otpChannel, OTP)) {
+ checkAuthLock(token, OTP);
+ }
+ else if(containsChannel(otpChannel, PHONE)) {
+ checkAuthLock(token, OTP_SMS);
+ }
+ else if(containsChannel(otpChannel, EMAIL)) {
+ checkAuthLock(token, OTP_EMAIL);
+ }
+ }
+
+ private static boolean containsChannel(List otpChannel, String channel) {
+ return otpChannel.stream().anyMatch(channelItem -> channel.equalsIgnoreCase(channelItem));
+ }
+
+ private void checkAuthLock(String token, String authTypeCode) throws IdAuthenticationFilterException {
+ List authTypeLocks = authLockRepository.findByTokenAndAuthtypecode(token, authTypeCode);
+ for(AuthtypeLock authtypeLock : authTypeLocks) {
+ if(authtypeLock.getStatuscode().equalsIgnoreCase("true")){
+ throw new IdAuthenticationFilterException(
+ IdAuthenticationErrorConstants.AUTH_TYPE_LOCKED.getErrorCode(),
+ String.format(IdAuthenticationErrorConstants.AUTH_TYPE_LOCKED.getErrorMessage(),
+ authTypeCode));
+ }
+ }
+ }
+
+ private void saveToTxnTable(OtpRequestDTO otpRequestDto, boolean isInternal, boolean status, String partnerId, String token, OtpResponseDTO otpResponseDTO, ObjectWithMetadata requestWithMetadata)
+ throws IdAuthenticationBusinessException {
+ if (token != null) {
+ boolean authTokenRequired = !isInternal
+ && EnvUtil.getAuthTokenRequired();
+ String authTokenId = authTokenRequired ? tokenIdManager.generateTokenId(token, partnerId) : null;
+ saveTxn(otpRequestDto, token, authTokenId, status, partnerId, isInternal, otpResponseDTO, requestWithMetadata);
+ }
+ }
+
+ private OtpResponseDTO doGenerateOTP(OtpRequestDTO otpRequestDto, String partnerId, boolean isInternal, String token, String individualIdType, Map idResDTO)
+ throws IdAuthenticationBusinessException, IDDataValidationException {
+ String individualId = otpRequestDto.getIndividualId();
+ String requestTime = otpRequestDto.getRequestTime();
+ OtpResponseDTO otpResponseDTO = new OtpResponseDTO();
+
+ if (isOtpFlooded(token, requestTime)) {
+ throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.OTP_REQUEST_FLOODED);
+ } else {
+ String transactionId = otpRequestDto.getTransactionID();
+ otpResponseDTO.setId(otpRequestDto.getId());
+ otpResponseDTO.setTransactionID(transactionId);
+
+ Map> idInfo = IdInfoFetcher.getIdInfo(idResDTO);
+ Map valueMap = new HashMap<>();
+
+ List templateLanguages = getTemplateLanguages(idInfo);
+ for (String lang : templateLanguages) {
+ valueMap.put(NAME + "_" + lang, getName(lang, idInfo));
+ }
+
+ String email = getEmail(idInfo);
+ String phoneNumber = getPhoneNumber(idInfo);
+ valueMap.put(IdAuthCommonConstants.PHONE_NUMBER, phoneNumber);
+ valueMap.put(IdAuthCommonConstants.EMAIL, email);
+
+ List otpChannel = otpRequestDto.getOtpChannel();
+ if (StringUtils.isBlank(phoneNumber) && containsChannel(otpChannel, PHONE) && !containsChannel(otpChannel, EMAIL)) {
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.OTP_GENERATION_FAILED.getErrorCode(),
+ IdAuthenticationErrorConstants.OTP_GENERATION_FAILED.getErrorMessage()
+ + ". Phone Number is not found in identity data.");
+ }
+
+ if (StringUtils.isBlank(email) && containsChannel(otpChannel, EMAIL) && !containsChannel(otpChannel, PHONE)) {
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.OTP_GENERATION_FAILED.getErrorCode(),
+ IdAuthenticationErrorConstants.OTP_GENERATION_FAILED.getErrorMessage()
+ + ". Email ID is not found in identity data.");
+ }
+
+ if(StringUtils.isBlank(phoneNumber) && StringUtils.isBlank(email) && (containsChannel(otpChannel, PHONE) && containsChannel(otpChannel, EMAIL))) {
+ throw new IdAuthenticationBusinessException(
+ IdAuthenticationErrorConstants.OTP_GENERATION_FAILED.getErrorCode(),
+ IdAuthenticationErrorConstants.OTP_GENERATION_FAILED.getErrorMessage()
+ + ". Both Phone Number and Email ID are not found in identity data.");
+ }
+
+ boolean isOtpGenerated = otpManager.sendOtp(otpRequestDto, individualId, individualIdType, valueMap,
+ templateLanguages);
+
+ if (isOtpGenerated) {
+ otpResponseDTO.setErrors(null);
+ String responseTime = IdaRequestResponsConsumerUtil.getResponseTime(otpRequestDto.getRequestTime(),
+ EnvUtil.getDateTimePattern());
+ otpResponseDTO.setResponseTime(responseTime);
+ MaskedResponseDTO maskedResponseDTO = new MaskedResponseDTO();
+ List otpChannels = otpRequestDto.getOtpChannel();
+ for (String channel : otpChannels) {
+ processChannel(channel, phoneNumber, email, maskedResponseDTO);
+ }
+ otpResponseDTO.setResponse(maskedResponseDTO);
+
+ mosipLogger.info(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(), this.getClass().getName(),
+ " is OTP generated: " + isOtpGenerated);
+ } else {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(),
+ this.getClass().getName(), "OTP Generation failed");
+ throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.OTP_GENERATION_FAILED);
+ }
+
+ }
+ return otpResponseDTO;
+ }
+
+ /**
+ * Audit txn.
+ *
+ * @param otpRequestDto the otp request dto
+ * @param token the uin
+ * @param authTokenId the auth token id
+ * @param status the status
+ * @param otpResponseDTO
+ * @param requestWithMetadata
+ * @throws IdAuthenticationBusinessException the id authentication business
+ * exception
+ */
+ private void saveTxn(OtpRequestDTO otpRequestDto, String token, String authTokenId, boolean status, String partnerId, boolean isInternal, OtpResponseDTO otpResponseDTO, ObjectWithMetadata requestWithMetadata)
+ throws IdAuthenticationBusinessException {
+ Optional partner = isInternal ? Optional.empty() : partnerService.getPartner(partnerId, otpRequestDto.getMetadata());
+ AutnTxn authTxn = AuthTransactionBuilder.newInstance()
+ .withRequest(otpRequestDto)
+ .addRequestType(RequestType.OTP_REQUEST)
+ .withAuthToken(authTokenId)
+ .withStatus(status)
+ .withToken(token)
+ .withPartner(partner)
+ .withInternal(isInternal)
+ .build(env,uinHashSaltRepo,securityManager);
+ fraudEventManager.analyseEvent(authTxn);
+ if(requestWithMetadata != null) {
+ requestWithMetadata.setMetadata(Map.of(AutnTxn.class.getSimpleName(), authTxn));
+ } else {
+ idAuthService.saveAutnTxn(authTxn);
+ }
+ }
+
+ private String getName(String language, Map> idInfo)
+ throws IdAuthenticationBusinessException {
+ return idInfoHelper.getEntityInfoAsString(DemoMatchType.NAME, language, idInfo);
+
+ }
+
+ /**
+ * Validate the number of request for OTP generation. Limit for the number of
+ * request for OTP is should not exceed 3 in 60sec.
+ *
+ * @return true, if is otp flooded
+ * @throws IdAuthenticationBusinessException
+ */
+ private boolean isOtpFlooded(String token, String requestTime) throws IdAuthenticationBusinessException {
+ boolean isOtpFlooded = false;
+ LocalDateTime reqTime;
+ try {
+ String strUTCDate = DateUtils.getUTCTimeFromDate(
+ DateUtils.parseToDate(requestTime, EnvUtil.getDateTimePattern()));
+ reqTime = LocalDateTime.parse(strUTCDate,
+ DateTimeFormatter.ofPattern(EnvUtil.getDateTimePattern()));
+
+ } catch (ParseException e) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(), e.getClass().getName(),
+ e.getMessage());
+ throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.UNABLE_TO_PROCESS, e);
+ }
+ int addMinutes = EnvUtil.getOtpRequestFloodingDuration();
+ LocalDateTime addMinutesInOtpRequestDTimes = reqTime.minus(addMinutes, ChronoUnit.MINUTES);
+ int maxCount = EnvUtil.getOtpRequestFloodingMaxCount();
+ if (autntxnrepository.countRequestDTime(reqTime, addMinutesInOtpRequestDTimes, token) >= maxCount) {
+ mosipLogger.error(IdAuthCommonConstants.SESSION_ID, this.getClass().getName(), this.getClass().getName(),
+ " OTP requested Flooded: " + reqTime + "," + addMinutesInOtpRequestDTimes + "," + maxCount);
+ isOtpFlooded = true;
+ }
+ return isOtpFlooded;
+ }
+
+ private void processChannel(String value, String phone, String email, MaskedResponseDTO maskedResponseDTO) throws IdAuthenticationBusinessException {
+ if (value.equalsIgnoreCase(NotificationType.SMS.getChannel())) {
+ if(phone != null && !phone.isEmpty()) {
+ maskedResponseDTO.setMaskedMobile(MaskUtil.maskMobile(phone));
+ } else {
+ mosipLogger.warn("Phone Number is not available in identity data. But PHONE channel is requested for OTP.");
+ }
+ } else if (value.equalsIgnoreCase(NotificationType.EMAIL.getChannel())) {
+ if(email != null && !email.isEmpty()) {
+ maskedResponseDTO.setMaskedEmail(MaskUtil.maskEmail(email));
+ } else {
+ mosipLogger.warn("Email ID is not available in identity data. But email channel is requested for OTP.");
+ }
+ }
+
+ }
+
+ /**
+ * Get Mail.
+ *
+ * @param idInfo List of IdentityInfoDTO
+ * @return mail
+ * @throws IdAuthenticationBusinessException
+ */
+ private String getEmail(Map> idInfo) throws IdAuthenticationBusinessException {
+ return idInfoHelper.getEntityInfoAsString(DemoMatchType.EMAIL, idInfo);
+ }
+
+ /**
+ * Get Mobile number.
+ *
+ * @param idInfo List of IdentityInfoDTO
+ * @return Mobile number
+ * @throws IdAuthenticationBusinessException
+ */
+ private String getPhoneNumber(Map> idInfo) throws IdAuthenticationBusinessException {
+ return idInfoHelper.getEntityInfoAsString(DemoMatchType.PHONE, idInfo);
+ }
+
+ /**
+ * This method gets the template languages in following order.
+ * 1. Gets user preferred languages if not
+ * 2. Gets default template languages from configuration if not
+ * 3. Gets the data capture languages
+ * @param idInfo
+ * @return
+ * @throws IdAuthenticationBusinessException
+ */
+ private List getTemplateLanguages(Map> idInfo)
+ throws IdAuthenticationBusinessException {
+ List userPreferredLangs = idInfoFetcher.getUserPreferredLanguages(idInfo);
+ List defaultTemplateLanguges = userPreferredLangs.isEmpty()
+ ? idInfoFetcher.getTemplatesDefaultLanguageCodes()
+ : userPreferredLangs;
+ if (defaultTemplateLanguges.isEmpty()) {
+ List dataCaptureLanguages = idInfoHelper.getDataCapturedLanguages(DemoMatchType.NAME, idInfo);
+ Collections.sort(dataCaptureLanguages, languageComparator);
+ return dataCaptureLanguages;
+ }
+
+ return defaultTemplateLanguges;
+
+ }
}
\ No newline at end of file
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/PasswordAuthServiceImpl.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/PasswordAuthServiceImpl.java
new file mode 100644
index 00000000000..d337d55c482
--- /dev/null
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/PasswordAuthServiceImpl.java
@@ -0,0 +1,70 @@
+package io.mosip.authentication.common.service.impl;
+
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import io.mosip.authentication.common.service.builder.AuthStatusInfoBuilder;
+import io.mosip.authentication.common.service.builder.MatchInputBuilder;
+import io.mosip.authentication.common.service.config.IDAMappingConfig;
+import io.mosip.authentication.common.service.helper.IdInfoHelper;
+import io.mosip.authentication.common.service.impl.match.PasswordAuthType;
+import io.mosip.authentication.common.service.impl.match.PasswordMatchType;
+import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
+import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
+import io.mosip.authentication.core.indauth.dto.AuthRequestDTO;
+import io.mosip.authentication.core.indauth.dto.AuthStatusInfo;
+import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO;
+import io.mosip.authentication.core.spi.indauth.match.MatchInput;
+import io.mosip.authentication.core.spi.indauth.match.MatchOutput;
+import io.mosip.authentication.core.spi.indauth.service.PasswordAuthService;
+import lombok.NoArgsConstructor;
+
+@Service
+@NoArgsConstructor
+public class PasswordAuthServiceImpl implements PasswordAuthService {
+
+ @Autowired
+ private IdInfoHelper idInfoHelper;
+
+ /** The id info helper. */
+ @Autowired
+ private MatchInputBuilder matchInputBuilder;
+
+ /** The ida mapping config. */
+ @Autowired
+ private IDAMappingConfig idaMappingConfig;
+
+ public AuthStatusInfo authenticate(AuthRequestDTO authRequestDTO,String individualId,
+ Map> idInfo,String partnerId)
+ throws IdAuthenticationBusinessException {
+
+ if (idInfo == null || idInfo.isEmpty()) {
+ throw new IdAuthenticationBusinessException(IdAuthenticationErrorConstants.SERVER_ERROR);
+ }
+
+ List listMatchInputs = constructMatchInput(authRequestDTO, idInfo);
+
+ List listMatchOutputs = constructMatchOutput(authRequestDTO, listMatchInputs, idInfo,
+ partnerId);
+ // Using AND condition on the match output for Bio auth.
+ boolean isMatched = !listMatchOutputs.isEmpty() && listMatchOutputs.stream().allMatch(MatchOutput::isMatched);
+ return AuthStatusInfoBuilder.buildStatusInfo(isMatched, listMatchInputs, listMatchOutputs,
+ PasswordAuthType.values(), idaMappingConfig);
+
+ }
+
+ public List constructMatchInput(AuthRequestDTO authRequestDTO,
+ Map> idInfo) {
+ return matchInputBuilder.buildMatchInput(authRequestDTO, PasswordAuthType.values(), PasswordMatchType.values(),
+ idInfo);
+ }
+
+ private List constructMatchOutput(AuthRequestDTO authRequestDTO, List listMatchInputs,
+ Map> idInfo, String partnerId)
+ throws IdAuthenticationBusinessException {
+ return idInfoHelper.matchIdentityData(authRequestDTO, idInfo, listMatchInputs, partnerId);
+ }
+}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java
index 789171e659b..4e3ccd80650 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/IdaIdMapping.java
@@ -177,13 +177,14 @@ public String getSubType() {
RIGHTIRIS, LEFTIRIS, UNKNOWN_IRIS,
FACE,UNKNOWN_FACE), "DummyType"),
-
KEY_BINDED_TOKENS("keyBindedTokens"){
public BiFunction> getMappingFunction() {
return (mappingConfig, matchType) -> { return Collections.emptyList(); };
}
},
+ PASSWORD("password", MappingConfig::getPassword),
+
/** The dynamic demographics ID Mapping. */
DYNAMIC("demographics") {
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/OtpMatchingStrategy.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/OtpMatchingStrategy.java
index 68bfb3401ef..ae35ea3615e 100644
--- a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/OtpMatchingStrategy.java
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/OtpMatchingStrategy.java
@@ -21,11 +21,12 @@
public enum OtpMatchingStrategy implements TextMatchingStrategy {
EXACT(MatchingStrategyType.EXACT, (Object reqInfo, Object entityInfo, Map props) -> {
- if (reqInfo instanceof String && entityInfo instanceof String) {
+ Object idvidObj = props.get(IdAuthCommonConstants.IDVID);
+ if (reqInfo instanceof String && entityInfo instanceof String && idvidObj instanceof String) {
Object object = props.get(ValidateOtpFunction.class.getSimpleName());
if (object instanceof ValidateOtpFunction) {
ValidateOtpFunction func = (ValidateOtpFunction) object;
- boolean otpValid = func.validateOtp((String) reqInfo, (String) entityInfo);
+ boolean otpValid = func.validateOtp((String) reqInfo, (String) entityInfo, (String) idvidObj);
if (!otpValid) {
return 0;
} else {
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordAuthType.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordAuthType.java
new file mode 100644
index 00000000000..5c301684adf
--- /dev/null
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordAuthType.java
@@ -0,0 +1,57 @@
+package io.mosip.authentication.common.service.impl.match;
+
+import io.mosip.authentication.common.service.impl.AuthTypeImpl;
+import io.mosip.authentication.core.indauth.dto.AuthRequestDTO;
+import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO;
+import io.mosip.authentication.core.spi.indauth.match.AuthType;
+import io.mosip.authentication.core.spi.indauth.match.ComparePasswordFunction;
+import io.mosip.authentication.core.spi.indauth.match.IdInfoFetcher;
+import io.mosip.authentication.core.spi.indauth.match.MatchType;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+public enum PasswordAuthType implements AuthType {
+
+ PASSWORD(IdaIdMapping.PASSWORD.getIdname(), AuthType.setOf(PasswordMatchType.PASSWORD), "PASSWORD");
+
+ private AuthTypeImpl authTypeImpl;
+
+ /**
+ * Instantiates a new demo auth type.
+ *
+ * @param type the type
+ * @param associatedMatchTypes the associated match types
+ */
+ private PasswordAuthType(String type, Set associatedMatchTypes, String displayName) {
+ authTypeImpl = new AuthTypeImpl(type, associatedMatchTypes, displayName);
+ }
+
+
+ @Override
+ public boolean isAuthTypeInfoAvailable(AuthRequestDTO authRequestDTO) {
+ if(authRequestDTO instanceof KycAuthRequestDTO) {
+ KycAuthRequestDTO kycAuthRequestDTO = (KycAuthRequestDTO) authRequestDTO;
+ return Objects.nonNull(kycAuthRequestDTO.getRequest().getPassword());
+ }
+ return false;
+ }
+
+ @Override
+ public Map getMatchProperties(AuthRequestDTO authRequestDTO, IdInfoFetcher idInfoFetcher,
+ String language) {
+ Map valueMap = new HashMap<>();
+ if(isAuthTypeInfoAvailable(authRequestDTO)) {
+ ComparePasswordFunction func = idInfoFetcher.getMatchPasswordFunction();
+ valueMap.put(IdaIdMapping.PASSWORD.getIdname(), func);
+ }
+ return valueMap;
+ }
+
+ @Override
+ public AuthType getAuthTypeImpl() {
+ return authTypeImpl;
+ }
+}
diff --git a/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchType.java b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchType.java
new file mode 100644
index 00000000000..6eee7370204
--- /dev/null
+++ b/authentication/authentication-common/src/main/java/io/mosip/authentication/common/service/impl/match/PasswordMatchType.java
@@ -0,0 +1,131 @@
+package io.mosip.authentication.common.service.impl.match;
+
+import static io.mosip.authentication.core.spi.indauth.match.MatchType.setOf;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+
+import io.mosip.authentication.core.indauth.dto.AuthRequestDTO;
+import io.mosip.authentication.core.indauth.dto.IdentityInfoDTO;
+import io.mosip.authentication.core.indauth.dto.KycAuthRequestDTO;
+import io.mosip.authentication.core.indauth.dto.RequestDTO;
+import io.mosip.authentication.core.spi.indauth.match.IdMapping;
+import io.mosip.authentication.core.spi.indauth.match.MatchType;
+import io.mosip.authentication.core.spi.indauth.match.MatchingStrategy;
+import io.mosip.authentication.core.spi.indauth.match.MatchingStrategyType;
+
+public enum PasswordMatchType implements MatchType {
+
+ /** Primary password Match Type. */
+ PASSWORD(IdaIdMapping.PASSWORD, Category.PWD, setOf(PasswordMatchingStrategy.EXACT), authReq -> {
+ KycAuthRequestDTO kycAuthRequestDTO = (KycAuthRequestDTO)authReq;
+ return (Objects.nonNull(kycAuthRequestDTO.getRequest()) &&
+ Objects.nonNull(kycAuthRequestDTO.getRequest().getPassword()))? kycAuthRequestDTO.getRequest().getPassword() : "";
+ });
+
+ /** The allowed matching strategy. */
+ private Set allowedMatchingStrategy;
+
+ /** The request info function. */
+ private Function> requestInfoFunction;
+
+ /** The id mapping. */
+ private IdMapping idMapping;
+
+ private Category category;
+
+ /**
+ * Instantiates a new demo match type.
+ *
+ * @param idMapping the id mapping
+ * @param allowedMatchingStrategy the allowed matching strategy
+ * @param requestInfoFunction the request info function
+ * @param langType the lang type
+ * @param usedBit the used bit
+ * @param matchedBit the matched bit
+ */
+ private PasswordMatchType(IdMapping idMapping, Category category, Set allowedMatchingStrategy,
+ Function requestInfoFunction) {
+ this.idMapping = idMapping;
+ this.category = category;
+ this.requestInfoFunction = (AuthRequestDTO authReq) -> {
+ Map map = new HashMap<>();
+ map.put(idMapping.getIdname(), requestInfoFunction.apply(authReq));
+ return map;
+ };
+ this.allowedMatchingStrategy = Collections.unmodifiableSet(allowedMatchingStrategy);
+ }
+
+ /**
+ * Gets the allowed matching strategy.
+ *
+ * @param matchStrategyType the match strategy type
+ * @return the allowed matching strategy
+ */
+ public Optional getAllowedMatchingStrategy(MatchingStrategyType matchStrategyType) {
+ return allowedMatchingStrategy.stream().filter(ms -> ms.getType().equals(matchStrategyType)).findAny();
+ }
+
+ /**
+ * Gets the entity info.
+ *
+ * @return the entity info
+ */
+ public BiFunction