Compare commits

..
49 Commits
Author SHA1 Message Date
Akizon f1cfbd9391 Merge pull request #41 from komari-monitor/dev
feat: 添加日志功能
2025-06-06 18:02:32 +08:00
Akizon77 ae6f9a7840 refactor: 移除冗余的版本文件 2025-06-06 18:00:56 +08:00
Akizon77 a75ac3e97d feat: session管理更加细致,识别UA、IP 2025-06-06 17:34:53 +08:00
Akizon77 00fa79e31c fix: 登陆后的重定向从/admin更改为/manage 2025-06-06 17:14:54 +08:00
Akizon77 392b05be94 feat: 更新日志获取接口,返回日志总数 2025-06-06 16:54:16 +08:00
Akizon77 26e120cc89 fix: 查询日志传入小于等于0的页数报500 2025-06-06 16:29:40 +08:00
Akizon77 413dd780f2 feat: 优化设置更新日志,忽略特定字段 2025-06-06 16:21:30 +08:00
Akizon77 3d26743492 feat: 添加服务器启动和关闭的信号处理,记录日志信息 2025-06-06 16:17:12 +08:00
Akizon77 0a6927805e feat: 添加分页功能,支持限制日志数量和选择页码 2025-06-06 16:06:29 +08:00
Akizon77 d16889c103 feat: 更新日志记录,添加客户端UUID信息 2025-06-06 16:01:19 +08:00
Akizon77 7894990d91 feat: 添加终端连接建立和断开的时间记录 2025-06-06 15:55:58 +08:00
Akizon77 fe3afceca9 feat: 终端添加日志 2025-06-06 15:54:42 +08:00
Akizon77 014ee67d69 feat:记录用户通过密码和OAuth登录的操作 2025-06-06 15:29:32 +08:00
Akizon77 ec4dee765a feat: 支持获取和删除旧日志 2025-06-06 15:05:39 +08:00
Akizon77 00d8936455 feat: 添加日志记录功能,记录用户操作及相关信息 2025-06-06 15:00:35 +08:00
Akizon77 4b97ae92da feat: 添加Telegram消息发送功能及GeoIP查询接口 2025-06-06 14:41:44 +08:00
Akizon77 a33885255c fix: 统一未授权响应处理,使用统一的错误响应函数 2025-06-05 19:01:15 +08:00
Akizon77 fd8a4c4895 feat: 统一API响应处理,简化错误和成功响应逻辑 2025-06-05 18:59:17 +08:00
Akizon77 039fd6b8d9 feat: 统一(大部分)API响应格式 2025-06-05 18:48:50 +08:00
Akizon77 09c346180e feat: 允许禁止密码登录
refactor: 大致上应该错误都返回message
2025-06-05 17:54:40 +08:00
Akizon77 179606ea6e fix: 自定义head不生效的bug 2025-06-04 23:00:28 +08:00
Akizon 2118648a58 Merge pull request #40 from komari-monitor/dev
feat: 添加上传和删除 favicon 的功能
2025-06-04 22:21:20 +08:00
Akizon77 db26327140 feat: 添加上传和删除 favicon 的功能 2025-06-04 22:12:39 +08:00
Akizon 5132b60f18 Merge pull request #39 from komari-monitor/dev
feat: 支持更新用户信息 & 手动更新geoip数据库
2025-06-04 20:48:44 +08:00
Akizon77 43cfbca62f feat: 更新用户信息 & 手动更新geoip数据库 2025-06-04 20:44:16 +08:00
Akizon77 1cc6f22a5a feat: 增加动态 CORS 支持和配置事件发布机制 2025-06-04 20:08:56 +08:00
Akizon dfc242dc0e Merge pull request #38 from komari-monitor/dev
fix: 修复 CORS
2025-06-04 19:21:08 +08:00
Akizon77 f1d17d9bcd feat: 清理过期任务结果 2025-06-04 19:17:41 +08:00
Akizon77 403879e705 fix: 修复配置中的 CORS 列名错误 2025-06-04 19:15:21 +08:00
Akizon77 cbc91cfb0c fix: 修复 CORS 2025-06-04 18:19:22 +08:00
Akizon b709ac9e98 Merge pull request #37 from komari-monitor/dev
feat: 添加批量执行任务
2025-06-04 17:46:27 +08:00
Akizon77 6d29b165ca feat: 增加任务结果的详细信息 2025-06-04 17:46:06 +08:00
Akizon77 44b1106dec feat: task 存储数组 2025-06-04 17:31:39 +08:00
Akizon77 2bb96b7272 Merge branch 'dev' of https://github.com/komari-monitor/komari into dev 2025-06-04 16:19:27 +08:00
Akizon77 2cd1159f94 feat: 添加批量执行任务 2025-06-04 16:19:22 +08:00
Akizon 5278803fb1 Merge pull request #36 from komari-monitor/dev
移除mmdb下载地址代理,增加版本号信息
2025-06-04 13:26:51 +08:00
Akizon 662a3033f7 Merge branch 'main' into dev 2025-06-04 13:26:43 +08:00
Akizon77 4c55e52374 feat: 添加版本信息API接口,支持获取当前版本和哈希 2025-06-03 23:25:50 +08:00
Akizon77 864b91fad1 ci/cd: 版本信息构建 2025-06-03 23:21:57 +08:00
Akizon77 8ed2e5a774 cd: 使用完整前端 2025-06-03 23:07:26 +08:00
Akizon77 907419ec73 cd: 工作流处理文件已存在 2025-05-30 16:53:12 +08:00
Akizon77 dc05937331 fix: 移除geoip下载地址代理 2025-05-30 16:44:21 +08:00
Akizon77 3169ec687b feat: 添加开发环境工作流,支持多平台构建和生产部署 2025-05-30 15:47:17 +08:00
Akizon 9160c1eef7 Merge pull request #35 from komari-monitor/dev
refactor: Client优化模型
2025-05-29 18:08:36 +08:00
Akizon77 7b95e270b5 fix: 修复EditClient函数中UUID的处理逻辑 2025-05-29 18:07:03 +08:00
Akizon77 95cf1d78d0 feat: 添加SSO相关信息返回 2025-05-29 17:51:04 +08:00
Akizon77 fefdcee60d refactor: 更新Client相关逻辑,迁移旧版ClientInfo数据并优化模型 2025-05-29 17:29:02 +08:00
Akizon 1f7bdf60c2 Merge pull request #34 from komari-monitor/dev
fix: 数据库charset=utf8mb4
2025-05-27 23:00:16 +08:00
Akizon77 554caf7a37 fix: 数据库charset=utf8mb4 2025-05-27 22:12:52 +08:00
48 changed files with 1534 additions and 314 deletions

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
name: Development Environment
on:
push:
branches:
- dev
workflow_dispatch:
jobs:
build-binaries:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
#- name: Create dummy index.html
# run: |
# mkdir -p public/dist
# echo "<html><body><h1>This is komari development server.</h1></body></html>" > public/dist/index.html
- name: Clone and build frontend
run: |
git clone https://github.com/komari-monitor/komari-web web
cd web
npm install
npm run build
cd ..
mkdir -p public/dist
cp -r web/dist/* public/dist/
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Build application
env:
GOOS: linux
GOARCH: amd64
run: |
VERSION_SHA="${{ github.sha }}"
go build -ldflags "-X github.com/komari-monitor/komari/utils.CurrentVersion=dev -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_SHA}" -o komari .
- name: Upload binary as artifact
uses: actions/upload-artifact@v4
with:
name: komari
path: komari
deploy-to-production:
needs: build-binaries
runs-on: ubuntu-latest
env:
PRODUCTION_SERVER: ${{ vars.PRODUCTION_SERVER }}
if: github.ref == 'refs/heads/dev'
steps:
- name: Download binary
uses: actions/download-artifact@v4
with:
name: komari
- name: Setup SSH Key
uses: webfactory/ssh-agent@v0.8.0
with:
ssh-private-key: ${{ secrets.PRODUCTION_SSH_KEY }}
- name: Add host to known hosts
run: |
mkdir -p ~/.ssh
ssh-keyscan -H ${{ env.PRODUCTION_SERVER }} >> ~/.ssh/known_hosts
- name: Deploy to production
run: |
chmod +x komari
ssh root@${{ env.PRODUCTION_SERVER }} 'mkdir -p /opt/komari/'
ssh root@${{ env.PRODUCTION_SERVER }} 'systemctl stop komari.service || true'
ssh root@${{ env.PRODUCTION_SERVER }} 'rm -f /opt/komari/komari.old'
ssh root@${{ env.PRODUCTION_SERVER }} 'mv /opt/komari/komari /opt/komari/komari.old || true'
scp komari root@${{ env.PRODUCTION_SERVER }}:/opt/komari/komari
ssh root@${{ env.PRODUCTION_SERVER }} 'systemctl start komari.service'
+4 -1
View File
@@ -3,7 +3,7 @@ name: Docker Build and Publish
on:
push:
branches:
- dev
- main
workflow_dispatch:
env:
@@ -44,3 +44,6 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ github.ref_name }}
VERSION_HASH=${{ github.sha }}
+7 -2
View File
@@ -55,7 +55,9 @@ jobs:
if [ "${{ matrix.goos }}" = "windows" ]; then
BINARY_NAME=${BINARY_NAME}.exe
fi
go build -trimpath -ldflags="-s -w" -o $BINARY_NAME
VERSION="${{ github.event.release.tag_name }}"
VERSION_HASH="${{ github.sha }}"
go build -trimpath -ldflags="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o $BINARY_NAME
- name: Upload binary to release
env:
@@ -97,4 +99,7 @@ jobs:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ github.event.release.tag_name }}
VERSION_HASH=${{ github.sha }}
+3 -1
View File
@@ -16,8 +16,10 @@ COPY . .
COPY --from=frontend /web/dist ./public/dist
ENV CGO_ENABLED=1
ARG VERSION=unknown
ARG VERSION_HASH=unknown
# RUN CC=musl-gcc go build -trimpath -ldflags="-s -w -linkmode external -extldflags -static" -o komari .
RUN go build -trimpath -ldflags="-s -w -linkmode external -extldflags -static" -o komari .
RUN go build -trimpath -ldflags="-s -w -linkmode external -extldflags -static -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o komari .
# FROM scratch
FROM alpine:3.21
+7 -3
View File
@@ -13,18 +13,22 @@ func AdminAuthMiddleware() gin.HandlerFunc {
session, err := c.Cookie("session_token")
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "error": "Unauthorized"})
RespondError(c, http.StatusUnauthorized, "Unauthorized.")
c.Abort()
return
}
// Komari is a single user system
_, err = accounts.GetSession(session)
uuid, err := accounts.GetSession(session)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "error": "Unauthorized."})
RespondError(c, http.StatusUnauthorized, "Unauthorized.")
c.Abort()
return
}
accounts.UpdateLatest(session, c.Request.UserAgent(), c.ClientIP())
// 将 session 和 用户 UUID 传递到后续处理器
c.Set("session", session)
c.Set("uuid", uuid)
c.Next()
}
+38 -3
View File
@@ -1,9 +1,11 @@
package api
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/common"
@@ -17,9 +19,10 @@ var (
)
type TerminalSession struct {
UUID string
Browser *websocket.Conn
Agent *websocket.Conn
UUID string
UserUUID string
Browser *websocket.Conn
Agent *websocket.Conn
}
var TerminalSessionsMutex = &sync.Mutex{}
@@ -51,3 +54,35 @@ func SaveClientReportToDB() error {
return nil
}
type Response struct {
Status string `json:"status"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// Respond sends a standardized JSON response.
func Respond(c *gin.Context, httpStatus int, status string, message string, data interface{}) {
c.JSON(httpStatus, Response{Status: status, Message: message, Data: data})
}
// RespondSuccess sends a success response with data.
func RespondSuccess(c *gin.Context, data interface{}) {
Respond(c, http.StatusOK, "success", "", data)
}
// RespondSuccessMessage sends a success response with message and data.
func RespondSuccessMessage(c *gin.Context, message string, data interface{}) {
Respond(c, http.StatusOK, "success", message, data)
}
// RespondError sends an error response with message.
func RespondError(c *gin.Context, httpStatus int, message string) {
Respond(c, httpStatus, "error", message, nil)
}
func GetVersion(c *gin.Context) {
RespondSuccess(c, gin.H{
"version": utils.CurrentVersion,
"hash": utils.VersionHash,
})
}
+35 -46
View File
@@ -2,70 +2,55 @@ package admin
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/database/records"
)
func AddClient(c *gin.Context) {
var req struct {
name string
Name string `json:"name"`
}
if err := c.ShouldBindJSON(&req); err != nil || req.name == "" {
if err := c.ShouldBindJSON(&req); err != nil || req.Name == "" {
uuid, token, err := clients.CreateClient()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "uuid": uuid, "token": token})
return
}
uuid, token, err := clients.CreateClientWithName(req.name)
uuid, token, err := clients.CreateClientWithName(req.Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "uuid": uuid, "token": token})
user_uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), user_uuid.(string), "create client:"+uuid, "info")
c.JSON(http.StatusOK, gin.H{"status": "success", "uuid": uuid, "token": token, "message": ""})
}
func EditClient(c *gin.Context) {
var req = make(map[string]interface{})
uuid := c.Param("uuid")
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": err.Error()})
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": err.Error()})
return
}
db := dbcore.GetDBInstance()
var err error
if req["token"] != "" {
err = db.Model(&models.Client{}).Where("uuid = ?", uuid).
Updates(map[string]interface{}{"token": req["token"], "updated_at": time.Now()}).Error
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
if uuid == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Invalid or missing UUID"})
return
}
allowed_fields := []string{"name", "remark", "public_remark", "weight", "price", "expired_at"}
updateFields := map[string]interface{}{
"updated_at": time.Now(),
req["uuid"] = uuid
err := clients.SaveClient(req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
for _, field := range allowed_fields {
if req[field] != nil {
updateFields[field] = req[field]
}
}
if len(updateFields) > 1 { // 大于1是因为至少包含了updated_at
if err := db.Model(&common.ClientInfo{}).Where("uuid = ?", uuid).Updates(updateFields).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
}
user_uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), user_uuid.(string), "edit client:"+uuid, "info")
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
@@ -79,17 +64,21 @@ func RemoveClient(c *gin.Context) {
})
return
}
user_uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), user_uuid.(string), "delete client:"+uuid, "warn")
c.JSON(200, gin.H{"status": "success"})
}
func ClearRecord(c *gin.Context) {
if err := records.DeleteAll(); err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to delete Record" + err.Error(),
"status": "error",
"message": "Failed to delete Record" + err.Error(),
})
return
}
user_uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), user_uuid.(string), "clear records", "warn")
c.JSON(200, gin.H{"status": "success"})
}
@@ -97,8 +86,8 @@ func GetClient(c *gin.Context) {
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing UUID",
"status": "error",
"message": "Invalid or missing UUID",
})
return
}
@@ -106,8 +95,8 @@ func GetClient(c *gin.Context) {
result, err := clients.GetClientByUUID(uuid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"status": "error",
"error": err.Error(),
"status": "error",
"message": err.Error(),
})
return
}
@@ -118,7 +107,7 @@ func GetClient(c *gin.Context) {
func ListClients(c *gin.Context) {
cls, err := clients.GetAllClientBasicInfo()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
@@ -129,17 +118,17 @@ func GetClientToken(c *gin.Context) {
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing UUID",
"status": "error",
"message": "Invalid or missing UUID",
})
return
}
token, err := clients.GetClientTokenByUUID(uuid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "token": token})
c.JSON(http.StatusOK, gin.H{"status": "success", "token": token, "message:": ""})
}
+9 -14
View File
@@ -2,32 +2,27 @@ package admin
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/database/models"
)
func OrderWeight(c *gin.Context) {
var req = make(map[string]int)
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing request body",
})
api.RespondError(c, 400, "Invalid or missing request body: "+err.Error())
return
}
db := dbcore.GetDBInstance()
for uuid, weight := range req {
err := db.Model(&common.ClientInfo{}).Where("uuid = ?", uuid).Update("weight", weight).Error
err := db.Model(&models.Client{}).Where("uuid = ?", uuid).Update("weight", weight).Error
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to update client weight",
})
api.RespondError(c, 500, "Failed to update client weight: "+err.Error())
return
}
}
c.JSON(200, gin.H{
"status": "success",
"message": "Client weight updated successfully",
})
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "order clients", "info")
api.RespondSuccess(c, nil)
}
+78
View File
@@ -0,0 +1,78 @@
package admin
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/database/tasks"
"github.com/komari-monitor/komari/utils"
"github.com/komari-monitor/komari/ws"
)
// 接受数据类型:
// - command: string
// - clients: []string (客户端 UUID 列表)
func Exec(c *gin.Context) {
var req struct {
Command string `json:"command" binding:"required"`
Clients []string `json:"clients" binding:"required"`
}
var onlineClients []string
if err := c.ShouldBindJSON(&req); err != nil {
api.RespondError(c, 400, "Invalid or missing request body: "+err.Error())
return
}
for uuid := range ws.ConnectedClients {
if contain(req.Clients, uuid) {
onlineClients = append(onlineClients, uuid)
} else {
api.RespondError(c, 400, "Client not connected: "+uuid)
return
}
}
if len(onlineClients) == 0 {
api.RespondError(c, 400, "No clients connected")
return
}
taskId := utils.GenerateRandomString(16)
if err := tasks.CreateTask(taskId, onlineClients, req.Command); err != nil {
api.RespondError(c, 500, "Failed to create task: "+err.Error())
return
}
for _, uuid := range onlineClients {
var send struct {
Message string `json:"message"`
Command string `json:"command"`
TaskId string `json:"task_id"`
}
send.Message = "exec"
send.Command = req.Command
send.TaskId = taskId
payload, _ := json.Marshal(send)
client := ws.ConnectedClients[uuid]
if client != nil {
client.WriteMessage(websocket.TextMessage, payload)
} else {
api.RespondError(c, 400, "Client connection is null: "+uuid)
return
}
}
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "REC, task id: "+taskId, "warn")
api.RespondSuccess(c, gin.H{
"task_id": taskId,
"clients": onlineClients,
})
}
func contain(clients []string, uuid string) bool {
for _, client := range clients {
if client == uuid {
return true
}
}
return false
}
+49
View File
@@ -0,0 +1,49 @@
package log
import (
"strconv"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
)
func GetLogs(c *gin.Context) {
limit := c.Query("limit")
if limit == "" {
limit = "100" // Default to 100 logs if not specified
}
page := c.Query("page")
if page == "" {
page = "1" // Default to page 1 if not specified
}
// Convert limit and page to integers
// If conversion fails, return an error
limitInt, err := strconv.Atoi(limit)
if err != nil || limitInt <= 0 {
api.RespondError(c, 400, "Invalid limit: "+limit)
return
}
pageInt, err := strconv.Atoi(page)
if err != nil || pageInt <= 0 {
api.RespondError(c, 400, "Invalid page: "+page)
return
}
db := dbcore.GetDBInstance()
var logs []models.Log
// 添加分页:计算偏移量并限制数量
offset := (pageInt - 1) * limitInt
var total int64
if err := db.Model(&models.Log{}).Count(&total).Error; err != nil {
api.RespondError(c, 500, "Failed to count logs: "+err.Error())
return
}
if err := db.Order("time desc").Limit(limitInt).Offset(offset).Find(&logs).Error; err != nil {
api.RespondError(c, 500, "Failed to retrieve logs: "+err.Error())
return
}
api.RespondSuccess(c, gin.H{"logs": logs, "total": total})
}
+5 -4
View File
@@ -2,6 +2,7 @@ package admin
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/accounts"
)
@@ -9,7 +10,7 @@ func BindingExternalAccount(c *gin.Context) {
session, _ := c.Cookie("session_token")
user, err := accounts.GetUserBySession(session)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "No user found"})
api.RespondError(c, 500, "No user found: "+err.Error())
return
}
@@ -20,15 +21,15 @@ func UnbindExternalAccount(c *gin.Context) {
session, _ := c.Cookie("session_token")
user, err := accounts.GetUserBySession(session)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "No user found"})
api.RespondError(c, 500, "No user found: "+err.Error())
return
}
err = accounts.UnbindExternalAccount(user.UUID)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "Failed to unbind external account"})
api.RespondError(c, 500, "Failed to unbind external account: "+err.Error())
return
}
c.JSON(200, gin.H{"status": "success", "message": "External account unbound"})
api.RespondSuccess(c, nil)
}
+12 -26
View File
@@ -1,7 +1,9 @@
package admin
import (
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/gin-gonic/gin"
)
@@ -10,10 +12,7 @@ func GetSessions(c *gin.Context) {
ss, err := accounts.GetAllSessions()
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to get sessions",
})
api.RespondError(c, 500, "Failed to retrieve sessions: "+err.Error())
return
}
current, _ := c.Cookie("session_token")
@@ -25,40 +24,27 @@ func DeleteSession(c *gin.Context) {
Session string `json:"session" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing session",
})
api.RespondError(c, 400, "Invalid request: "+err.Error())
return
}
err := accounts.DeleteSession(req.Session)
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to delete session",
})
api.RespondError(c, 500, "Failed to delete session: "+err.Error())
return
}
c.JSON(200, gin.H{
"status": "success",
"message": "Session deleted successfully",
})
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "delete session", "info")
api.RespondSuccess(c, nil)
}
func DeleteAllSession(c *gin.Context) {
err := accounts.DeleteAllSessions()
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to delete session",
})
api.RespondError(c, 500, "Failed to delete all sessions: "+err.Error())
return
}
c.JSON(200, gin.H{
"status": "success",
"message": "Session deleted successfully",
})
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "delete all sessions", "warn")
api.RespondSuccess(c, nil)
}
+32 -13
View File
@@ -3,7 +3,9 @@ package admin
import (
"database/sql"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/database/models"
"github.com/gin-gonic/gin"
@@ -18,35 +20,52 @@ func GetSettings(c *gin.Context) {
cst = models.Config{Sitename: "Komari"}
cst.ID = 1
config.Save(cst)
c.JSON(200, cst)
api.RespondSuccess(c, cst)
return
}
c.JSON(500, gin.H{
"status": "error",
"error": "Internal Server Error: " + err.Error(),
"status": "error",
"message": "Internal Server Error: " + err.Error(),
})
}
c.JSON(200, cst)
api.RespondSuccess(c, cst)
}
// EditSettings 更新自定义配置
func EditSettings(c *gin.Context) {
cfg := make(map[string]interface{})
if err := c.ShouldBindJSON(&cfg); err != nil {
c.JSON(400, gin.H{
"status": "error",
"error": "Bad Request: " + err.Error(),
})
api.RespondError(c, 400, "Invalid or missing request body: "+err.Error())
return
}
cfg["id"] = 1 // Only one record
if err := config.Update(cfg); err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Internal Server Error: " + err.Error(),
})
api.RespondError(c, 500, "Failed to update settings: "+err.Error())
return
}
c.JSON(200, gin.H{"status": "success"})
uuid, _ := c.Get("uuid")
message := "update settings: "
for key := range cfg {
ignoredKeys := []string{"id", "updated_at"}
if contains(ignoredKeys, key) {
continue
}
message += key + ", "
}
if len(message) > 2 {
message = message[:len(message)-2]
}
logOperation.Log(c.ClientIP(), uuid.(string), message, "info")
api.RespondSuccess(c, nil)
}
func contains(slice []string, item string) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
}
+154
View File
@@ -0,0 +1,154 @@
package admin
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/tasks"
)
func GetTasks(c *gin.Context) {
dbTasks, err := tasks.GetAllTasks()
if err != nil {
api.RespondError(c, 500, "Failed to retrieve tasks: "+err.Error())
return
}
var responseTasks []gin.H
for _, t := range dbTasks {
results, err := tasks.GetTaskResultsByTaskId(t.TaskId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve task results: "+err.Error())
return
}
var filteredResults []gin.H
for _, r := range results {
filteredResults = append(filteredResults, gin.H{
"client": r.Client,
"result": r.Result,
"exit_code": r.ExitCode,
"finished_at": r.FinishedAt,
"created_at": r.CreatedAt,
})
}
responseTasks = append(responseTasks, gin.H{
"task_id": t.TaskId,
"clients": t.Clients,
"command": t.Command,
"results": filteredResults,
})
}
api.RespondSuccess(c, responseTasks)
}
func GetTaskById(c *gin.Context) {
taskId := c.Param("task_id")
if taskId == "" {
api.RespondError(c, 400, "Task ID is required")
return
}
task, err := tasks.GetTaskByTaskId(taskId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve task: "+err.Error())
return
}
if task == nil {
api.RespondError(c, 404, "Task not found")
return
}
results, err := tasks.GetTaskResultsByTaskId(taskId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve task results: "+err.Error())
return
}
var filteredResults []gin.H
for _, r := range results {
filteredResults = append(filteredResults, gin.H{
"client": r.Client,
"result": r.Result,
"exit_code": r.ExitCode,
"finished_at": r.FinishedAt,
"created_at": r.CreatedAt,
})
}
api.RespondSuccess(c, gin.H{
"task_id": task.TaskId,
"clients": task.Clients,
"command": task.Command,
"results": filteredResults,
})
}
func GetTasksByClientId(c *gin.Context) {
clientId := c.Param("uuid")
if clientId == "" {
api.RespondError(c, 400, "Client ID is required")
return
}
tasks, err := tasks.GetTasksByClientId(clientId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve tasks: "+err.Error())
return
}
if len(tasks) == 0 {
api.RespondError(c, 404, "No tasks found for this client")
return
}
api.RespondSuccess(c, tasks)
}
func GetSpecificTaskResult(c *gin.Context) {
taskId := c.Param("task_id")
clientId := c.Param("uuid")
if taskId == "" || clientId == "" {
api.RespondError(c, 400, "Task ID and Client ID are required")
return
}
result, err := tasks.GetSpecificTaskResult(taskId, clientId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve task result: "+err.Error())
return
}
if result == nil {
api.RespondError(c, 404, "No result found for this task and client")
return
}
api.RespondSuccess(c, result)
}
// Param: task_id
func GetTaskResultsByTaskId(c *gin.Context) {
taskId := c.Param("task_id")
if taskId == "" {
api.RespondError(c, 400, "Task ID is required")
return
}
results, err := tasks.GetTaskResultsByTaskId(taskId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve task results: "+err.Error())
return
}
if len(results) == 0 {
api.RespondError(c, 404, "No results found for this task")
return
}
api.RespondSuccess(c, results)
}
func GetAllTaskResultByUUID(c *gin.Context) {
clientId := c.Param("uuid")
if clientId == "" {
api.RespondError(c, 400, "Client ID is required")
return
}
results, err := tasks.GetAllTasksResultByUUID(clientId)
if err != nil {
api.RespondError(c, 500, "Failed to retrieve tasks: "+err.Error())
return
}
if len(results) == 0 {
api.RespondError(c, 404, "No tasks found for this client")
return
}
api.RespondSuccess(c, results)
}
+47
View File
@@ -0,0 +1,47 @@
package test
import (
"net"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/utils/geoip"
"github.com/komari-monitor/komari/utils/telegram"
)
func TestTelegram(c *gin.Context) {
message := "Komari test message."
err := telegram.SendTextMessage(message)
if err != nil {
api.RespondError(c, 500, "Failed to send Telegram message: "+err.Error())
return
}
api.RespondSuccess(c, nil)
}
func TestGeoIp(c *gin.Context) {
ip := c.Query("ip")
if ip == "" {
if cfIP := c.GetHeader("CF-Connecting-IP"); cfIP != "" {
ip = cfIP
} else {
ip = c.ClientIP()
}
}
conf, err := config.Get()
if err != nil {
api.RespondError(c, 500, "Failed to get configuration: "+err.Error())
return
}
if !conf.GeoIpEnabled {
api.RespondError(c, 400, "GeoIP is not enabled in the configuration.")
return
}
GeoIpRecord, err := geoip.GetGeoIpInfo(net.ParseIP(ip))
if err != nil {
api.RespondError(c, 500, "Failed to get GeoIP record: "+err.Error())
return
}
api.RespondSuccess(c, GeoIpRecord)
}
+46
View File
@@ -0,0 +1,46 @@
package update
import (
"io"
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/logOperation"
)
func UploadFavicon(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 5<<20) // 5MB
data, err := io.ReadAll(c.Request.Body)
if err != nil {
if strings.Contains(err.Error(), "request body too large") {
api.RespondError(c, http.StatusRequestEntityTooLarge, "File too large. Maximum size is 5MB")
} else {
api.RespondError(c, http.StatusBadRequest, err.Error())
}
return
}
if err := os.WriteFile("./data/favicon.ico", data, 0644); err != nil {
api.RespondError(c, http.StatusInternalServerError, "Failed to save favicon: "+err.Error())
return
}
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "Favicon uploaded", "info")
api.RespondSuccess(c, nil)
}
func DeleteFavicon(c *gin.Context) {
if err := os.Remove("./data/favicon.ico"); err != nil {
if os.IsNotExist(err) {
api.RespondError(c, http.StatusNotFound, "Favicon not found")
} else {
api.RespondError(c, http.StatusInternalServerError, "Failed to delete favicon: "+err.Error())
}
return
}
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "Favicon deleted", "info")
api.RespondSuccess(c, nil)
}
+18
View File
@@ -0,0 +1,18 @@
package update
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/utils/geoip"
)
func UpdateMmdbGeoIP(c *gin.Context) {
if err := geoip.UpdateGeoIpDatabase(); err != nil {
api.RespondError(c, 500, "Failed to update GeoIP database "+err.Error())
return
}
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "GeoIP database updated", "info")
api.RespondSuccess(c, nil)
}
+40
View File
@@ -0,0 +1,40 @@
package update
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/logOperation"
)
func UpdateUser(c *gin.Context) {
var req struct {
Uuid string `json:"uuid" binding:"required"`
Name *string `json:"username"`
Password *string `json:"password"`
SsoType *string `json:"sso_type"`
}
if err := c.ShouldBindJSON(&req); err != nil {
api.RespondError(c, 400, "Invalid or missing request body: "+err.Error())
return
}
if req.Password == nil && req.Name == nil {
api.RespondError(c, 400, "At least one field (username or password) must be provided")
return
}
if req.Name != nil && len(*req.Name) < 3 {
api.RespondError(c, 400, "Username must be at least 3 characters long")
return
}
if req.Password != nil && len(*req.Password) < 6 {
api.RespondError(c, 400, "Password must be at least 6 characters long")
return
}
if err := accounts.UpdateUser(req.Uuid, req.Name, req.Password, req.SsoType); err != nil {
api.RespondError(c, 500, "Failed to update user: "+err.Error())
return
}
uuid, _ := c.Get("uuid")
logOperation.Log(c.ClientIP(), uuid.(string), "User updated", "warn")
api.RespondSuccess(c, gin.H{"uuid": req.Uuid})
}
+35
View File
@@ -0,0 +1,35 @@
package client
import (
"time"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/database/tasks"
)
func TaskResult(c *gin.Context) {
token := c.Query("token")
clientId, _ := clients.GetClientUUIDByToken(token)
if clientId == "" {
c.JSON(400, gin.H{"status": "error", "message": "Invalid or missing token"})
return
}
var req struct {
TaskId string `json:"task_id" binding:"required"`
Result string `json:"result" binding:"required"`
ExitCode int `json:"exit_code"`
FinishedAt time.Time `json:"finished_at" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"status": "error", "message": "Invalid request"})
return
}
if err := tasks.SaveTaskResult(req.TaskId, clientId, req.Result, req.ExitCode, req.FinishedAt); err != nil {
c.JSON(500, gin.H{"status": "error", "message": "Failed to update task result: " + err.Error()})
return
}
c.JSON(200, gin.H{"status": "success", "message": "Task result updated successfully"})
}
+2 -5
View File
@@ -7,11 +7,8 @@ import (
func GetClientRecentRecords(c *gin.Context) {
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing UUID",
})
RespondError(c, 400, "UUID is required")
return
}
c.JSON(200, Records[uuid])
RespondSuccess(c, Records[uuid])
}
+23 -7
View File
@@ -6,6 +6,8 @@ import (
"net/http"
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/gin-gonic/gin"
)
@@ -16,35 +18,49 @@ type LoginRequest struct {
}
func Login(c *gin.Context) {
conf, _ := config.Get()
if conf.DisablePasswordLogin {
RespondError(c, http.StatusForbidden, "Password login is disabled")
return
}
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Invalid request body"})
RespondError(c, http.StatusBadRequest, "Invalid request body: "+err.Error())
return
}
var data LoginRequest
err = json.Unmarshal(bodyBytes, &data)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Invalid request body"})
RespondError(c, http.StatusBadRequest, "Invalid request body: "+err.Error())
return
}
if data.Username == "" || data.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Invalid request body"})
RespondError(c, http.StatusBadRequest, "Invalid request body: Username and password are required")
return
}
if uuid, success := accounts.CheckPassword(data.Username, data.Password); success {
session, err := accounts.CreateSession(uuid, 2592000)
session, err := accounts.CreateSession(uuid, 2592000, c.Request.UserAgent(), c.ClientIP(), "password")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "Failed to create session" + err.Error()})
RespondError(c, http.StatusInternalServerError, "Failed to create session: "+err.Error())
return
}
c.SetCookie("session_token", session, 2592000, "/", "", false, true)
c.JSON(200, gin.H{"set-cookie": map[string]interface{}{"session_token": session}})
logOperation.Log(c.ClientIP(), uuid, "logged in (password)", "login")
RespondSuccess(c, gin.H{"set-cookie": gin.H{"session_token": session}})
return
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "error": "Invalid credentials"})
RespondError(c, http.StatusUnauthorized, "Invalid credentials")
}
}
func Logout(c *gin.Context) {
session, _ := c.Cookie("session_token")
accounts.DeleteSession(session)
c.SetCookie("session_token", "", -1, "/", "", false, true)
logOperation.Log(c.ClientIP(), "", "logged out", "logout")
c.Redirect(302, "/")
}
-13
View File
@@ -1,13 +0,0 @@
package api
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/accounts"
)
func Logout(c *gin.Context) {
session, _ := c.Cookie("session_token")
accounts.DeleteSession(session)
c.SetCookie("session_token", "", -1, "/", "", false, true)
c.Redirect(302, "/")
}
+1 -1
View File
@@ -22,6 +22,6 @@ func GetMe(c *gin.Context) {
c.JSON(200, gin.H{"username": "Guest", "logged_in": false})
return
}
c.JSON(200, gin.H{"username": user.Username, "logged_in": true, "uuid": user.UUID})
c.JSON(200, gin.H{"username": user.Username, "logged_in": true, "uuid": user.UUID, "sso_type": user.SSOType, "sso_id": user.SSOID})
}
+1 -1
View File
@@ -21,7 +21,7 @@ func TestGetMe(t *testing.T) {
t.Fatalf("Failed to create test user: %v", err)
}
uuid := user.UUID
sessionToken, _ := accounts.CreateSession(uuid, 2592000)
sessionToken, _ := accounts.CreateSession(uuid, 2592000, "test_user_agent", "127.0.0.1", "oauth")
tests := []struct {
name string
+3 -2
View File
@@ -8,7 +8,7 @@ import (
func GetNodesInformation(c *gin.Context) {
clientList, err := clients.GetAllClientBasicInfo()
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": err.Error()})
RespondError(c, 500, "Failed to retrieve client information: "+err.Error())
return
}
@@ -19,7 +19,8 @@ func GetNodesInformation(c *gin.Context) {
clientList[i].IPv6 = ""
clientList[i].Remark = ""
clientList[i].Version = ""
clientList[i].Token = ""
}
c.JSON(200, gin.H{"status": "success", "data": clientList})
RespondSuccess(c, clientList)
}
+11 -8
View File
@@ -6,6 +6,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/utils/oauth"
)
@@ -59,15 +60,16 @@ func OAuthCallback(c *gin.Context) {
session, _ := c.Cookie("session_token")
user, err := accounts.GetUserBySession(session)
if err != nil || user.UUID != uuid {
c.JSON(500, gin.H{"status": "error", "error": "Binding failed"})
c.JSON(500, gin.H{"status": "error", "message": "Binding failed"})
return
}
err = accounts.BindingExternalAccount(user.UUID, sso_id)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "Binding failed"})
c.JSON(500, gin.H{"status": "error", "message": "Binding failed"})
return
}
c.Redirect(302, "/")
logOperation.Log(c.ClientIP(), user.UUID, "bound external account (OAuth)"+fmt.Sprintf(",sso_id: %s", sso_id), "login")
c.Redirect(302, "/manage")
return
}
@@ -75,20 +77,21 @@ func OAuthCallback(c *gin.Context) {
user, err := accounts.GetUserBySSO(sso_id)
if err != nil {
c.JSON(401, gin.H{
"status": "error",
"error": "please log in and bind your GitHub account first.",
"status": "error",
"message": "please log in and bind your GitHub account first.",
})
return
}
// 创建会话
session, err := accounts.CreateSession(user.UUID, 2592000)
session, err := accounts.CreateSession(user.UUID, 2592000, c.Request.UserAgent(), c.ClientIP(), "oauth")
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": err.Error()})
c.JSON(500, gin.H{"status": "error", "message": err.Error()})
return
}
// 设置cookie并返回
c.SetCookie("session_token", session, 2592000, "/", "", false, true)
c.Redirect(302, "/")
logOperation.Log(c.ClientIP(), user.UUID, "logged in (OAuth)", "login")
c.Redirect(302, "/manage")
}
+11 -13
View File
@@ -8,20 +8,18 @@ import (
func GetPublicSettings(c *gin.Context) {
cst, err := config.Get()
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Internal Server Error: " + err.Error(),
})
RespondError(c, 500, err.Error())
return
}
c.JSON(200, gin.H{
"status": "success",
"data": gin.H{
"sitename": cst.Sitename,
"desc": cst.Description,
"custom_head": cst.CustomHead,
"oauth_enable": cst.OAuthEnabled,
"allow_cros": cst.AllowCros,
},
// Return public settings including CORS
RespondSuccess(c, gin.H{
"sitename": cst.Sitename,
"description": cst.Description,
"custom_head": cst.CustomHead,
"custom_body": cst.CustomBody,
"oauth_enable": cst.OAuthEnabled,
"disable_password_login": cst.DisablePasswordLogin,
"allow_cors": cst.AllowCors,
})
}
+19 -9
View File
@@ -8,27 +8,30 @@ import (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/utils"
"github.com/komari-monitor/komari/ws"
)
func RequestTerminal(c *gin.Context) {
uuid := c.Param("uuid")
user_uuid, _ := c.Get("uuid")
_, err := clients.GetClientByUUID(uuid)
if err != nil {
c.JSON(400, gin.H{
"error": "Client not found",
"status": "error",
"message": "Client not found",
})
return
}
// 建立ws
if !websocket.IsWebSocketUpgrade(c.Request) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"})
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Require WebSocket upgrade"})
return
}
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // TODO: 检查源站
return true
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
@@ -38,9 +41,10 @@ func RequestTerminal(c *gin.Context) {
// 新建一个终端连接
id := utils.GenerateRandomString(32)
session := &TerminalSession{
UUID: uuid,
Browser: conn,
Agent: nil,
UserUUID: user_uuid.(string),
UUID: uuid,
Browser: conn,
Agent: nil,
}
TerminalSessionsMutex.Lock()
@@ -59,7 +63,7 @@ func RequestTerminal(c *gin.Context) {
})
if ws.ConnectedClients[uuid] == nil {
conn.WriteMessage(1, []byte("Client offline!"))
conn.WriteMessage(1, []byte("Client offline!\n被控端离线!"))
conn.Close()
TerminalSessionsMutex.Lock()
delete(TerminalSessions, id)
@@ -77,13 +81,13 @@ func RequestTerminal(c *gin.Context) {
TerminalSessionsMutex.Unlock()
return
}
conn.WriteMessage(1, []byte("waiting for agent..."))
conn.WriteMessage(1, []byte("等待被控端连接 waiting for agent..."))
// 如果没有连接上,则关闭连接
time.AfterFunc(30*time.Second, func() {
TerminalSessionsMutex.Lock()
if session.Agent == nil {
if session.Browser != nil {
session.Browser.WriteMessage(1, []byte("timeout"))
session.Browser.WriteMessage(1, []byte("被控端连接超时 timeout"))
session.Browser.Close()
}
conn.Close()
@@ -91,13 +95,17 @@ func RequestTerminal(c *gin.Context) {
}
TerminalSessionsMutex.Unlock()
})
logOperation.Log(c.ClientIP(), user_uuid.(string), "request, terminal id:"+id+",client:"+session.UUID, "terminal")
}
func ForwardTerminal(id string) {
session, exists := TerminalSessions[id]
if !exists || session == nil || session.Agent == nil || session.Browser == nil {
return
}
logOperation.Log("", session.UserUUID, "established, terminal id:"+id, "terminal")
established_time := time.Now()
errChan := make(chan error, 1)
go func() {
@@ -152,6 +160,8 @@ func ForwardTerminal(id string) {
if session.Browser != nil {
session.Browser.Close()
}
disconnect_time := time.Now()
logOperation.Log("", session.UserUUID, "disconnected, terminal id:"+id+", duration:"+disconnect_time.Sub(established_time).String(), "terminal")
TerminalSessionsMutex.Lock()
delete(TerminalSessions, id)
TerminalSessionsMutex.Unlock()
+33
View File
@@ -0,0 +1,33 @@
package cmd
import (
"os"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/spf13/cobra"
"gorm.io/gorm"
)
var PermitPasswordLoginCmd = &cobra.Command{
Use: "permit-login",
Short: "Force permit password login",
Long: `Force permit password login`,
Run: func(cmd *cobra.Command, args []string) {
db := dbcore.GetDBInstance()
err := db.Transaction(func(tx *gorm.DB) error {
return tx.Model(&models.Config{}).Where("id = ?", 1).
Update("disable_password_login", false).Error
})
if err != nil {
cmd.Println("Error:", err)
os.Exit(1)
}
cmd.Println("Password login has been permitted.")
cmd.Println("Please restart the server to apply the changes.")
},
}
func init() {
RootCmd.AddCommand(PermitPasswordLoginCmd)
}
+98 -36
View File
@@ -1,62 +1,74 @@
package cmd
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/api/admin"
log_api "github.com/komari-monitor/komari/api/admin/log"
"github.com/komari-monitor/komari/api/admin/test"
"github.com/komari-monitor/komari/api/admin/update"
"github.com/komari-monitor/komari/api/client"
"github.com/komari-monitor/komari/cmd/flags"
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/logOperation"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/database/records"
"github.com/komari-monitor/komari/database/tasks"
"github.com/komari-monitor/komari/public"
"github.com/komari-monitor/komari/utils/geoip"
"github.com/komari-monitor/komari/ws"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
)
var (
DynamicCorsEnabled bool = false
)
var ServerCmd = &cobra.Command{
Use: "server",
Short: "Start the server",
Long: `Start the server`,
Run: func(cmd *cobra.Command, args []string) {
InitDatabase()
go DoRecordsWork()
go geoip.InitGeoIp()
go DoScheduledWork()
r := gin.Default()
cfg, err := config.Get()
// 动态 CORS 中间件
conf, err := config.Get()
if err != nil {
log.Fatalln("Failed to get config:", err)
log.Fatal(err)
}
if cfg.AllowCros {
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
}
if cfg.GeoIpEnabled {
geoip.InitGeoIp()
go func() {
ticker := time.NewTicker(time.Hour * 24)
for range ticker.C {
geoip.UpdateGeoIpDatabase()
DynamicCorsEnabled = conf.AllowCors
config.Subscribe(func(event config.ConfigEvent) {
DynamicCorsEnabled = event.New.AllowCors
})
r.Use(func(c *gin.Context) {
if DynamicCorsEnabled {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Origin, Content-Length, Content-Type, Authorization, Accept, X-CSRF-Token, X-Requested-With, Set-Cookie")
c.Header("Access-Control-Expose-Headers", "Content-Length, Authorization, Set-Cookie")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Max-Age", "43200") // 12 hours
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
}()
}
}
c.Next()
})
r.Use(func(c *gin.Context) {
if len(c.Request.URL.Path) >= 4 && c.Request.URL.Path[:4] == "/api" {
@@ -77,6 +89,7 @@ var ServerCmd = &cobra.Command{
r.GET("/api/oauth", api.OAuth)
r.GET("/api/oauth_callback", api.OAuthCallback)
r.GET("/api/logout", api.Logout)
r.GET("/api/version", api.GetVersion)
r.GET("/api/recent/:uuid", api.GetClientRecentRecords)
tokenAuthrized := r.Group("/api/clients", api.TokenAuthMiddleware())
@@ -85,10 +98,35 @@ var ServerCmd = &cobra.Command{
tokenAuthrized.POST("/uploadBasicInfo", client.UploadBasicInfo)
tokenAuthrized.POST("/report", client.UploadReport)
tokenAuthrized.GET("/terminal", client.EstablishConnection)
tokenAuthrized.POST("/task/result", client.TaskResult)
}
adminAuthrized := r.Group("/api/admin", api.AdminAuthMiddleware())
{
// test
testGroup := adminAuthrized.Group("/test")
{
testGroup.GET("/telegram", test.TestTelegram)
testGroup.GET("/geoip", test.TestGeoIp)
}
// update
updateGroup := adminAuthrized.Group("/update")
{
updateGroup.POST("/mmdb", update.UpdateMmdbGeoIP)
updateGroup.POST("/user", update.UpdateUser)
updateGroup.PUT("/favicon", update.UploadFavicon)
updateGroup.POST("/favicon", update.DeleteFavicon)
}
// tasks
taskGroup := adminAuthrized.Group("/task")
{
taskGroup.GET("/all", admin.GetTasks)
taskGroup.POST("/exec", admin.Exec)
taskGroup.GET("/:task_id", admin.GetTaskById)
taskGroup.GET("/:task_id/result", admin.GetTaskResultsByTaskId)
taskGroup.GET("/:task_id/result/:uuid", admin.GetSpecificTaskResult)
taskGroup.GET("/client/:uuid", admin.GetTasksByClientId)
}
// settings
adminAuthrized.GET("/settings", admin.GetSettings)
adminAuthrized.POST("/settings", admin.EditSettings)
@@ -123,21 +161,37 @@ var ServerCmd = &cobra.Command{
sessionGroup.POST("/remove", admin.DeleteSession)
sessionGroup.POST("/remove/all", admin.DeleteAllSession)
}
adminAuthrized.GET("/logs", log_api.GetLogs)
}
public.Static(r.Group("/"), func(handlers ...gin.HandlerFunc) {
r.NoRoute(handlers...)
})
// 静态文件服务
public.UpdateIndex(conf)
config.Subscribe(func(event config.ConfigEvent) {
public.UpdateIndex(event.New)
})
srv := &http.Server{
Addr: flags.Listen,
Handler: r,
}
go func() {
cfg, err := config.Get()
if err != nil {
log.Fatalln("Failed to get config:", err)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
OnFatal(err)
log.Fatalf("listen: %s\n", err)
}
public.UpdateIndex(cfg)
}()
r.Run(flags.Listen)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
OnShutdown()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
},
}
@@ -172,7 +226,7 @@ func InitDatabase() {
}
}
func DoRecordsWork() {
func DoScheduledWork() {
ticker := time.NewTicker(time.Minute * 30)
ticker1 := time.NewTicker(60 * time.Second)
records.DeleteRecordBefore(time.Now().Add(-time.Hour * 24 * 30))
@@ -182,11 +236,19 @@ func DoRecordsWork() {
case <-ticker.C:
records.DeleteRecordBefore(time.Now().Add(-time.Hour * 24 * 30))
records.CompactRecord()
break
tasks.ClearTaskResultsByTimeBefore(time.Now().Add(-time.Hour * 24 * 30))
logOperation.RemoveOldLogs()
case <-ticker1.C:
api.SaveClientReportToDB()
break
}
}
}
func OnShutdown() {
logOperation.Log("", "", "server is shutting down", "info")
}
func OnFatal(err error) {
logOperation.Log("", "", "server encountered a fatal error: "+err.Error(), "error")
}
+1
View File
@@ -29,6 +29,7 @@ type ClientConfig struct {
}
// ClientInfo stores static client information
// Deprecated: Use models.Client instead.
type ClientInfo struct {
UUID string `json:"uuid,omitempty" gorm:"type:varchar(36);primaryKey;foreignKey:ClientUUID;references:UUID;constraint:OnDelete:CASCADE"`
Name string `json:"name" gorm:"type:varchar(100);not null"`
+23
View File
@@ -152,3 +152,26 @@ func UnbindExternalAccount(uuid string) error {
}
return nil
}
func UpdateUser(uuid string, name, password, sso_type *string) error {
db := dbcore.GetDBInstance()
updates := make(map[string]interface{})
if name != nil {
updates["username"] = *name
}
if password != nil {
updates["passwd"] = hashPasswd(*password)
}
if sso_type != nil {
updates["sso_type"] = *sso_type
}
updates["updated_at"] = time.Now()
err := db.Model(&models.User{}).Where("uuid = ?", uuid).Updates(updates).Error
if err != nil {
return err
}
if password != nil {
DeleteAllSessions()
}
return nil
}
+31 -4
View File
@@ -20,14 +20,18 @@ func GetAllSessions() (sessions []models.Session, err error) {
}
// CreateSession 创建新会话
func CreateSession(uuid string, expires int) (string, error) {
func CreateSession(uuid string, expires int, userAgent, ip, login_method string) (string, error) {
db := dbcore.GetDBInstance()
session := utils.GenerateRandomString(32)
sessionRecord := models.Session{
UUID: uuid,
Session: session,
Expires: time.Now().Add(time.Duration(expires) * time.Second),
UUID: uuid,
Session: session,
Expires: time.Now().Add(time.Duration(expires) * time.Second),
UserAgent: userAgent,
Ip: ip,
LoginMethod: login_method,
LatestOnline: time.Now(),
}
err := db.Create(&sessionRecord).Error
@@ -83,3 +87,26 @@ func DeleteAllSessions() error {
}
return nil
}
func UpdateLatestOnline(session string) error {
db := dbcore.GetDBInstance()
return db.Model(&models.Session{}).Where("session = ?", session).Update("latest_online", time.Now()).Error
}
func UpdateLatestUserAgent(session, userAgent string) error {
db := dbcore.GetDBInstance()
return db.Model(&models.Session{}).Where("session = ?", session).Update("latest_user_agent", userAgent).Error
}
func UpdateLatestIp(session, ip string) error {
db := dbcore.GetDBInstance()
return db.Model(&models.Session{}).Where("session = ?", session).Update("latest_ip", ip).Error
}
func UpdateLatest(session, useragent, ip string) error {
db := dbcore.GetDBInstance()
return db.Model(&models.Session{}).Where("session = ?", session).Updates(map[string]interface{}{
"latest_online": time.Now(),
"latest_user_agent": useragent,
"latest_ip": ip,
}).Error
}
+55 -29
View File
@@ -30,14 +30,10 @@ func DeleteClient(clientUuid string) error {
if err != nil {
return err
}
err = db.Delete(&common.ClientInfo{}, "uuid = ?", clientUuid).Error
if err != nil {
return err
}
return nil
}
// Decprecated: UpdateOrInsertBasicInfo is deprecated and will be removed in a future release. Use SaveClientInfo instead.
// Deprecated: UpdateOrInsertBasicInfo is deprecated and will be removed in a future release. Use SaveClientInfo instead.
func UpdateOrInsertBasicInfo(cbi common.ClientInfo) error {
db := dbcore.GetDBInstance()
updates := make(map[string]interface{})
@@ -78,10 +74,33 @@ func UpdateOrInsertBasicInfo(cbi common.ClientInfo) error {
updates["version"] = cbi.Version
updates["updated_at"] = time.Now()
err := db.Clauses(clause.OnConflict{
// 转换为更新Client表
client := models.Client{
UUID: cbi.UUID,
}
err := db.Model(&client).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "uuid"}},
DoUpdates: clause.Assignments(updates),
}).Create(&cbi).Error
}).Create(map[string]interface{}{
"uuid": cbi.UUID,
"name": cbi.Name,
"cpu_name": cbi.CpuName,
"arch": cbi.Arch,
"cpu_cores": cbi.CpuCores,
"os": cbi.OS,
"gpu_name": cbi.GpuName,
"ipv4": cbi.IPv4,
"ipv6": cbi.IPv6,
"region": cbi.Region,
"remark": cbi.Remark,
"mem_total": cbi.MemTotal,
"swap_total": cbi.SwapTotal,
"disk_total": cbi.DiskTotal,
"version": cbi.Version,
"updated_at": time.Now(),
}).Error
if err != nil {
return err
}
@@ -101,7 +120,7 @@ func SaveClientInfo(update map[string]interface{}) error {
update["updated_at"] = time.Now()
err := db.Model(&common.ClientInfo{}).Where("uuid = ?", clientUUID).Updates(update).Error
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Updates(update).Error
if err != nil {
return err
}
@@ -120,7 +139,7 @@ func UpdateClientConfig(config common.ClientConfig) error {
func EditClientName(clientUUID, clientName string) error {
db := dbcore.GetDBInstance()
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Update("client_name", clientName).Error
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Update("name", clientName).Error
if err != nil {
return err
}
@@ -160,6 +179,7 @@ func CreateClient() (clientUUID, token string, err error) {
client := models.Client{
UUID: clientUUID,
Token: token,
Name: "client_" + clientUUID[0:8],
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
@@ -168,14 +188,6 @@ func CreateClient() (clientUUID, token string, err error) {
if err != nil {
return "", "", err
}
clientInfo := common.ClientInfo{
UUID: clientUUID,
Name: "client_" + clientUUID[0:8],
}
err = db.Create(&clientInfo).Error
if err != nil {
return "", "", err
}
return clientUUID, token, nil
}
@@ -189,6 +201,7 @@ func CreateClientWithName(name string) (clientUUID, token string, err error) {
client := models.Client{
UUID: clientUUID,
Token: token,
Name: name,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
@@ -197,14 +210,6 @@ func CreateClientWithName(name string) (clientUUID, token string, err error) {
if err != nil {
return "", "", err
}
clientInfo := common.ClientInfo{
UUID: clientUUID,
Name: name,
}
err = db.Create(&clientInfo).Error
if err != nil {
return "", "", err
}
return clientUUID, token, nil
}
@@ -230,14 +235,14 @@ func GetClientByUUID(uuid string) (client models.Client, err error) {
}
// GetClientBasicInfo 获取指定 UUID 的客户端基本信息
func GetClientBasicInfo(uuid string) (client common.ClientInfo, err error) {
func GetClientBasicInfo(uuid string) (client models.Client, err error) {
db := dbcore.GetDBInstance()
err = db.Where("uuid = ?", uuid).First(&client).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return common.ClientInfo{}, fmt.Errorf("客户端不存在: %s", uuid)
return models.Client{}, fmt.Errorf("客户端不存在: %s", uuid)
}
return common.ClientInfo{}, err
return models.Client{}, err
}
return client, nil
}
@@ -252,7 +257,7 @@ func GetClientTokenByUUID(uuid string) (token string, err error) {
return client.Token, nil
}
func GetAllClientBasicInfo() (clients []common.ClientInfo, err error) {
func GetAllClientBasicInfo() (clients []models.Client, err error) {
db := dbcore.GetDBInstance()
err = db.Find(&clients).Error
if err != nil {
@@ -260,3 +265,24 @@ func GetAllClientBasicInfo() (clients []common.ClientInfo, err error) {
}
return clients, nil
}
func SaveClient(updates map[string]interface{}) error {
db := dbcore.GetDBInstance()
clientUUID, ok := updates["uuid"].(string)
if !ok || clientUUID == "" {
return fmt.Errorf("invalid client UUID")
}
// 确保更新的字段不为空
if len(updates) == 0 {
return fmt.Errorf("no fields to update")
}
updates["updated_at"] = time.Now()
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Updates(updates).Error
if err != nil {
return err
}
return nil
}
+33 -4
View File
@@ -1,6 +1,7 @@
package config
import (
"errors"
"log"
"time"
@@ -18,7 +19,7 @@ func Get() (models.Config, error) {
ID: 1,
Sitename: "Komari",
Description: "Komari Monitor, a simple server monitoring tool.",
AllowCros: false,
AllowCors: false,
OAuthEnabled: false,
GeoIpEnabled: true,
GeoIpProvider: "mmdb",
@@ -37,6 +38,7 @@ func Get() (models.Config, error) {
func Save(cst models.Config) error {
db := dbcore.GetDBInstance()
oldConfig, _ := Get()
// Only one records
cst.ID = 1
cst.UpdatedAt = time.Now()
@@ -44,7 +46,7 @@ func Save(cst models.Config) error {
if err := db.Model(&models.Config{}).Where("id = ?", cst.ID).
Select("sitename",
"description",
"allow_cros",
"allow_cors",
"geo_ip_enabled",
"geo_ip_provider",
"o_auth_client_id",
@@ -55,18 +57,45 @@ func Save(cst models.Config) error {
Updates(cst).Error; err != nil {
return err
}
newConfig, _ := Get()
publishEvent(oldConfig, newConfig)
return nil
}
func Update(cst map[string]interface{}) error {
db := dbcore.GetDBInstance()
oldConfig, _ := Get()
// Proceed with update
cst["id"] = 1
cst["updated_at"] = time.Now()
delete(cst, "created_at")
delete(cst, "CreatedAt")
if err := db.Model(&models.Config{}).Where("id = ?", 1).Updates(cst).Error; err != nil {
// 至少有一种登录方式启用
newDisablePasswordLogin := oldConfig.DisablePasswordLogin
newOAuthEnabled := oldConfig.OAuthEnabled
if val, exists := cst["disable_password_login"]; exists {
newDisablePasswordLogin = val.(bool)
}
if val, exists := cst["o_auth_enabled"]; exists {
newOAuthEnabled = val.(bool)
}
if newDisablePasswordLogin && !newOAuthEnabled {
return errors.New("at least one login method must be enabled (password/oauth)")
}
err := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Model(&models.Config{}).Where("id = ?", oldConfig.ID).Updates(cst).Error; err != nil {
return errors.Join(err, errors.New("failed to update configuration"))
}
newConfig := &models.Config{}
if err := tx.Where("id = ?", oldConfig.ID).First(newConfig).Error; err != nil {
return errors.Join(err, errors.New("failed to retrieve updated configuration"))
}
publishEvent(oldConfig, *newConfig)
return nil
})
if err != nil {
return err
}
return nil
+38
View File
@@ -0,0 +1,38 @@
package config
import (
"sync"
"github.com/komari-monitor/komari/database/models"
)
// ConfigEvent represents a configuration change event
type ConfigEvent struct {
Old models.Config
New models.Config
}
// ConfigSubscriber handles config events
type ConfigSubscriber func(event ConfigEvent)
var (
subscribersMu sync.RWMutex
subscribers []ConfigSubscriber
)
// Subscribe registers a subscriber for all config events.
func Subscribe(subscriber ConfigSubscriber) {
subscribersMu.Lock()
defer subscribersMu.Unlock()
subscribers = append(subscribers, subscriber)
}
// publishEvent notifies all subscribers of a config change.
func publishEvent(oldVal, newVal models.Config) {
subscribersMu.RLock()
defer subscribersMu.RUnlock()
event := ConfigEvent{Old: oldVal, New: newVal}
for _, sub := range subscribers {
go sub(event)
}
}
+106 -39
View File
@@ -3,8 +3,6 @@ package dbcore
import (
"fmt"
"log"
"os"
"path/filepath"
"sync"
"github.com/komari-monitor/komari/cmd/flags"
@@ -15,6 +13,68 @@ import (
"gorm.io/gorm"
)
// mergeClientInfo 将旧版ClientInfo数据迁移到新版Client表
func mergeClientInfo(db *gorm.DB) {
var clientInfos []common.ClientInfo
if err := db.Find(&clientInfos).Error; err != nil {
log.Printf("Failed to read ClientInfo table: %v", err)
return
}
for _, info := range clientInfos {
var client models.Client
if err := db.Where("uuid = ?", info.UUID).First(&client).Error; err != nil {
log.Printf("Could not find Client record with UUID %s: %v", info.UUID, err)
continue
}
// 更新Client记录
client.Name = info.Name
client.CpuName = info.CpuName
client.Virtualization = info.Virtualization
client.Arch = info.Arch
client.CpuCores = info.CpuCores
client.OS = info.OS
client.GpuName = info.GpuName
client.IPv4 = info.IPv4
client.IPv6 = info.IPv6
client.Region = info.Region
client.Remark = info.Remark
client.PublicRemark = info.PublicRemark
client.MemTotal = info.MemTotal
client.SwapTotal = info.SwapTotal
client.DiskTotal = info.DiskTotal
client.Version = info.Version
client.Weight = info.Weight
client.Price = info.Price
client.BillingCycle = info.BillingCycle
client.ExpiredAt = info.ExpiredAt
// Save updated Client record
if err := db.Save(&client).Error; err != nil {
log.Printf("Failed to update Client record: %v", err)
continue
}
}
// Backup and rename old table after migration
if err := db.Migrator().RenameTable("client_infos", "client_infos_backup"); err != nil {
log.Printf("Failed to backup ClientInfo table: %v", err)
return
}
log.Println("Data migration completed, old table has been backed up as client_infos_backup")
}
func MergeDatabase(db *gorm.DB) {
if db.Migrator().HasTable("client_infos") {
log.Println("[>0.0.5] Legacy ClientInfo table detected, starting data migration...")
mergeClientInfo(db)
}
if db.Migrator().HasColumn(&models.Config{}, "allow_cros") {
log.Println("[>0.0.5a] Renaming column 'allow_cros' to 'allow_cors' in config table...")
db.Migrator().RenameColumn(&models.Config{}, "allow_cros", "allow_cors")
}
}
var (
instance *gorm.DB
once sync.Once
@@ -23,39 +83,39 @@ var (
// 初始化数据库
// 对于 SQLite:true 如果数据库文件存在,false 如果数据库文件不存在并被创建
// 对于 MySQL/其他数据库:总是返回 true
func InitDatabase() bool {
// 默认使用 SQLite 如果未指定类型
if flags.DatabaseType == "" || flags.DatabaseType == "sqlite" {
if _, err := os.Stat(flags.DatabaseFile); os.IsNotExist(err) {
log.Printf("SQLite database file %q does not exist, creating...", flags.DatabaseFile)
dbDir := filepath.Dir(flags.DatabaseFile)
if dbDir != "" {
if err := os.MkdirAll(dbDir, 0755); err != nil {
log.Fatalf("Failed to create database file directory %q: %v", dbDir, err)
}
}
file, err := os.Create(flags.DatabaseFile)
if err != nil {
log.Fatalf("Failed to create SQLite database file %q: %v", flags.DatabaseFile, err)
}
if err := file.Close(); err != nil {
log.Fatalf("Failed to close database file %q: %v", flags.DatabaseFile, err)
}
return false
} else if err != nil {
log.Fatalf("Failed to check database file %q: %v", flags.DatabaseFile, err)
}
return true
} else if flags.DatabaseType == "mysql" {
// 对于 MySQL,我们不需要创建文件,只需检查连接信息是否有效
log.Printf("Using MySQL database: %s@%s:%s/%s",
flags.DatabaseUser, flags.DatabaseHost, flags.DatabasePort, flags.DatabaseName)
return true
} else {
log.Fatalf("Unsupported database type: %s", flags.DatabaseType)
return false
}
}
// func InitDatabase() bool {
// // 默认使用 SQLite 如果未指定类型
// if flags.DatabaseType == "" || flags.DatabaseType == "sqlite" {
// if _, err := os.Stat(flags.DatabaseFile); os.IsNotExist(err) {
// log.Printf("SQLite database file %q does not exist, creating...", flags.DatabaseFile)
// dbDir := filepath.Dir(flags.DatabaseFile)
// if dbDir != "" {
// if err := os.MkdirAll(dbDir, 0755); err != nil {
// log.Fatalf("Failed to create database file directory %q: %v", dbDir, err)
// }
// }
// file, err := os.Create(flags.DatabaseFile)
// if err != nil {
// log.Fatalf("Failed to create SQLite database file %q: %v", flags.DatabaseFile, err)
// }
// if err := file.Close(); err != nil {
// log.Fatalf("Failed to close database file %q: %v", flags.DatabaseFile, err)
// }
// return false
// } else if err != nil {
// log.Fatalf("Failed to check database file %q: %v", flags.DatabaseFile, err)
// }
// return true
// } else if flags.DatabaseType == "mysql" {
// // 对于 MySQL,我们不需要创建文件,只需检查连接信息是否有效
// log.Printf("Using MySQL database: %s@%s:%s/%s",
// flags.DatabaseUser, flags.DatabaseHost, flags.DatabasePort, flags.DatabaseName)
// return true
// } else {
// log.Fatalf("Unsupported database type: %s", flags.DatabaseType)
// return false
// }
// }
func GetDBInstance() *gorm.DB {
once.Do(func() {
@@ -77,7 +137,7 @@ func GetDBInstance() *gorm.DB {
case "mysql":
// MySQL 连接
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local",
flags.DatabaseUser,
flags.DatabasePass,
flags.DatabaseHost,
@@ -92,15 +152,14 @@ func GetDBInstance() *gorm.DB {
default:
log.Fatalf("Unsupported database type: %s", flags.DatabaseType)
}
MergeDatabase(instance)
// 自动迁移模型
err = instance.AutoMigrate(
&models.User{},
&models.Client{},
// &models.Session{}, Error 1061 (42000): Duplicate key name 'idx_sessions_session'
&models.Record{},
&common.ClientInfo{},
&models.Config{},
&models.Log{},
)
if err != nil {
log.Fatalf("Failed to create tables: %v", err)
@@ -111,6 +170,14 @@ func GetDBInstance() *gorm.DB {
if err != nil {
log.Printf("Failed to create Session table, it may already exist: %v", err)
}
err = instance.AutoMigrate(
&models.Task{},
&models.TaskResult{},
)
if err != nil {
log.Printf("Failed to create Task and TaskResult table, it may already exist: %v", err)
}
})
return instance
}
+31
View File
@@ -0,0 +1,31 @@
package logOperation
import (
"log"
"time"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
)
func Log(ip, uuid, message, msgType string) {
now := time.Now()
db := dbcore.GetDBInstance()
logEntry := &models.Log{
IP: ip,
UUID: uuid,
Message: message,
MsgType: msgType,
Time: now,
}
db.Create(logEntry)
}
// Delete logs older than 30 days
func RemoveOldLogs() {
db := dbcore.GetDBInstance()
threshold := time.Now().AddDate(0, 0, -30)
if err := db.Where("time < ?", threshold).Delete(&models.Log{}).Error; err != nil {
log.Println("Failed to remove old logs:", err)
}
}
+28
View File
@@ -0,0 +1,28 @@
package models
import "time"
type Config struct {
ID uint `json:"id,omitempty" gorm:"primaryKey;autoIncrement"` // 1
Sitename string `json:"sitename" gorm:"type:varchar(100);not null"`
Description string `json:"description" gorm:"type:text"`
AllowCors bool `json:"allow_cors" gorm:"column:allow_cors;default:false"`
// GeoIP 配置
GeoIpEnabled bool `json:"geo_ip_enabled" gorm:"default:true"`
GeoIpProvider string `json:"geo_ip_provider" gorm:"type:varchar(20);default:'mmdb'"` // mmdb, bilibili, ip-api. 暂时只实现了mmdb
// OAuth 配置
OAuthClientID string `json:"o_auth_client_id" gorm:"type:varchar(255)"`
OAuthClientSecret string `json:"o_auth_client_secret" gorm:"type:varchar(255)"`
OAuthEnabled bool `json:"o_auth_enabled" gorm:"default:false"`
DisablePasswordLogin bool `json:"disable_password_login" gorm:"default:false"`
// 自定义美化
CustomHead string `json:"custom_head" gorm:"type:longtext"`
CustomBody string `json:"custom_body" gorm:"type:longtext"`
// Telegram Bot 配置
TelegramEnabled bool `json:"telegram_enabled" gorm:"default:false"`
TelegramEndpoint string `json:"telegram_endpoint" gorm:"type:varchar(255);default:'https://api.telegram.org/bot'"`
TelegramBotToken string `json:"telegram_bot_token" gorm:"type:varchar(255)"`
TelegramChatID string `json:"telegram_chat_id" gorm:"type:varchar(255)"`
CreatedAt time.Time
UpdatedAt time.Time
}
+12
View File
@@ -0,0 +1,12 @@
package models
import "time"
type Log struct {
ID uint `json:"id,omitempty" gorm:"primaryKey;autoIncrement"`
IP string `json:"ip" gorm:"type:varchar(45);"` // IPv4 or IPv6
UUID string `json:"uuid" gorm:"type:varchar(36);"`
Message string `json:"message" gorm:"type:text;not null"`
MsgType string `json:"msg_type" gorm:"type:varchar(20);not null"`
Time time.Time `json:"time" gorm:"autoCreateTime;not null"`
}
+34 -27
View File
@@ -6,10 +6,30 @@ import (
// Client represents a registered client device
type Client struct {
UUID string `json:"uuid,omitempty" gorm:"type:varchar(36);primaryKey"`
Token string `json:"token,omitempty" gorm:"type:varchar(255);unique;not null"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UUID string `json:"uuid,omitempty" gorm:"type:varchar(36);primaryKey"`
Token string `json:"token,omitempty" gorm:"type:varchar(255);unique;not null"`
Name string `json:"name" gorm:"type:varchar(100)"`
CpuName string `json:"cpu_name" gorm:"type:varchar(100)"`
Virtualization string `json:"virtualization" gorm:"type:varchar(50)"`
Arch string `json:"arch" gorm:"type:varchar(50)"`
CpuCores int `json:"cpu_cores" gorm:"type:int"`
OS string `json:"os" gorm:"type:varchar(100)"`
GpuName string `json:"gpu_name" gorm:"type:varchar(100)"`
IPv4 string `json:"ipv4,omitempty" gorm:"type:varchar(100)"`
IPv6 string `json:"ipv6,omitempty" gorm:"type:varchar(100)"`
Region string `json:"region" gorm:"type:varchar(100)"`
Remark string `json:"remark,omitempty" gorm:"type:longtext"`
PublicRemark string `json:"public_remark,omitempty" gorm:"type:longtext"`
MemTotal int64 `json:"mem_total" gorm:"type:bigint"`
SwapTotal int64 `json:"swap_total" gorm:"type:bigint"`
DiskTotal int64 `json:"disk_total" gorm:"type:bigint"`
Version string `json:"version,omitempty" gorm:"type:varchar(100)"`
Weight int `json:"weight" gorm:"type:int"`
Price float64 `json:"price"`
BillingCycle int `json:"billing_cycle"`
ExpiredAt time.Time `json:"expired_at" gorm:"type:timestamp"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// User represents an authenticated user
@@ -25,10 +45,16 @@ type User struct {
// Session manages user sessions
type Session struct {
UUID string `gorm:"type:varchar(36);foreignKey:UserUUID;references:UUID;constraint:OnDelete:CASCADE"`
Session string `gorm:"type:varchar(255);uniqueIndex:idx_sessions_session;not null"`
Expires time.Time `gorm:"not null"`
CreatedAt time.Time
UUID string `json:"uuid" gorm:"type:varchar(36);foreignKey:UserUUID;references:UUID;constraint:OnDelete:CASCADE"`
Session string `json:"session" gorm:"type:varchar(255);uniqueIndex:idx_sessions_session;not null"`
UserAgent string `json:"user_agent" gorm:"type:text"`
Ip string `json:"ip" gorm:"type:varchar(100)"`
LoginMethod string `json:"login_method" gorm:"type:varchar(50)"`
LatestOnline time.Time `json:"latest_online" gorm:"type:timestamp"`
LatestUserAgent string `json:"latest_user_agent" gorm:"type:text"`
LatestIp string `json:"latest_ip" gorm:"type:varchar(100)"`
Expires time.Time `json:"expires" gorm:"not null"`
CreatedAt time.Time `json:"created_at"`
}
// Record logs client metrics over time
@@ -53,22 +79,3 @@ type Record struct {
Connections int `json:"connections"`
ConnectionsUdp int `json:"connections_udp"`
}
// Config stores site-wide settings
type Config struct {
ID uint `json:"id,omitempty" gorm:"primaryKey;autoIncrement"`
Sitename string `json:"sitename" gorm:"type:varchar(100);not null"`
Description string `json:"description" gorm:"type:text"`
AllowCros bool `json:"allow_cros" gorm:"default:false"`
// GeoIP 配置
GeoIpEnabled bool `json:"geo_ip_enabled" gorm:"default:true"`
GeoIpProvider string `json:"geo_ip_provider" gorm:"type:varchar(20);default:'mmdb'"` // mmdb, bilibili, ip-api. 暂时只实现了mmdb
// OAuth 配置
OAuthClientID string `json:"o_auth_client_id" gorm:"type:varchar(255);not null"`
OAuthClientSecret string `json:"o_auth_client_secret" gorm:"type:varchar(255);not null"`
OAuthEnabled bool `json:"o_auth_enabled" gorm:"default:false"`
// 自定义美化
CustomHead string `json:"custom_head" gorm:"type:longtext"`
CreatedAt time.Time
UpdatedAt time.Time
}
+37
View File
@@ -0,0 +1,37 @@
package models
import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
)
// StringArray represents a slice of strings stored as JSON in the database
type StringArray []string
func (sa *StringArray) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return fmt.Errorf("failed to scan StringArray: value is not []byte")
}
return json.Unmarshal(bytes, sa)
}
func (sa StringArray) Value() (driver.Value, error) {
return json.Marshal(sa)
}
type Task struct {
TaskId string `json:"task_id" gorm:"type:varchar(36);primaryKey;unique"`
Clients StringArray `json:"clients" gorm:"type:longtext"`
Command string `json:"command" gorm:"type:text"`
}
type TaskResult struct {
TaskId string `json:"task_id" gorm:"type:varchar(36)"`
Client string `json:"client" gorm:"type:varchar(36)"`
Result string `json:"result" gorm:"type:longtext"`
ExitCode *int `json:"exit_code" gorm:"type:int"`
FinishedAt *time.Time `json:"finished_at" gorm:"type:timestamp"`
CreatedAt time.Time `json:"created_at" gorm:"type:timestamp"`
}
+99
View File
@@ -0,0 +1,99 @@
package tasks
import (
"time"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
)
func CreateTask(taskId string, clients []string, command string) error {
db := dbcore.GetDBInstance()
// Create a new task in the database with clients as JSON array
task := models.Task{
TaskId: taskId,
Clients: models.StringArray(clients),
Command: command,
}
if err := db.Create(&task).Error; err != nil {
return err
}
var taskResults []models.TaskResult
for _, client := range clients {
taskResults = append(taskResults, models.TaskResult{
TaskId: taskId,
Client: client,
Result: "",
ExitCode: nil,
FinishedAt: nil,
CreatedAt: time.Now(),
})
}
if len(taskResults) > 0 {
return db.Create(&taskResults).Error
}
return nil
}
func GetTaskByTaskId(taskId string) (*models.Task, error) {
var task models.Task
if err := dbcore.GetDBInstance().Where("task_id = ?", taskId).First(&task).Error; err != nil {
return nil, err
}
return &task, nil
}
func GetTasksByClientId(clientId string) ([]models.Task, error) {
var tasks []models.Task
if err := dbcore.GetDBInstance().Where("clients LIKE ?", "%"+clientId+"%").Find(&tasks).Error; err != nil {
return nil, err
}
return tasks, nil
}
func GetSpecificTaskResult(taskId, clientId string) (*models.TaskResult, error) {
var result models.TaskResult
if err := dbcore.GetDBInstance().Where("task_id = ? AND client = ?", taskId, clientId).First(&result).Error; err != nil {
return nil, err
}
return &result, nil
}
func GetAllTasksResultByUUID(uuid string) ([]models.TaskResult, error) {
var results []models.TaskResult
if err := dbcore.GetDBInstance().Where("client = ?", uuid).Find(&results).Error; err != nil {
return nil, err
}
return results, nil
}
func GetAllTasks() ([]models.Task, error) {
var tasks []models.Task
if err := dbcore.GetDBInstance().Find(&tasks).Error; err != nil {
return nil, err
}
return tasks, nil
}
func GetTaskResultsByTaskId(taskId string) ([]models.TaskResult, error) {
var results []models.TaskResult
if err := dbcore.GetDBInstance().Where("task_id = ?", taskId).Find(&results).Error; err != nil {
return nil, err
}
return results, nil
}
func DeleteTaskByTaskId(taskId string) error {
return dbcore.GetDBInstance().Where("task_id = ?", taskId).Delete(&models.Task{}).Error
}
func SaveTaskResult(taskId, clientId, result string, exitCode int, timestamp time.Time) error {
return dbcore.GetDBInstance().
Model(&models.TaskResult{}).
Where("task_id = ? AND client = ?", taskId, clientId).
Updates(map[string]interface{}{
"result": result,
"exit_code": exitCode,
"finished_at": timestamp,
}).Error
}
func ClearTaskResultsByTimeBefore(before time.Time) error {
return dbcore.GetDBInstance().Where("created_at < ?", before.Format(time.RFC3339)).Delete(&models.TaskResult{}).Error
}
+4
View File
@@ -1,9 +1,13 @@
package main
import (
"log"
"github.com/komari-monitor/komari/cmd"
"github.com/komari-monitor/komari/utils"
)
func main() {
log.Printf("Komari Monitor %s (hash: %s)", utils.CurrentVersion, utils.VersionHash)
cmd.Execute()
}
+25 -2
View File
@@ -8,6 +8,7 @@ import (
"io/fs"
"log"
"net/http"
"os" // added for file existence check
"strings"
"github.com/gin-gonic/gin"
@@ -47,11 +48,14 @@ func initIndex() {
}
func UpdateIndex(cfg models.Config) {
replaceMap := map[string]string{
"<!-- customize head -->": cfg.CustomHead,
"</head>": cfg.CustomHead + "</head>",
"</body>": cfg.CustomBody + "</body>",
}
updated := RawIndexFile
for k, v := range replaceMap {
IndexFile = strings.Replace(RawIndexFile, k, v, 1)
updated = strings.Replace(updated, k, v, 1)
}
IndexFile = updated
}
func Static(r *gin.RouterGroup, noRoute func(handlers ...gin.HandlerFunc)) {
@@ -71,6 +75,25 @@ func Static(r *gin.RouterGroup, noRoute func(handlers ...gin.HandlerFunc)) {
}
r.StaticFS(fmt.Sprintf("/%s/", folders[i]), http.FS(sub))
}
// Serve favicon.ico: use local file if exists, fallback to embedded
r.GET("/favicon.ico", func(c *gin.Context) {
if _, err := os.Stat("data/favicon.ico"); err == nil {
c.File("data/favicon.ico")
return
}
f, err := DistFS.Open("favicon.ico")
if err != nil {
c.Status(http.StatusNotFound)
return
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Data(http.StatusOK, "image/x-icon", data)
})
noRoute(func(c *gin.Context) {
if c.Request.Method != "GET" && c.Request.Method != "POST" {
+1 -1
View File
@@ -15,7 +15,7 @@ import (
)
var (
GeoIpUrl = "https://gh-proxy.com/raw.githubusercontent.com/Loyalsoldier/geoip/release/GeoLite2-Country.mmdb"
GeoIpUrl = "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/GeoLite2-Country.mmdb"
GeoIpFilePath = "./data/GeoLite2-Country.mmdb"
geoIpDb *maxminddb.Reader = nil
lock = &sync.RWMutex{}
+67
View File
@@ -0,0 +1,67 @@
package telegram
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/komari-monitor/komari/database/config"
)
func SendMessage(message, msgType string) error {
conf, err := config.Get()
if err != nil {
return err
}
if !conf.TelegramEnabled || message == "" {
return errors.New("telegram is disabled or message is empty")
}
endpoint := conf.TelegramEndpoint + conf.TelegramBotToken + "/sendMessage"
data := url.Values{}
data.Set("chat_id", conf.TelegramChatID)
data.Set("text", message)
if msgType != "text" {
data.Set("parse_mode", msgType)
}
resp, err := http.PostForm(endpoint, data)
if err != nil {
return fmt.Errorf("failed to send message: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("telegram API returned non-OK status: %d", resp.StatusCode)
}
var result struct {
Ok bool `json:"ok"`
Description string `json:"description"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return err
}
if !result.Ok {
return fmt.Errorf("telegram API error: %s", result.Description)
}
return nil
}
// SendTextMessage sends a text message via Telegram API
func SendTextMessage(message string) error {
return SendMessage(message, "text")
}
// SendMarkdownMessage sends a message formatted in Markdown via Telegram API
func SendMarkdownMessage(message string) error {
return SendMessage(message, "MarkdownV2")
}
func SendHTMLMessage(message string) error {
return SendMessage(message, "HTML")
}
+6
View File
@@ -0,0 +1,6 @@
package utils
var (
CurrentVersion = "0.0.1"
VersionHash = "unknown"
)