Commit 614c6aef authored by shajiaiming's avatar shajiaiming

log operation

parent f6fedd70
package log
import (
"bwallet/service/auth_service"
"bwallet/service/operation_log_service"
"fmt"
"github.com/gin-gonic/gin"
"strconv"
"strings"
)
func LogMiddleware(handlerTableName map[string]string) gin.HandlerFunc {
return func(ctx *gin.Context) {
var operation string
// 获取当前用户信息
token := ctx.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
user_id := auth.Uid
user_name := auth.Username
platform_id := auth.PlatformId
// 获取表名 这里会把前面 "加载的包名.HandlerName"
handlerName := strings.Split(ctx.HandlerName(), ".")[1]
if _, ok := handlerTableName[handlerName]; !ok {
ctx.Next()
}
tableDesc := strings.Split(handlerTableName[handlerName], ",")
if len(tableDesc) != 2 {
return // 存在映射,但是不完全则返回
}
tableName := tableDesc[0] // 0表名
desc := tableDesc[1] // 1业务描述
switch ctx.Request.Method {
case "POST":
operation = "增加"
case "GET":
operation = "查询"
case "PUT":
operation = "更新"
case "DELETE":
operation = "删除"
default:
operation = "未知"
}
operationLogService := operation_log_service.OperationLog{
UserId: user_id,
UserName: user_name,
PlatformId: platform_id,
Ip: ctx.ClientIP(),
Operation: operation,
Business: desc,
Table: tableName,
}
if err := operationLogService.Add(); err != nil {
fmt.Println(err)
}
return
}
}
func FirstMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println(c.Request.Method, c.ClientIP(), c.Request.Header.Get("Token"))
fmt.Println("first middleware before next()")
isAbort := c.Query("isAbort")
bAbort, err := strconv.ParseBool(isAbort)
if err != nil {
fmt.Printf("is abort value err, value %s\n", isAbort)
c.Next() // (2)
}
if bAbort {
fmt.Println("first middleware abort") //(3)
c.Abort()
//c.AbortWithStatusJSON(http.StatusOK, "abort is true")
return
} else {
fmt.Println("first middleware doesnot abort") //(4)
return
}
fmt.Println("first middleware after next()")
}
}
func SecondMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("current inside of second middleware")
}
}
package models
import (
"bwallet/pkg/setting"
"bwallet/pkg/util"
)
type OperationLog struct {
Model
Id uint64 `json:"primary_key, id,omitempty"`
UserId int `json:"user_id"`
UserName string `json:"user_name"`
PlatformId int `json:"platform_id"`
Ip uint `json:"ip"`
Operation string `json:"operation"`
Business string `json:"business"`
Table string `json:"table"`
}
type OperationLogs struct {
UserId int `json:"user_id"`
UserName string `json:"user_name"`
PlatformId int `json:"platform_id"`
Ip string `json:"ip"`
Operation string `json:"operation"`
Business string `json:"business"`
Table string `json:"table"`
}
func (a OperationLog) TableName() string {
return setting.DatabaseSetting.Name_Sources + ".wallet_operation_log"
}
func GetOperationLogTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&OperationLog{}).Where(maps).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func GetOperationLogs(pageNum, pageSize int, maps interface{}) ([]*OperationLog, error) {
var operationLogs []*OperationLog
if err := db.Where(maps).Order("id desc").Offset(pageNum).Limit(pageSize).Find(&operationLogs).Error; err != nil {
return nil, err
}
return operationLogs, nil
}
func AddOperationLog(data map[string]interface{}) error {
ip, _ := util.IPString2Long(data["ip"].(string))
operationLog := OperationLog{
UserId: data["user_id"].(int),
UserName: data["user_name"].(string),
PlatformId: data["platform_id"].(int),
Ip: ip,
Operation: data["operation"].(string),
Business: data["business"].(string),
Table: data["table"].(string),
}
if err := db.Create(&operationLog).Error; err != nil {
return err
}
return nil
}
package e
type HandleTableAndDesc map[string]string // value 值填入 {最直接关联的唯一表名},{业务描述}
var HandleTableName = HandleTableAndDesc{
"GetCoins": "coin,获取币种库列表",
"AddCoin": "coin,添加新币种至币种库",
"GetCoin": "coin,获取币种库中币种信息",
"EditCoin": "coin,更新币种库币种信息",
"DeleteCoin": "coin,删除币种库币种",
"GetCoinChains": "coin,获取主链列表",
"GetTypes": "custom,获取币种类型",
"GetWalletCoinRelationCoinRelations": "coin,查询币种列表",
"AddWalletCoinRelationCoinRelation": "coin,添加币种",
"DeleteWalletCoinRelationCoinRelation": "coin,删除币种",
"GetWallets": "coin_platform,获取钱包列表",
"AddWallet": "coin_platform,添加钱包",
"GetWallet": "coin_platform,获取钱包信息",
"EditWallet": "coin_platform,更新钱包",
"DeleteWallet": "coin_platform,删除钱包",
"GetChains": "coin_platform_withhold,获取平行链列表",
"AddChain": "coin_platform_withhold,添加平行链",
"GetChain": "coin_platform_withhold,获取平行链信息",
"EditChain": "coin_platform_withhold,更新平行链",
"DeleteChain": "coin_platform_withhold,删除平行链",
"GetUserChains": "coin_platform_withhold,获取平行链名称",
"GetRecommendCoins": "wallet_recommend_coin,获取推荐币种列表",
"AddRecommendCoin": "wallet_recommend_coin,添加推荐币种",
"EditRecommendCoin": "wallet_recommend_coin,更新推荐币种信息",
"DeleteRecommendCoin": "wallet_recommend_coin,删除推荐币种币种",
"GetSupportedCurrencies": "coin_supported_currency,获取钱包支持的法币列表",
"AddSupportedCurrency": "coin_supported_currency,添加钱包支持的法币",
"GetSupportedCurrency": "coin_supported_currency,获取钱包支持的法币信息",
"EditSupportedCurrency": "coin_supported_currency,更新钱包支持的法币",
"DeleteSupportedCurrency": "coin_supported_currency,删除钱包支持的法币",
"GetCurrencies": "coin_supported_currency,获取法币列表",
"GetSupportedChains": "coin_supported_chain,,获取钱包支持的币种列表",
"AddSupportedChain": "coin_supported_chain,添加钱包支持的币种",
"DeleteSupportedChain": "coin_supported_chain,删除钱包支持的币种",
"GetOperationLogs": "operation_log,查询操作日志列表",
}
......@@ -74,7 +74,7 @@ var (
ErrDeleteCoin = &Errno{Code: 20102, Message: "The coin delete error."}
ErrExistCoin = &Errno{Code: 20103, Message: "The coin already exists."}
ErrNotExistCoin = &Errno{Code: 20104, Message: "The coin not exists."}
ErrAuthCoin = &Errno{Code: 20105, Message: "The coin auth error."}
ErrAuthCoin = &Errno{Code: 20105, Message: "The coin auth error."}
// recommend coin errors
ErrRecommendCoinNotFound = &Errno{Code: 20101, Message: "The recommend coin was not found."}
......@@ -109,11 +109,11 @@ var (
// recommend category errors
ErrRecommendCategoryNotFound = &Errno{Code: 20101, Message: "The recommend category was not found."}
ErrCountRecommendCategory = &Errno{Code: 20102, Message: "The recommend category statistic error."}
ErrAddRecommendCategory = &Errno{Code: 20101, Message: "The recommend category add error."}
ErrUpdateRecommendCategory = &Errno{Code: 20102, Message: "The recommend category update error."}
ErrDeleteRecommendCategory = &Errno{Code: 20102, Message: "The recommend category delete error."}
ErrExistRecommendCategory = &Errno{Code: 20103, Message: "The recommend category already exists."}
ErrCountRecommendCategory = &Errno{Code: 20102, Message: "The recommend category statistic error."}
ErrAddRecommendCategory = &Errno{Code: 20101, Message: "The recommend category add error."}
ErrUpdateRecommendCategory = &Errno{Code: 20102, Message: "The recommend category update error."}
ErrDeleteRecommendCategory = &Errno{Code: 20102, Message: "The recommend category delete error."}
ErrExistRecommendCategory = &Errno{Code: 20103, Message: "The recommend category already exists."}
// wallet supported chain errors
ErrSupportedChainNotFound = &Errno{Code: 20101, Message: "The wallet supported chain was not found."}
......@@ -127,4 +127,8 @@ var (
ErrUserAuthIncorrect = &Errno{Code: 40001, Message: "The user auth was incorrect."}
ErrUserNotFound = &Errno{Code: 20101, Message: "The user was not found."}
ErrPasswordIncorrect = &Errno{Code: 20102, Message: "The password was incorrect."}
// operation log errors
ErrCountOperationLog = &Errno{Code: 20102, Message: "The operation log statistic error."}
ErrAddOperationLog = &Errno{Code: 20101, Message: "The operation log add error."}
)
......@@ -2,6 +2,9 @@ package util
import (
"bwallet/pkg/setting"
"errors"
"math"
"net"
"strconv"
)
......@@ -30,4 +33,29 @@ func ToInt(o interface{}) int {
default:
return -1
}
}
// IPString2Long 把ip字符串转为数值
func IPString2Long(ip string) (uint, error) {
b := net.ParseIP(ip).To4()
if b == nil {
return 0, errors.New("invalid ipv4 format")
}
return uint(b[3]) | uint(b[2])<<8 | uint(b[1])<<16 | uint(b[0])<<24, nil
}
// Long2IPString 把数值转为ip字符串
func Long2IPString(i uint) (string, error) {
if i > math.MaxUint32 {
return "", errors.New("beyond the scope of ipv4")
}
ip := make(net.IP, net.IPv4len)
ip[0] = byte(i >> 24)
ip[1] = byte(i >> 16)
ip[2] = byte(i >> 8)
ip[3] = byte(i)
return ip.String(), nil
}
\ No newline at end of file
package v1
import (
"bwallet/pkg/errno"
"bwallet/pkg/handler"
"bwallet/pkg/util"
"bwallet/service/auth_service"
"bwallet/service/operation_log_service"
"bwallet/validate_service"
"github.com/Unknwon/com"
"github.com/gin-gonic/gin"
)
func GetOperationLogs(c *gin.Context) {
token := c.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
group := auth.Group
var platform_id, user_id int
if ("administrator" == group) {
platform_id = com.StrTo(c.DefaultQuery("platform_id", "1")).MustInt()
} else {
platform_id = auth.PlatformId
}
if arg := c.Query("user_id"); arg != "" {
user_id = com.StrTo(c.Query("user_id")).MustInt()
}
var user_name string
if arg := c.Query("user_name"); arg != "" {
user_name = c.Query("user_id")
}
operationLogService := operation_log_service.OperationLog{
UserId: user_id,
UserName: user_name,
PlatformId: platform_id,
PageNum: util.GetPage(c),
PageSize: util.GetLimit(c),
}
total, err := operationLogService.Count()
if err != nil {
handler.SendResponse(c, errno.ErrCountRecommendCategory, nil)
return
}
operation_logs, err := operationLogService.GetAll()
if err != nil {
handler.SendResponse(c, errno.InternalServerError, nil)
return
}
data := make(map[string]interface{})
data["items"] = operation_logs
data["total"] = total
handler.SendResponse(c, nil, data)
}
func AddOperationLog(c *gin.Context) {
token := c.Request.Header.Get("Token")
authService := auth_service.Auth{Token: token}
auth, _ := authService.GetUserInfo()
operation_log := validate_service.OperationLog{}
c.ShouldBindJSON(&operation_log)
operationLogService := operation_log_service.OperationLog{
UserId: auth.Uid,
UserName: auth.Username,
PlatformId: auth.PlatformId,
Ip: operation_log.Ip,
Operation: operation_log.Operation,
Business: operation_log.Business,
Table: operation_log.Table,
}
if err := operationLogService.Add(); err != nil {
handler.SendResponse(c, errno.ErrAddOperationLog, nil)
return
}
handler.SendResponse(c, nil, nil)
}
package routers
import (
"bwallet/middleware/log"
"bwallet/pkg/e"
"github.com/gin-gonic/gin"
"bwallet/middleware/auth"
......@@ -25,8 +27,11 @@ func InitRouter() *gin.Engine {
//r.POST("/upload", api.UploadImage)
api := r.Group("/api")
api.Use(auth.AUTH())
api.Use(auth.AUTH())
api.POST("/log", v1.AddOperationLog)
api.GET("/logs", v1.GetOperationLogs)
api.Use(log.LogMiddleware(e.HandleTableName))
{
//api.POST("/upload",v1.Upload)
......
package operation_log_service
import (
"bwallet/models"
"bwallet/pkg/util"
)
type OperationLog struct {
UserId int
UserName string
PlatformId int
Ip string
Operation string
Business string
Table string
PageNum int
PageSize int
}
func (ol *OperationLog) Add() error {
operationLog := map[string]interface{}{
"user_id": ol.UserId,
"user_name": ol.UserName,
"platform_id": ol.PlatformId,
"ip": ol.Ip,
"operation": ol.Operation,
"business": ol.Business,
"table": ol.Table,
}
if err := models.AddOperationLog(operationLog); err != nil {
return err
}
return nil
}
func (ol *OperationLog) GetAll() ([]*models.OperationLogs, error) {
var operationLog []*models.OperationLog
operationLog, err := models.GetOperationLogs(ol.PageNum, ol.PageSize, ol.getMaps())
if err != nil {
return nil, err
}
var operationLogs []*models.OperationLogs
for _, value := range operationLog {
op := &models.OperationLogs{}
ip, _ := util.Long2IPString(value.Ip)
op.UserId = value.UserId
op.UserName = value.UserName
op.PlatformId = value.PlatformId
op.Ip = ip
op.Operation = value.Operation
op.Business = value.Business
op.Table = value.Table
operationLogs = append(operationLogs, op)
}
return operationLogs, nil
}
func (ol *OperationLog) Count() (int, error) {
return models.GetOperationLogTotal(ol.getMaps())
}
func (ol *OperationLog) getMaps() (map[string]interface{}) {
maps := make(map[string]interface{})
if ol.UserId != 0 {
maps["user_id"] = ol.UserId
}
if ol.UserName != "" {
maps["user_name"] = ol.UserName
}
if ol.PlatformId != 0 {
maps["platform_id"] = ol.PlatformId
}
if ol.Ip != "" {
ip, _ := util.IPString2Long(ol.Ip)
maps["ip"] = ip
}
return maps
}
package validate_service
type OperationLog struct {
Ip string `json:"ip" validate:"required"`
Operation string `json:"operation" validate:"required"`
Business string `json:"business" validate:"required"`
Table string `json:"table" validate:"required"`
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment