-
Notifications
You must be signed in to change notification settings - Fork 2.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Optimize Location Information Display in System Login Logs #7459
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,9 @@ package service | |
|
||
import ( | ||
"fmt" | ||
"github.com/1Panel-dev/1Panel/backend/utils/common" | ||
"github.com/1Panel-dev/1Panel/backend/utils/geo" | ||
"github.com/gin-gonic/gin" | ||
"os" | ||
"path" | ||
"path/filepath" | ||
|
@@ -26,7 +29,7 @@ const logs = "https://resource.fit2cloud.com/installation-log.sh" | |
type ILogService interface { | ||
ListSystemLogFile() ([]string, error) | ||
CreateLoginLog(operation model.LoginLog) error | ||
PageLoginLog(search dto.SearchLgLogWithPage) (int64, interface{}, error) | ||
PageLoginLog(c *gin.Context, search dto.SearchLgLogWithPage) (int64, interface{}, error) | ||
|
||
CreateOperationLog(operation model.OperationLog) error | ||
PageOperationLog(search dto.SearchOpLogWithPage) (int64, interface{}, error) | ||
|
@@ -77,7 +80,7 @@ func (u *LogService) ListSystemLogFile() ([]string, error) { | |
return files, nil | ||
} | ||
|
||
func (u *LogService) PageLoginLog(req dto.SearchLgLogWithPage) (int64, interface{}, error) { | ||
func (u *LogService) PageLoginLog(c *gin.Context, req dto.SearchLgLogWithPage) (int64, interface{}, error) { | ||
total, ops, err := logRepo.PageLoginLog( | ||
req.Page, | ||
req.PageSize, | ||
|
@@ -91,6 +94,7 @@ func (u *LogService) PageLoginLog(req dto.SearchLgLogWithPage) (int64, interface | |
if err := copier.Copy(&item, &op); err != nil { | ||
return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) | ||
} | ||
item.Address, _ = geo.GetIPLocation(item.IP, common.GetLang(c)) | ||
dtoOps = append(dtoOps, item) | ||
} | ||
return total, dtoOps, err | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The provided code changes look mostly correct for the intended functionality. However, a few improvements could be made:
Here's an optimized version with some considerations: package service
import (
"errors"
"fmt"
"github.com/1Panel-dev/1Panel/backend/utils/common"
"github.com/1Panel-dev/1Panel/backend/utils/geo"
"github.com/gin-gonic/gin"
)
var (
logs = "https://resource.fit2cloud.com/installation-log.sh"
defaultLimit int64 = 50 // Default page size
)
type LogService struct{}
func NewLogService() *LogService {
return &LogService{}
}
// ListSystemLogFile returns system log files.
func (u *LogService) ListSystemLogFile() ([]string, error) {
files := make([]string, 0)
err := filepath.Walk(logDir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && path == filepath.Join(logDir, fileName) {
files = append(files, path)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error reading logs directory: %w", err)
}
return files, nil
}
// PageLoginLog retrieves paginated login logs based on filters and pagination parameters.
func (u *LogService) PageLoginLog(c *gin.Context, req dto.SearchLgLogWithPage) (int64, interface{}, error) {
lang := common.GetLang(c)
limitParam := c.DefaultQuery("limit", strconv.FormatInt(defaultLimit, 10))
offsetParam := c.Query("offset")
pageSize, offset := parseOffsetAndLimit(limitParam, offsetParam)
if pageSize < 1 || offset < 0 {
return 0, nil, errors.New("invalid limit or offset parameter")
}
total, ops, err := logRepo.PageLoginLog(
req.Page,
int(pageSize),
req.PageSize,
req.LikeFieldFilter(),
req.FieldFilters(),
req.TimeRangeFilter(),)
if err != nil {
return 0, nil, errors.WithMessage(constant.ErrDatabaseAccess, err.Error())
}
dtoOps := make([]LogDTO, len(ops))
for i, op := range ops {
var item LogDTO
copyValuesToDTO(&item, op)
item.Address, _ = geo.GetIPLocation(op.IP, lang)
dtoOps[i] = item
}
return total, convertInterfacesSlice(dtoOps), err
}
func parseOffsetAndLimit(large, small string) (largeNum int, smallNum int) {
largeNumStr := strings.ReplaceAll(dashboardConfig.Server.MaxPaginationSize, ",","")
largeNumParse, err:=strconv.Atoi(largeNumStr)
if err!=nil{
largeNum=dashboardConfig.Server.MaxPaginationSizeInt()
}else{
if largeNum>dashboardConfig.Server.MaxPaginationSizeInt(){
largeNum=dashboardConfig.Server.MaxPaginationSizeInt();
}
}
smallNum,_=strconv.Atoi(small)
return int(largeNum),smallNum
}
func copyValuesToDTO(dest, src interface{}) {
copier.Copy(dest, src)
}
func convertInterfacesSlice(data []interface{}) *[]map[string]interface{} {
result := make([]map[string]interface{}, len(data))
for index, value := range data {
marshal, e := json.Marshal(value)
if e != nil {
continue
}
json.Unmarshal(marshal,&result[index])
}
return &result
} Key Changes Made:
These optimizations aim to improve readability and maintainability while potentially reducing runtime costs. |
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -32,8 +32,8 @@ func GetIPLocation(ip, lang string) (string, error) { | |
if err != nil { | ||
return "", err | ||
} | ||
if lang == "en" { | ||
return geoLocation.Country.En + " " + geoLocation.Province.En, nil | ||
if lang == "zh" { | ||
return geoLocation.Country.Zh + " " + geoLocation.Province.Zh, nil | ||
} | ||
return geoLocation.Country.Zh + " " + geoLocation.Province.Zh, nil | ||
return geoLocation.Country.En + " " + geoLocation.Province.En, nil | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The code has two main issues:
Changes suggested:func GetIPLocation(ip, lang string) (string, error) {
if err != nil {
return "", err
}
switch lang {
case "en":
return geoLocation.Country.En + " " + geoLocation.Province.En, nil
case "zh":
return geoLocation.Country.Zh + " " + geoLocation.Province.Zh, nil
default:
return "", fmt.Errorf("Unsupported language: %s", lang)
}
}
// If 'geoLocation' is not defined elsewhere in this file, you should define it here to avoid compile errors.
type GeoLocation struct {
Country struct {
En string
Zh string
} Province struct {
En string
Zh string
}
} These changes address both issues by using a switch statement for better readability and proper handling of unsupported languages. Additionally, I've added missing type definitions and included a default case to indicate an unsupported language. This ensures that the function behaves as expected across different scenarios. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code provided has some minor adjustments for readability and maintenance:
Unused Imports: The imports of
common
andgeo
frombackend/utils
are not used elsewhere in the file, so they can be removed to clean up the file.Redundant Code Block:
This redundant block should be removed because it doesn't add value to the function when only the IP is needed for logging purposes without additional geolocation information.
Minor Styling Improvements: Minor style fixes such as removing trailing spaces at the end of lines or using consistent indentation might improve code readability.
Here's the updated version of the code after applying these changes:
Summary of Changes:
common
andgeo
.These adjustments make the code cleaner and more maintainable while preserving its functionality.