mirror of
https://github.com/komari-monitor/komari.git
synced 2026-11-21 23:44:19 +00:00
- 添加用户认证和权限控制 - 实现客户端管理功能,包括添加、编辑和删除客户端 - 支持客户端上传基础信息和监控报告 - 提供基本的自定义配置功能 - 实现数据库初始化和数据存储
78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"io"
|
|
"komari/database"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// TokenAuthMiddleware creates a Gin middleware that validates a token from query parameters or request body.
|
|
func TokenAuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
var token string
|
|
|
|
// Step 1: Check query parameter for token
|
|
token = c.Query("token")
|
|
|
|
// Step 2: If no token in query, check request body for non-GET requests
|
|
if token == "" && c.Request.Method != http.MethodGet {
|
|
// Read the body
|
|
bodyBytes, err := io.ReadAll(c.Request.Body)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"status": "error", "error": "failed to read request body"})
|
|
return
|
|
}
|
|
|
|
// Restore the body for downstream handlers
|
|
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
|
|
|
// Try to extract token from JSON body
|
|
var bodyMap map[string]interface{}
|
|
if len(bodyBytes) > 0 {
|
|
if err := json.Unmarshal(bodyBytes, &bodyMap); err == nil {
|
|
if tokenVal, exists := bodyMap["token"]; exists {
|
|
if str, ok := tokenVal.(string); ok && str != "" {
|
|
token = str
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if token == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"status": "error", "error": "token is required"})
|
|
return
|
|
}
|
|
|
|
exists, err := checkTokenExists(token)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to validate token"})
|
|
return
|
|
}
|
|
if !exists {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"status": "error", "error": "invalid token"})
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func checkTokenExists(token string) (bool, error) {
|
|
db := database.GetSQLiteInstance()
|
|
var uuid string
|
|
err := db.QueryRow(`SELECT UUID FROM Clients WHERE TOKEN = ?`, token).Scan(&uuid)
|
|
if err == sql.ErrNoRows {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return true, nil
|
|
}
|