diff --git a/app.js b/app.js index f3b05c5..1dd2416 100644 --- a/app.js +++ b/app.js @@ -5,8 +5,9 @@ import apiRouter from "./router/api.js" import { Server } from "socket.io"; import { saveToDatabase } from "./utils/storage.js"; import { onlineList, clientMap } from "./data.js"; +import { verifyToken } from "./utils/auth.js"; -const PORT = process.env.PORT || 5691; +const PORT = process.env.PORT || 1111; const app = express(); @@ -52,25 +53,37 @@ io.on("connection", (socket) => { const { opt, args } = JSON.parse(data); logger.trace(opt, args) if (opt == "signin") { - if (!args || !args.username) { - socket.emit("system", JSON.stringify(new Response(false, "username is empty."))) + if (!args || !args.token) { + socket.emit("system", JSON.stringify(new Response(false, "token is empty."))) return; } - const { username } = args - if (username.length > 20) { - socket.emit("system", JSON.stringify(new Response(false, "username is too long."))) - } - if (onlineList.indexOf(username) != -1) { - socket.emit("system", JSON.stringify(new Response(false, "username is already taken."))) + const { token } = args + // const username = token.trim(); + verifyToken(token) + .then(res => { + if (res.data.code != 200) { + socket.emit("system", JSON.stringify(new Response(false, "token is invaild."))) + username = res.data.UserName; + uid = res.data.ID; + return; + } + if (onlineList.indexOf(username) != -1) { + socket.emit("system", JSON.stringify(new Response(false, "token is already taken."))) + return; + } + socket.emit("system", JSON.stringify(new Response(true, "sign in successfully."))) + socket.emit("username", username) + socket.username = username; + onlineList.push(username); + clientMap.set(socket.id, username); + io.emit("notice", JSON.stringify(new Response(true, `${socket.username} join the chat.`))) + logger.debug(`socket(${socket.id}) -- ${username} signed in.`) + }) + .catch(err => { + logger.error(`socket(${socket.id}) -- ${err}.`) + socket.emit("system", JSON.stringify(new Response(false, "token is invaild."))) return; - } - socket.username = username; - onlineList.push(username); - clientMap.set(socket.id, username); - socket.emit("username", socket.username); - socket.emit("system", JSON.stringify(new Response(true, `welcome, ${socket.username}`))) - io.emit("notice", JSON.stringify(new Response(true, `${socket.username} join the chat.`))) - logger.debug(`socket(${socket.id}) -- ${username} signed in.`) + }) } } catch (err) { diff --git a/package.json b/package.json index 5d9d914..e74ddd8 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "author": "star", "license": "MIT", "dependencies": { + "axios": "^1.13.2", "express": "^5.1.0", "log4js": "^6.9.1", "sequelize": "^6.37.7", diff --git a/static/index.html b/static/index.html index 9e86379..62bec6a 100644 --- a/static/index.html +++ b/static/index.html @@ -4,267 +4,63 @@
-