Skip to content

Commit

Permalink
feature. add buz logic to audit
Browse files Browse the repository at this point in the history
  • Loading branch information
ktkfree committed Feb 13, 2024
1 parent a7095c3 commit b6be649
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 23 deletions.
5 changes: 5 additions & 0 deletions internal/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,10 @@ func migrateSchema(db *gorm.DB) error {
return err
}

// Audit
if err := db.AutoMigrate(&repository.Audit{}); err != nil {
return err
}

return nil
}
85 changes: 66 additions & 19 deletions internal/middleware/audit/audit.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
package audit

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"

"github.com/gorilla/mux"
internalApi "github.com/openinfradev/tks-api/internal/delivery/api"
"github.com/openinfradev/tks-api/internal/middleware/auth/request"
"github.com/openinfradev/tks-api/internal/middleware/logging"
"github.com/openinfradev/tks-api/internal/repository"
"github.com/openinfradev/tks-api/pkg/domain"
"github.com/openinfradev/tks-api/pkg/httpErrors"
"github.com/openinfradev/tks-api/pkg/log"
)

Expand All @@ -25,36 +32,76 @@ func NewDefaultAudit(repo repository.Repository) *defaultAudit {
}
}

func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
type fnAudit = func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string)

// WRITE LOGIC HERE
var auditMap = map[internalApi.Endpoint]fnAudit{
internalApi.CreateStack: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) {
input := domain.CreateStackRequest{}
_ = json.Unmarshal(in, &input)

log.InfoWithContext(ctx, endpoint)
if statusCode >= 200 && statusCode < 300 {
return fmt.Sprintf("[%s] 스택을 생성하였습니다.", input.Name), ""
}

GetIpAddress(w, r)
var e httpErrors.RestError
_ = json.NewDecoder(out).Decode(&e)
return "스택을 생성하는데 실패하였습니다. ", e.Text()
}, internalApi.GetStacks: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) {
return "스택을 조회 하였습니다.", ""
},
}

func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := request.UserFrom(r.Context())
if !ok {
log.Error("Invalid user token")
return
}
userId := user.GetUserId()

lrw := logging.NewLoggingResponseWriter(w)
handler.ServeHTTP(lrw, r)

statusCode := lrw.GetStatusCode()

log.Infof("%v", endpoint)
log.Infof("%v", internalApi.CreateStack)
vars := mux.Vars(r)
organizationId, ok := vars["organizationId"]
if !ok {
organizationId = user.GetOrganizationId()
}

// check & matching
if statusCode >= 200 && statusCode < 300 {
if endpoint == internalApi.CreateStack {
log.Info("스택을 생성하였습니다.")
}
message, description := "", ""
if fn, ok := auditMap[endpoint]; ok {
body, _ := io.ReadAll(r.Body)
message, description = fn(lrw.GetBody(), body, statusCode)
}

dto := domain.Audit{
OrganizationId: organizationId,
Group: internalApi.ApiMap[endpoint].Group,
Message: message,
Description: description,
ClientIP: getClientIpAddress(w, r),
UserId: &userId,
}
if _, err := a.repo.Create(dto); err != nil {
log.Error(err)
}
})
}

func GetIpAddress(w http.ResponseWriter, r *http.Request) {
clientAddr, _, err := net.SplitHostPort(r.RemoteAddr)
log.Info(err)
log.Info(clientAddr)
var X_FORWARDED_FOR = "X-Forwarded-For"

func getClientIpAddress(w http.ResponseWriter, r *http.Request) string {
xforward := r.Header.Get(X_FORWARDED_FOR)
if xforward != "" {
return xforward
}

xforward := r.Header.Get("X-Forwarded-For")
fmt.Println("X-Forwarded-For : ", xforward)
clientAddr, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return clientAddr
}
return ""
}
2 changes: 1 addition & 1 deletion internal/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ func (m *Middleware) Handle(endpoint internalApi.Endpoint, handle http.Handler)

// pre-handler
preHandler := m.authorizer.WithAuthorization(handle)
preHandler = m.audit.WithAudit(endpoint, preHandler)
preHandler = m.requestRecoder.WithRequestRecoder(endpoint, preHandler)
preHandler = m.authenticator.WithAuthentication(preHandler)
preHandler = m.audit.WithAudit(endpoint, preHandler)

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
preHandler.ServeHTTP(w, r)
Expand Down
6 changes: 4 additions & 2 deletions internal/repository/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ type Audit struct {
ID uuid.UUID `gorm:"primarykey"`
OrganizationId string
Organization Organization `gorm:"foreignKey:OrganizationId"`
Type string
Group string
Message string
Description string
ClientIP string
UserId *uuid.UUID `gorm:"type:uuid"`
User User `gorm:"foreignKey:UserId"`
Expand All @@ -59,8 +60,9 @@ func (r *AuditRepository) Fetch(pg *pagination.Pagination) (out []domain.Audit,
func (r *AuditRepository) Create(dto domain.Audit) (auditId uuid.UUID, err error) {
audit := Audit{
OrganizationId: dto.OrganizationId,
Type: dto.Type,
Group: dto.Group,
Message: dto.Message,
Description: dto.Description,
ClientIP: dto.ClientIP,
UserId: dto.UserId}
res := r.db.Create(&audit)
Expand Down
3 changes: 2 additions & 1 deletion pkg/domain/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ type Audit struct {
ID uuid.UUID
OrganizationId string
Organization Organization
Type string
Group string
Message string
Description string
ClientIP string
UserId *uuid.UUID
User User
Expand Down

0 comments on commit b6be649

Please sign in to comment.