Initial commit: LAN Manager with Go backend and Vue frontend
This commit is contained in:
53
server/middleware/auth.go
Normal file
53
server/middleware/auth.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const AdminSessionKey = "admin_user"
|
||||
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
user := session.Get(AdminSessionKey)
|
||||
if user == nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
c.Set("admin_user", user.(string))
|
||||
c.Set("is_admin", true)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func OptionalAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
if user := session.Get(AdminSessionKey); user != nil {
|
||||
c.Set("admin_user", user.(string))
|
||||
c.Set("is_admin", true)
|
||||
} else {
|
||||
c.Set("is_admin", false)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func IsAdmin(c *gin.Context) bool {
|
||||
v, exists := c.Get("is_admin")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
return v.(bool)
|
||||
}
|
||||
|
||||
func CurrentUser(c *gin.Context) string {
|
||||
u, _ := c.Get("admin_user")
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
return u.(string)
|
||||
}
|
||||
19
server/middleware/log.go
Normal file
19
server/middleware/log.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"lan-manager/server/db"
|
||||
)
|
||||
|
||||
func LogOperation(action, entityType string, entityID *int64, entityName, oldValue, newValue, sourceIP, username string) {
|
||||
_, _ = db.DB.Exec(
|
||||
`INSERT INTO operation_logs (action, entity_type, entity_id, entity_name, old_value, new_value, source_ip, username)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
action, entityType, entityID, entityName, oldValue, newValue, sourceIP, username,
|
||||
)
|
||||
}
|
||||
|
||||
func ToJSON(v interface{}) string {
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b)
|
||||
}
|
||||
Reference in New Issue
Block a user