From 2d4fe29bb8bab1f40f596e870fb4467571ab8b1c Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Mon, 8 Sep 2025 14:26:09 +0700 Subject: [PATCH 1/6] forgejo --- .forgejo/workflows/build.yml | 50 +++++++++++++++++++++++++++++++++++ .forgejo/workflows/deploy.yml | 29 ++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 .forgejo/workflows/build.yml create mode 100644 .forgejo/workflows/deploy.yml diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml new file mode 100644 index 0000000..c4746ff --- /dev/null +++ b/.forgejo/workflows/build.yml @@ -0,0 +1,50 @@ +# /.forgejo/workflows/build.yml +name: Build + +on: + push: + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+*" + workflow_dispatch: + +env: + REGISTRY: ${{ vars.CONTAINER_REGISTRY }} + REGISTRY_USERNAME: ${{ vars.CONTAINER_REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.CONTAINER_REGISTRY_PASSWORD }} + CONTAINER_IMAGE_NAME: ${{ vars.CONTAINER_REGISTRY }}/${{ vars.CONTAINER_IMAGE_OWNER }}/${{ vars.CONTAINER_IMAGE_NAME }} + IMAGE_VERSION: build + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + with: + config-inline: | + [registry."${{ env.REGISTRY }}"] + ca=["/etc/ssl/certs/ca-certificates.crt"] + - name: Tag Version + run: | + if [[ "${{ github.event_name }}" == "push" ]]; then + echo "IMAGE_VERSION=${{ github.ref_name }}" | sed 's/v//g' >> $GITHUB_ENV + else + echo "IMAGE_VERSION=${{ env.IMAGE_VERSION }}-${{ github.run_number }}" >> $GITHUB_ENV + fi + - name: Login in to registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ env.REGISTRY_USERNAME }} + password: ${{ env.REGISTRY_PASSWORD }} + - name: Build and push docker image + uses: docker/build-push-action@v3 + with: + platforms: linux/amd64 + context: . + file: ./docker/Dockerfile + tags: ${{ env.CONTAINER_IMAGE_NAME }}:latest,${{ env.CONTAINER_IMAGE_NAME }}:${{ env.IMAGE_VERSION }} + push: true \ No newline at end of file diff --git a/.forgejo/workflows/deploy.yml b/.forgejo/workflows/deploy.yml new file mode 100644 index 0000000..b318ed5 --- /dev/null +++ b/.forgejo/workflows/deploy.yml @@ -0,0 +1,29 @@ +name: Build + +on: + workflow_dispatch: + inputs: + version: + description: "Version to deploy" + type: string + required: false + default: "latest" + +env: + IMAGE_VERSION: build + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Remote Deploy + uses: appleboy/ssh-action@v1.2.1 + with: + host: ${{ vars.SSH_DEPLOY_HOST }} + port: ${{ vars.SSH_DEPLOY_PORT }} + username: ${{ secrets.SSH_DEPLOY_USER }} + password: ${{ secrets.SSH_DEPLOY_PASSWORD }} + script: | + cd ~/repo + ./replace-env.sh API_SSO "${{ inputs.version }}" + ./deploy.sh hrms-api-sso From 4ab953a07ba50bdb30b5e91cfeaa1aa6743b7e6e Mon Sep 17 00:00:00 2001 From: forgejo Date: Wed, 10 Sep 2025 12:07:41 +0700 Subject: [PATCH 2/6] Add .forgejo/workflows/ci-cd.yml --- .forgejo/workflows/ci-cd.yml | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 .forgejo/workflows/ci-cd.yml diff --git a/.forgejo/workflows/ci-cd.yml b/.forgejo/workflows/ci-cd.yml new file mode 100644 index 0000000..ce73c9c --- /dev/null +++ b/.forgejo/workflows/ci-cd.yml @@ -0,0 +1,61 @@ +# /.forgejo/workflows/build.yml +name: Build + +on: + push: + tags: + - "dev[0-9]+.[0-9]+.[0-9]+" + - "dev[0-9]+.[0-9]+.[0-9]+*" + workflow_dispatch: + +env: + REGISTRY: ${{ vars.CONTAINER_REGISTRY }} + REGISTRY_USERNAME: ${{ vars.CONTAINER_REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.CONTAINER_REGISTRY_PASSWORD }} + CONTAINER_IMAGE_NAME: ${{ vars.CONTAINER_REGISTRY }}/${{ vars.CONTAINER_IMAGE_OWNER }}/${{ vars.CONTAINER_IMAGE_NAME }} + IMAGE_VERSION: build + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + with: + config-inline: | + [registry."${{ env.REGISTRY }}"] + ca=["/etc/ssl/certs/ca-certificates.crt"] + - name: Tag Version + run: | + if [[ "${{ github.event_name }}" == "push" ]]; then + echo "IMAGE_VERSION=${{ github.ref_name }}" | sed 's/dev//g' >> $GITHUB_ENV + else + echo "IMAGE_VERSION=${{ env.IMAGE_VERSION }}-${{ github.run_number }}" >> $GITHUB_ENV + fi + - name: Login in to registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ env.REGISTRY_USERNAME }} + password: ${{ env.REGISTRY_PASSWORD }} + - name: Build and push docker image + uses: docker/build-push-action@v3 + with: + platforms: linux/amd64 + context: . + file: ./docker/Dockerfile + tags: ${{ env.CONTAINER_IMAGE_NAME }}:latest,${{ env.CONTAINER_IMAGE_NAME }}:${{ env.IMAGE_VERSION }} + push: true + - name: Remote Deploy + uses: appleboy/ssh-action@v1.2.1 + with: + host: ${{ vars.SSH_DEPLOY_HOST }} + port: ${{ vars.SSH_DEPLOY_PORT }} + username: ${{ secrets.SSH_DEPLOY_USER }} + password: ${{ secrets.SSH_DEPLOY_PASSWORD }} + script: | + cd ~/repo + ./replace-env.sh API_SSO "${{ env.IMAGE_VERSION }}" + ./deploy.sh hrms-api-sso From f3d6e6eb66ae3340839c1f637a02027d3ad74e77 Mon Sep 17 00:00:00 2001 From: warunee Date: Fri, 12 Sep 2025 10:40:48 +0700 Subject: [PATCH 3/6] Update sso.js --- sso.js | 180 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 96 insertions(+), 84 deletions(-) diff --git a/sso.js b/sso.js index eca0d34..30c4fb9 100644 --- a/sso.js +++ b/sso.js @@ -1,6 +1,3 @@ -//simulate BMA SSO behavior Authenticator and reverse proxy -//cookie with token is the final product of SSO - require("dotenv").config(); const cookieParser = require('cookie-parser'); const querystring = require("querystring"); @@ -11,6 +8,8 @@ const cors = require('cors'); const jwt = require("jsonwebtoken"); const fs = require("fs"); const axios = require("axios"); +const CryptoJS = require("crypto-js"); +const secretKey = "uuidSecretKey2025"; // ใช้เป็นคีย์สำหรับเข้ารหัส const cookieName = process.env.SSO_COOKIE_NAME || "ssotoken"; const privateKey = fs.readFileSync(`./BMA`, "utf8"); @@ -26,85 +25,107 @@ const urlKeycloakToken = `${process.env.KC_URL}/realms/${process.env.KC_REALMS}/ const app = express(); -// Allow a specific origin and enable credentials -const corsOptions = { - origin: 'http://localhost:3002', // Replace with your Vue app's URL - methods: 'GET,POST,PUT,DELETE', - credentials: true, // Enable cookies or Authorization headers -}; +// ตั้งค่าการป้องกัน Origin +const allowedOrigins = ['http://localhost:3002', 'https://hrmsbkk.case-collection.com']; // อนุญาตเฉพาะ domain ที่กำหนด //http://localhost:3002 -app.use(cors(corsOptions)); +app.use(cors({ + origin: function (origin, callback) { + if (allowedOrigins.includes(origin)) { + callback(null, true); // อนุญาต + } else { + callback(new Error('Origin not allowed by CORS')); // ปฏิเสธ + } + }, + methods: ['GET', 'POST'], // จำกัดเฉพาะ method ที่อนุญาต + credentials: true, +})); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cookieParser()); + +app.get("/api/v1/sso", async (req, res) => { + res.status(200).send("HRMS API SSO"); +}); + app.post("/api/v1/sso/signin", async (req, res) => { + const origin = req.headers.origin; + if (allowedOrigins.includes(origin)) { + try { + const login_user = req.body; - try { - const login_user = req.body; + const formdata = new URLSearchParams(); + formdata.append("grant_type", "password"); + formdata.append("client_id", process.env.VITE_CLIENTID_KEYCLOAK); + formdata.append("username", login_user.username); + formdata.append("password", login_user.password); - const formdata = new URLSearchParams(); - formdata.append("grant_type", "password"); - formdata.append("client_id", process.env.VITE_CLIENTID_KEYCLOAK); - formdata.append("username", login_user.username); - formdata.append("password", login_user.password); + await axios.post(urlKeycloakToken, formdata, { + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + }).then(async () => { + const payload = { username: login_user.username }; + let token = jwt.sign(payload, privateKey, signOptions); - await axios.post(urlKeycloakToken, formdata, { - headers: { - "Content-Type": "application/x-www-form-urlencoded", - }, - }).then(() => { - const payload = { username: login_user.username }; - let token = jwt.sign(payload, privateKey, signOptions); + res.cookie(cookieName, token, { + maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond + path: "/", + httpOnly: true, + }); - res.cookie(cookieName, token, { - maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond - path: "/", - httpOnly: true, + const uid = await CryptoJS.AES.encrypt(login_user.username, secretKey).toString(); + res.status(200).send({ uid }); + + }).catch((err) => { + if (err.status) { + res.status(401).send("Incorrect user or password"); + } else + res.status(err.status).send(error); }); - - res.sendStatus(200); - }).catch((err) => { - if (err.status) { - res.status(401).send("Incorrect user or password"); - } else - res.status(err.status).send(error); - }); - } catch (error) { - res.status(500).send(error); + } catch (error) { + res.status(500).send(error); + } + } else { + res.status(403).json({ error: 'Forbidden: Origin not allowed' }); } }); app.post("/api/v1/sso/kcauth", async (req, res) => { - try { - // kcauth - const useBMA = Boolean(process.env.USE_BMA) || false; - const publicKeyLanding = fs.readFileSync(`./BMA.pub.pem`, "utf8"); - const clientSecret = process.env.KC_CLIENT_SECRET; - const clientId = process.env.KC_CLIENT_ID; + const origin = req.headers.origin; + if (allowedOrigins.includes(origin)) { + try { + // kcauth + // const useBMA = Boolean(process.env.USE_BMA) || false; + // const publicKeyLanding = fs.readFileSync(`./BMA.pub.pem`, "utf8"); + const clientSecret = process.env.KC_CLIENT_SECRET; + const clientId = process.env.KC_CLIENT_ID; - const cookies = req.cookies; - const tokenSSO = cookies[cookieName]; + // const cookies = req.cookies; + // const tokenSSO = cookies[cookieName]; + //if (tokenSSO) { + // let decodedToken = ""; + // if (useBMA) { + // decodedToken = jwt.decode(tokenSSO); + // } else { + // decodedToken = jwt.verify(tokenSSO, publicKeyLanding); + // } + // let d = JSON.parse(JSON.stringify(decodedToken)); + // console.log("==== username from cookies ====", d); + // username = d.username; + // } - if (!tokenSSO) { - res.status(401).send("Unauthorized"); - return; - } - - const oldssotoken = cookies['oldssotoken']; - - if (tokenSSO !== oldssotoken) { - - let decodedToken = ""; - if (useBMA) { - decodedToken = jwt.decode(tokenSSO); - } else { - decodedToken = jwt.verify(tokenSSO, publicKeyLanding); + // send uid from client + const uid = req.body.uid; + if (!uid) { + res.status(401).send("Unauthorized"); + return; } - let d = JSON.parse(JSON.stringify(decodedToken)); - // console.log("==== username from cookies ====", d); - const username = d.username; + let username = ""; + const bytes = CryptoJS.AES.decrypt(uid, secretKey); + const decrypted = bytes.toString(CryptoJS.enc.Utf8); + username = decrypted; // create body for admin token let body = { @@ -121,6 +142,7 @@ app.post("/api/v1/sso/kcauth", async (req, res) => { "Content-Type": "application/x-www-form-urlencoded", }, }); + // console.log("==== admin token ===="); const adminToken = response.data.access_token; // console.log(adminToken); @@ -137,10 +159,8 @@ app.post("/api/v1/sso/kcauth", async (req, res) => { }; const postData2 = querystring.stringify(body2); - // console.log("==== postData2 ===="); - // console.log(body2); - // get admin token + // get token for user const tokenResponse = await axios.post(urlKeycloakToken, postData2, { headers: { "Content-Type": "application/x-www-form-urlencoded", @@ -150,29 +170,21 @@ app.post("/api/v1/sso/kcauth", async (req, res) => { // console.log("==== user token ===="); // console.log(tokenResponse.data); // await postLog('เข้าสู่ระบบ', tokenResponse.data.access_token); - res.cookie('oldssotoken', tokenSSO, { - maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond - path: "/", - httpOnly: true, - }); + // res.cookie('oldssotoken', tokenSSO, { + // maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond + // path: "/", + // httpOnly: true, + // }); res.status(200).send(tokenResponse.data); - } else { - res.status(200).send({ isLogin: true }); + + } catch (error) { + res.status(500).send(error); } - - } catch (error) { - // console.log("error===>", error); - - res.status(500).send(error); + } else { + res.status(403).json({ error: 'Forbidden: Origin not allowed' }); } }) -// app.use(express.static(path.join(__dirname, "public-sso"))); - -// app.get("/", (_req, res) => { -// res.sendFile(`${process.cwd()}/sso.js`); -// }); - console.log("Start BMA SSO Simulator at port " + port); app.listen(port); \ No newline at end of file From 658fcb176f8a5f2ed051f035da8baa20a3ca81a8 Mon Sep 17 00:00:00 2001 From: warunee Date: Fri, 12 Sep 2025 10:47:02 +0700 Subject: [PATCH 4/6] revert 4ab953a07ba50bdb30b5e91cfeaa1aa6743b7e6e revert Add .forgejo/workflows/ci-cd.yml --- .forgejo/workflows/ci-cd.yml | 61 ------------------------------------ 1 file changed, 61 deletions(-) delete mode 100644 .forgejo/workflows/ci-cd.yml diff --git a/.forgejo/workflows/ci-cd.yml b/.forgejo/workflows/ci-cd.yml deleted file mode 100644 index ce73c9c..0000000 --- a/.forgejo/workflows/ci-cd.yml +++ /dev/null @@ -1,61 +0,0 @@ -# /.forgejo/workflows/build.yml -name: Build - -on: - push: - tags: - - "dev[0-9]+.[0-9]+.[0-9]+" - - "dev[0-9]+.[0-9]+.[0-9]+*" - workflow_dispatch: - -env: - REGISTRY: ${{ vars.CONTAINER_REGISTRY }} - REGISTRY_USERNAME: ${{ vars.CONTAINER_REGISTRY_USERNAME }} - REGISTRY_PASSWORD: ${{ secrets.CONTAINER_REGISTRY_PASSWORD }} - CONTAINER_IMAGE_NAME: ${{ vars.CONTAINER_REGISTRY }}/${{ vars.CONTAINER_IMAGE_OWNER }}/${{ vars.CONTAINER_IMAGE_NAME }} - IMAGE_VERSION: build - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - with: - config-inline: | - [registry."${{ env.REGISTRY }}"] - ca=["/etc/ssl/certs/ca-certificates.crt"] - - name: Tag Version - run: | - if [[ "${{ github.event_name }}" == "push" ]]; then - echo "IMAGE_VERSION=${{ github.ref_name }}" | sed 's/dev//g' >> $GITHUB_ENV - else - echo "IMAGE_VERSION=${{ env.IMAGE_VERSION }}-${{ github.run_number }}" >> $GITHUB_ENV - fi - - name: Login in to registry - uses: docker/login-action@v2 - with: - registry: ${{ env.REGISTRY }} - username: ${{ env.REGISTRY_USERNAME }} - password: ${{ env.REGISTRY_PASSWORD }} - - name: Build and push docker image - uses: docker/build-push-action@v3 - with: - platforms: linux/amd64 - context: . - file: ./docker/Dockerfile - tags: ${{ env.CONTAINER_IMAGE_NAME }}:latest,${{ env.CONTAINER_IMAGE_NAME }}:${{ env.IMAGE_VERSION }} - push: true - - name: Remote Deploy - uses: appleboy/ssh-action@v1.2.1 - with: - host: ${{ vars.SSH_DEPLOY_HOST }} - port: ${{ vars.SSH_DEPLOY_PORT }} - username: ${{ secrets.SSH_DEPLOY_USER }} - password: ${{ secrets.SSH_DEPLOY_PASSWORD }} - script: | - cd ~/repo - ./replace-env.sh API_SSO "${{ env.IMAGE_VERSION }}" - ./deploy.sh hrms-api-sso From eea002177ba38ec8df77fe3b6f98561de6d712d9 Mon Sep 17 00:00:00 2001 From: warunee Date: Fri, 12 Sep 2025 10:49:19 +0700 Subject: [PATCH 5/6] Add .forgejo/workflows/ci-cd.yml ci cd --- .forgejo/workflows/ci-cd.yml | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 .forgejo/workflows/ci-cd.yml diff --git a/.forgejo/workflows/ci-cd.yml b/.forgejo/workflows/ci-cd.yml new file mode 100644 index 0000000..ce73c9c --- /dev/null +++ b/.forgejo/workflows/ci-cd.yml @@ -0,0 +1,61 @@ +# /.forgejo/workflows/build.yml +name: Build + +on: + push: + tags: + - "dev[0-9]+.[0-9]+.[0-9]+" + - "dev[0-9]+.[0-9]+.[0-9]+*" + workflow_dispatch: + +env: + REGISTRY: ${{ vars.CONTAINER_REGISTRY }} + REGISTRY_USERNAME: ${{ vars.CONTAINER_REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.CONTAINER_REGISTRY_PASSWORD }} + CONTAINER_IMAGE_NAME: ${{ vars.CONTAINER_REGISTRY }}/${{ vars.CONTAINER_IMAGE_OWNER }}/${{ vars.CONTAINER_IMAGE_NAME }} + IMAGE_VERSION: build + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + with: + config-inline: | + [registry."${{ env.REGISTRY }}"] + ca=["/etc/ssl/certs/ca-certificates.crt"] + - name: Tag Version + run: | + if [[ "${{ github.event_name }}" == "push" ]]; then + echo "IMAGE_VERSION=${{ github.ref_name }}" | sed 's/dev//g' >> $GITHUB_ENV + else + echo "IMAGE_VERSION=${{ env.IMAGE_VERSION }}-${{ github.run_number }}" >> $GITHUB_ENV + fi + - name: Login in to registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ env.REGISTRY_USERNAME }} + password: ${{ env.REGISTRY_PASSWORD }} + - name: Build and push docker image + uses: docker/build-push-action@v3 + with: + platforms: linux/amd64 + context: . + file: ./docker/Dockerfile + tags: ${{ env.CONTAINER_IMAGE_NAME }}:latest,${{ env.CONTAINER_IMAGE_NAME }}:${{ env.IMAGE_VERSION }} + push: true + - name: Remote Deploy + uses: appleboy/ssh-action@v1.2.1 + with: + host: ${{ vars.SSH_DEPLOY_HOST }} + port: ${{ vars.SSH_DEPLOY_PORT }} + username: ${{ secrets.SSH_DEPLOY_USER }} + password: ${{ secrets.SSH_DEPLOY_PASSWORD }} + script: | + cd ~/repo + ./replace-env.sh API_SSO "${{ env.IMAGE_VERSION }}" + ./deploy.sh hrms-api-sso From 6f3d98ccc6a088981584231fb848e09047660d97 Mon Sep 17 00:00:00 2001 From: warunee Date: Fri, 12 Sep 2025 10:49:38 +0700 Subject: [PATCH 6/6] revert f3d6e6eb66ae3340839c1f637a02027d3ad74e77 revert Update sso.js --- sso.js | 180 +++++++++++++++++++++++++++------------------------------ 1 file changed, 84 insertions(+), 96 deletions(-) diff --git a/sso.js b/sso.js index 30c4fb9..eca0d34 100644 --- a/sso.js +++ b/sso.js @@ -1,3 +1,6 @@ +//simulate BMA SSO behavior Authenticator and reverse proxy +//cookie with token is the final product of SSO + require("dotenv").config(); const cookieParser = require('cookie-parser'); const querystring = require("querystring"); @@ -8,8 +11,6 @@ const cors = require('cors'); const jwt = require("jsonwebtoken"); const fs = require("fs"); const axios = require("axios"); -const CryptoJS = require("crypto-js"); -const secretKey = "uuidSecretKey2025"; // ใช้เป็นคีย์สำหรับเข้ารหัส const cookieName = process.env.SSO_COOKIE_NAME || "ssotoken"; const privateKey = fs.readFileSync(`./BMA`, "utf8"); @@ -25,107 +26,85 @@ const urlKeycloakToken = `${process.env.KC_URL}/realms/${process.env.KC_REALMS}/ const app = express(); -// ตั้งค่าการป้องกัน Origin -const allowedOrigins = ['http://localhost:3002', 'https://hrmsbkk.case-collection.com']; // อนุญาตเฉพาะ domain ที่กำหนด //http://localhost:3002 +// Allow a specific origin and enable credentials +const corsOptions = { + origin: 'http://localhost:3002', // Replace with your Vue app's URL + methods: 'GET,POST,PUT,DELETE', + credentials: true, // Enable cookies or Authorization headers +}; -app.use(cors({ - origin: function (origin, callback) { - if (allowedOrigins.includes(origin)) { - callback(null, true); // อนุญาต - } else { - callback(new Error('Origin not allowed by CORS')); // ปฏิเสธ - } - }, - methods: ['GET', 'POST'], // จำกัดเฉพาะ method ที่อนุญาต - credentials: true, -})); +app.use(cors(corsOptions)); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cookieParser()); - -app.get("/api/v1/sso", async (req, res) => { - res.status(200).send("HRMS API SSO"); -}); - app.post("/api/v1/sso/signin", async (req, res) => { - const origin = req.headers.origin; - if (allowedOrigins.includes(origin)) { - try { - const login_user = req.body; - const formdata = new URLSearchParams(); - formdata.append("grant_type", "password"); - formdata.append("client_id", process.env.VITE_CLIENTID_KEYCLOAK); - formdata.append("username", login_user.username); - formdata.append("password", login_user.password); + try { + const login_user = req.body; - await axios.post(urlKeycloakToken, formdata, { - headers: { - "Content-Type": "application/x-www-form-urlencoded", - }, - }).then(async () => { - const payload = { username: login_user.username }; - let token = jwt.sign(payload, privateKey, signOptions); + const formdata = new URLSearchParams(); + formdata.append("grant_type", "password"); + formdata.append("client_id", process.env.VITE_CLIENTID_KEYCLOAK); + formdata.append("username", login_user.username); + formdata.append("password", login_user.password); - res.cookie(cookieName, token, { - maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond - path: "/", - httpOnly: true, - }); + await axios.post(urlKeycloakToken, formdata, { + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + }).then(() => { + const payload = { username: login_user.username }; + let token = jwt.sign(payload, privateKey, signOptions); - const uid = await CryptoJS.AES.encrypt(login_user.username, secretKey).toString(); - res.status(200).send({ uid }); - - }).catch((err) => { - if (err.status) { - res.status(401).send("Incorrect user or password"); - } else - res.status(err.status).send(error); + res.cookie(cookieName, token, { + maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond + path: "/", + httpOnly: true, }); - } catch (error) { - res.status(500).send(error); - } - } else { - res.status(403).json({ error: 'Forbidden: Origin not allowed' }); + + res.sendStatus(200); + }).catch((err) => { + if (err.status) { + res.status(401).send("Incorrect user or password"); + } else + res.status(err.status).send(error); + }); + } catch (error) { + res.status(500).send(error); } }); app.post("/api/v1/sso/kcauth", async (req, res) => { - const origin = req.headers.origin; - if (allowedOrigins.includes(origin)) { - try { - // kcauth - // const useBMA = Boolean(process.env.USE_BMA) || false; - // const publicKeyLanding = fs.readFileSync(`./BMA.pub.pem`, "utf8"); - const clientSecret = process.env.KC_CLIENT_SECRET; - const clientId = process.env.KC_CLIENT_ID; + try { + // kcauth + const useBMA = Boolean(process.env.USE_BMA) || false; + const publicKeyLanding = fs.readFileSync(`./BMA.pub.pem`, "utf8"); + const clientSecret = process.env.KC_CLIENT_SECRET; + const clientId = process.env.KC_CLIENT_ID; - // const cookies = req.cookies; - // const tokenSSO = cookies[cookieName]; - //if (tokenSSO) { - // let decodedToken = ""; - // if (useBMA) { - // decodedToken = jwt.decode(tokenSSO); - // } else { - // decodedToken = jwt.verify(tokenSSO, publicKeyLanding); - // } - // let d = JSON.parse(JSON.stringify(decodedToken)); - // console.log("==== username from cookies ====", d); - // username = d.username; - // } + const cookies = req.cookies; + const tokenSSO = cookies[cookieName]; - // send uid from client - const uid = req.body.uid; - if (!uid) { - res.status(401).send("Unauthorized"); - return; + if (!tokenSSO) { + res.status(401).send("Unauthorized"); + return; + } + + const oldssotoken = cookies['oldssotoken']; + + if (tokenSSO !== oldssotoken) { + + let decodedToken = ""; + if (useBMA) { + decodedToken = jwt.decode(tokenSSO); + } else { + decodedToken = jwt.verify(tokenSSO, publicKeyLanding); } - let username = ""; - const bytes = CryptoJS.AES.decrypt(uid, secretKey); - const decrypted = bytes.toString(CryptoJS.enc.Utf8); - username = decrypted; + let d = JSON.parse(JSON.stringify(decodedToken)); + // console.log("==== username from cookies ====", d); + const username = d.username; // create body for admin token let body = { @@ -142,7 +121,6 @@ app.post("/api/v1/sso/kcauth", async (req, res) => { "Content-Type": "application/x-www-form-urlencoded", }, }); - // console.log("==== admin token ===="); const adminToken = response.data.access_token; // console.log(adminToken); @@ -159,8 +137,10 @@ app.post("/api/v1/sso/kcauth", async (req, res) => { }; const postData2 = querystring.stringify(body2); + // console.log("==== postData2 ===="); + // console.log(body2); - // get token for user + // get admin token const tokenResponse = await axios.post(urlKeycloakToken, postData2, { headers: { "Content-Type": "application/x-www-form-urlencoded", @@ -170,21 +150,29 @@ app.post("/api/v1/sso/kcauth", async (req, res) => { // console.log("==== user token ===="); // console.log(tokenResponse.data); // await postLog('เข้าสู่ระบบ', tokenResponse.data.access_token); - // res.cookie('oldssotoken', tokenSSO, { - // maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond - // path: "/", - // httpOnly: true, - // }); + res.cookie('oldssotoken', tokenSSO, { + maxAge: 1000 * 60 * 60 * 24, // กำหนด timeout หน่วยเป็น millisecond + path: "/", + httpOnly: true, + }); res.status(200).send(tokenResponse.data); - - } catch (error) { - res.status(500).send(error); + } else { + res.status(200).send({ isLogin: true }); } - } else { - res.status(403).json({ error: 'Forbidden: Origin not allowed' }); + + } catch (error) { + // console.log("error===>", error); + + res.status(500).send(error); } }) +// app.use(express.static(path.join(__dirname, "public-sso"))); + +// app.get("/", (_req, res) => { +// res.sendFile(`${process.cwd()}/sso.js`); +// }); + console.log("Start BMA SSO Simulator at port " + port); app.listen(port); \ No newline at end of file