forked from eolinker/apinto-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactivity-log.go
73 lines (65 loc) · 1.63 KB
/
activity-log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package apinto_dashboard
import (
"log"
"net/http"
"strings"
)
type ActivityLogAddHandler interface {
Add(user, ip, content, operation, target string, args []*Arg) error
}
type ActivityLogGetHandler interface {
GetLogList(offset, limit int, user, operation, target string, startUnix, endUnix int64) ([]*LogEntity, int64, error)
}
type LogEntity struct {
Time string `json:"time"`
User string `json:"user"`
IP string `json:"ip"`
Operation string `json:"operation"`
Target string `json:"target"`
Content string `json:"content"`
Args []*Arg `json:"args"`
}
type Arg struct {
Key string `json:"key"`
Value interface{} `json:"value"`
}
var (
activityLogHandler ActivityLogAddHandler
isFileterForwarded bool
)
const (
OptLogin = "login"
OptLogout = "logout"
OptCreate = "create"
OptUpdate = "update"
OptDelete = "delete"
)
func SetActivityLogAddHandler(h ActivityLogAddHandler, fileterForwarded bool) {
activityLogHandler = h
isFileterForwarded = fileterForwarded
}
func AddActivityLog(r *http.Request, user, operation, target, content string, args []*Arg) {
if activityLogHandler != nil {
err := activityLogHandler.Add(user, getIP(r), operation, target, content, args)
if err != nil {
log.Println("[ERR] add log:", err)
}
}
}
func getIP(r *http.Request) string {
if !isFileterForwarded {
forwarded := r.Header.Get("x-forwarded-for")
if len(forwarded) > 0 {
if i := strings.Index(forwarded, ","); i > 0 {
return forwarded[:i]
}
return forwarded
}
}
remoteIP := r.RemoteAddr
idx := strings.LastIndex(remoteIP, ":")
if idx > 0 {
return remoteIP[:idx]
}
return remoteIP
}