first commit
This commit is contained in:
75
internal/middleware/manage/audit/audit.go
Normal file
75
internal/middleware/manage/audit/audit.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
db "management/internal/db/sqlc"
|
||||
"management/internal/middleware/manage/auth"
|
||||
systemservice "management/internal/service/system"
|
||||
|
||||
"github.com/zhang2092/browser"
|
||||
)
|
||||
|
||||
func Audit(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
defer func(res http.ResponseWriter, req *http.Request) {
|
||||
// 记录审计日志
|
||||
go writeLog(req, start)
|
||||
}(w, r)
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func writeLog(req *http.Request, start time.Time) {
|
||||
end := time.Now()
|
||||
duration := end.Sub(start)
|
||||
var params string
|
||||
method := req.Method
|
||||
if method == "GET" {
|
||||
params = req.URL.Query().Encode()
|
||||
} else if method == "POST" {
|
||||
contentType := req.Header.Get("Content-Type")
|
||||
if strings.Contains(contentType, "application/json") {
|
||||
body := make([]byte, req.ContentLength)
|
||||
req.Body.Read(body)
|
||||
params = string(body)
|
||||
} else if strings.Contains(contentType, "application/x-www-form-urlencoded") {
|
||||
params = req.Form.Encode()
|
||||
}
|
||||
}
|
||||
|
||||
ctx := req.Context()
|
||||
au := auth.AuthUser(ctx)
|
||||
arg := &db.CreateSysAuditLogParams{
|
||||
CreatedAt: time.Now(),
|
||||
Email: au.Email,
|
||||
Username: au.Username,
|
||||
UserUuid: au.Uuid,
|
||||
StartAt: start,
|
||||
EndAt: end,
|
||||
Duration: strconv.FormatInt(duration.Milliseconds(), 10),
|
||||
Url: req.URL.RequestURI(),
|
||||
Method: method,
|
||||
Parameters: params,
|
||||
RefererUrl: req.Header.Get("Referer"),
|
||||
Ip: req.RemoteAddr,
|
||||
Remark: "",
|
||||
}
|
||||
br, err := browser.NewBrowser(req.Header.Get("User-Agent"))
|
||||
if err == nil {
|
||||
arg.Os = br.Platform().Name()
|
||||
arg.Browser = br.Name()
|
||||
}
|
||||
|
||||
c, cancel := context.WithTimeout(context.Background(), time.Second*3)
|
||||
defer cancel()
|
||||
|
||||
_ = systemservice.CreateSysAuditLog(c, arg)
|
||||
}
|
||||
Reference in New Issue
Block a user