working on auth

This commit is contained in:
2024-11-19 10:40:30 +05:30
parent a2739dbbcd
commit 5954ec2501
13 changed files with 284 additions and 38 deletions

View File

@@ -8,6 +8,9 @@ import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"strings"
"time"
"contrib.go.opencensus.io/integrations/ocsql"
@@ -58,24 +61,31 @@ func Client() *ent.Client {
return cl
}
type entity interface {
GetID() (int64, error)
}
// A AuditHook is an example for audit-log hook.
func AuditHook(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (v ent.Value, err error) {
// start timer
start := time.Now()
defer func() {
saveAudit(ctx, m.Type(), m.Op(), v, err, time.Since(start))
}()
// do the operation
v, err = next.Mutate(ctx, m)
// audit log
var id int64
if v != nil {
ev := reflect.Indirect(reflect.ValueOf(v))
f := ev.FieldByName("ID")
if f.IsValid() {
id = f.Int()
}
}
saveAudit(ctx, m.Type(), m.Op(), id, err, time.Since(start))
return
})
}
func saveAudit(ctx context.Context, t string, op ent.Op, v ent.Value, err error, d time.Duration) {
func saveAudit(ctx context.Context, t string, op ent.Op, id int64, err error, d time.Duration) {
if t == "Audit" {
// skip Audit table operations
return
@@ -95,15 +105,30 @@ func saveAudit(ctx context.Context, t string, op ent.Op, v ent.Value, err error,
entOp = "UpdateOne"
}
big.
reqID := ctx.Value("RequestID")
ip := ctx.Value("RequestIP")
ua := ctx.Value("RequestUA")
if en, ok := v.(entity); ok {
id, _ := en.GetID()
logger.Info("%s %s %s-%s(%d) ip=%s ua=%s t=%v error=%e", reqID, status, op.String(), t, id, ip, ua, d, err)
} else {
logger.Info("%s %s %s-%s ip=%s ua=%s t=%v error=%e", reqID, status, op.String(), t, ip, ua, d, err)
var sb strings.Builder
if reqID, ok := ctx.Value("RequestID").(string); ok {
sb.WriteString(reqID + " ")
}
if err != nil {
sb.WriteString("failed ")
}
sb.WriteString(fmt.Sprintf("%s:%s:%d ", entOp, t, id))
if ip, ok := ctx.Value("RequestIP").(string); ok {
sb.WriteString(fmt.Sprintf("ip=%s ", ip))
}
if ua, ok := ctx.Value("RequestUA").(string); ok {
sb.WriteString(fmt.Sprintf("ip=%s ", ua))
}
if err != nil {
sb.WriteString(fmt.Sprintf("error=%s ", err))
}
sb.WriteString(fmt.Sprintf("t=%s", d))
logger.Info(sb.String())
}