diff --git a/docker-compose.yml b/docker-compose.yml index 194039b..65c2761 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,7 +10,6 @@ services: - OIDC_WELL_KNOWN_URL= - CLIENT_ID= - CLIENT_SECRET= - - REDIRECT_URI=http://127.0.0.1:3000/callback - COOKIE_SECRET= network_mode: host restart: always diff --git a/index.js b/index.js index d712148..673fb29 100755 --- a/index.js +++ b/index.js @@ -8,11 +8,9 @@ require("dotenv").config(); const PORT = process.env.PORT || 3000; const COMPUTER_NAME = process.env.COMPUTER_NAME || "MyComputer"; -const REDIRECT_URI = - process.env.REDIRECT_URI || "http://127.0.0.1:3000/callback"; const app = express(); - +app.use(express.json()); app.use( session({ secret: process.env.COOKIE_SECRET, @@ -32,7 +30,6 @@ let client; client = new issuer.Client({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, - redirect_uris: [REDIRECT_URI], response_types: ["code"], }); @@ -49,18 +46,39 @@ let client; } }); - app.get("/login", (req, res) => { + const stateMap = {}; + + app.post("/authorize", (req, res) => { + const { redirectUri } = req.body; + if (!redirectUri) { + return res.send( + renderHtml("login-fail.html", { + COMPUTER_NAME, + ERROR: "redirectUri missing or invalid", + }) + ); + } + + const state = Math.random().toString(36).substring(2); + stateMap[state] = { redirectUri }; + const url = client.authorizationUrl({ scope: "openid profile", - redirect_uri: REDIRECT_URI, + redirect_uri: redirectUri, + state, }); - res.redirect(url); + + // 回傳 JSON 給前端,讓前端負責導向 + res.json({ redirect: url }); }); app.get("/callback", async (req, res) => { try { + const state = req.query.state; + const { redirectUri } = stateMap[state]; + const params = client.callbackParams(req); - const tokenSet = await client.callback(REDIRECT_URI, params); + const tokenSet = await client.callback(redirectUri, params, { state }); const userinfo = await client.userinfo(tokenSet.access_token); req.session.user = userinfo; diff --git a/templates/login.html b/templates/login.html index b25e501..a9e4ad3 100644 --- a/templates/login.html +++ b/templates/login.html @@ -1,20 +1,51 @@ + 登入 | 喚醒 {{COMPUTER_NAME}} +

喚醒 {{COMPUTER_NAME}}

- 點此登入 + + +