feat: 代码优化、机器计划任务完善

This commit is contained in:
meilin.huang
2023-07-21 17:07:04 +08:00
parent 7b51705f4e
commit 7f9e972828
56 changed files with 376 additions and 235 deletions

View File

@@ -3,14 +3,14 @@ package api
import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/cryptox"
)
type Common struct {
}
func (i *Common) RasPublicKey(rc *req.Ctx) {
publicKeyStr, err := utils.GetRsaPublicKey()
publicKeyStr, err := cryptox.GetRsaPublicKey()
biz.ErrIsNilAppendErr(err, "rsa生成公私钥失败")
rc.ResData = publicKeyStr
}

View File

@@ -14,7 +14,9 @@ import (
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/cryptox"
"mayfly-go/pkg/utils/stringx"
"mayfly-go/pkg/utils/structx"
"mayfly-go/pkg/ws"
"strconv"
"strings"
@@ -57,7 +59,7 @@ func (d *Db) Save(rc *req.Ctx) {
db := ginx.BindJsonAndCopyTo[*entity.Db](rc.GinCtx, form, new(entity.Db))
// 密码解密,并使用解密后的赋值
originPwd, err := utils.DefaultRsaDecrypt(form.Password, true)
originPwd, err := cryptox.DefaultRsaDecrypt(form.Password, true)
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
db.Password = originPwd
@@ -83,10 +85,10 @@ func (d *Db) GetDatabaseNames(rc *req.Ctx) {
ginx.BindJsonAndValid(rc.GinCtx, form)
db := new(entity.Db)
utils.Copy(db, form)
structx.Copy(db, form)
// 密码解密,并使用解密后的赋值
originPwd, err := utils.DefaultRsaDecrypt(form.Password, true)
originPwd, err := cryptox.DefaultRsaDecrypt(form.Password, true)
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
db.Password = originPwd
@@ -143,7 +145,7 @@ func (d *Db) ExecSql(rc *req.Ctx) {
biz.NotEmpty(form.Sql, "sql不能为空")
// 去除前后空格及换行符
sql := utils.StrTrimSpaceAndBr(form.Sql)
sql := stringx.TrimSpaceAndBr(form.Sql)
execReq := &application.DbSqlExecReq{
DbId: id,
@@ -158,7 +160,7 @@ func (d *Db) ExecSql(rc *req.Ctx) {
isMulti := len(sqls) > 1
var execResAll *application.DbSqlExecRes
for _, s := range sqls {
s = utils.StrTrimSpaceAndBr(s)
s = stringx.TrimSpaceAndBr(s)
// 多条执行,如果有查询语句,则跳过
if isMulti && strings.HasPrefix(strings.ToLower(s), "select") {
continue
@@ -308,7 +310,7 @@ func (d *Db) DumpSql(rc *req.Ctx) {
if ok {
values = append(values, fmt.Sprintf("%#v", strValue))
} else {
values = append(values, utils.ToString(value))
values = append(values, stringx.AnyToStr(value))
}
}
writer.WriteString(fmt.Sprintf(insertSql, table, strings.Join(values, ", ")))

View File

@@ -11,7 +11,8 @@ import (
"mayfly-go/pkg/cache"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/collx"
"mayfly-go/pkg/utils/structx"
"reflect"
"strconv"
"strings"
@@ -120,7 +121,7 @@ func (d *dbAppImpl) Save(dbEntity *entity.Db) {
newDbs = append(newDbs, v)
}
// 比较新旧数据库列表,需要将移除的数据库相关联的信息删除
_, delDb, _ := utils.ArrayCompare(newDbs, oldDbs, func(i1, i2 any) bool {
_, delDb, _ := collx.ArrayCompare(newDbs, oldDbs, func(i1, i2 any) bool {
return i1.(string) == i2.(string)
})
for _, v := range delDb {
@@ -193,7 +194,7 @@ func (da *dbAppImpl) GetDbInstance(id uint64, db string) *DbInstance {
d.PwdDecrypt()
dbInfo := new(DbInfo)
utils.Copy(dbInfo, d)
structx.Copy(dbInfo, d)
dbInfo.Database = db
dbi := &DbInstance{Id: cacheKey, Info: dbInfo}

View File

@@ -3,7 +3,7 @@ package application
import (
"embed"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/stringx"
"strings"
)
@@ -88,7 +88,7 @@ func GetLocalSql(file, key string) string {
sqls := strings.Split(allSql, "---------------------------------------")
var resSql string
for _, sql := range sqls {
sql = utils.StrTrimSpaceAndBr(sql)
sql = stringx.TrimSpaceAndBr(sql)
// 获取sql第一行的sql备注信息如--MYSQL_TABLE_MA 表信息元数据
info := strings.SplitN(sql, "\n", 2)
// 原始sql即去除第一行的key与备注信息

View File

@@ -7,7 +7,7 @@ import (
"mayfly-go/internal/db/domain/entity"
machineapp "mayfly-go/internal/machine/application"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/anyx"
"net"
"github.com/go-sql-driver/mysql"
@@ -51,7 +51,7 @@ func (mm *MysqlMetadata) GetTables() []Table {
for _, re := range res {
tables = append(tables, Table{
TableName: re["tableName"].(string),
TableComment: utils.Any2String(re["tableComment"]),
TableComment: anyx.ConvString(re["tableComment"]),
})
}
return tables
@@ -74,11 +74,11 @@ func (mm *MysqlMetadata) GetColumns(tableNames ...string) []Column {
columns = append(columns, Column{
TableName: re["tableName"].(string),
ColumnName: re["columnName"].(string),
ColumnType: utils.Any2String(re["columnType"]),
ColumnComment: utils.Any2String(re["columnComment"]),
Nullable: utils.Any2String(re["nullable"]),
ColumnKey: utils.Any2String(re["columnKey"]),
ColumnDefault: utils.Any2String(re["columnDefault"]),
ColumnType: anyx.ConvString(re["columnType"]),
ColumnComment: anyx.ConvString(re["columnComment"]),
Nullable: anyx.ConvString(re["nullable"]),
ColumnKey: anyx.ConvString(re["columnKey"]),
ColumnDefault: anyx.ConvString(re["columnDefault"]),
})
}
return columns
@@ -106,11 +106,11 @@ func (mm *MysqlMetadata) GetTableInfos() []Table {
for _, re := range res {
tables = append(tables, Table{
TableName: re["tableName"].(string),
TableComment: utils.Any2String(re["tableComment"]),
CreateTime: utils.Any2String(re["createTime"]),
TableRows: utils.Any2Int(re["tableRows"]),
DataLength: utils.Any2Int64(re["dataLength"]),
IndexLength: utils.Any2Int64(re["indexLength"]),
TableComment: anyx.ConvString(re["tableComment"]),
CreateTime: anyx.ConvString(re["createTime"]),
TableRows: anyx.ConvInt(re["tableRows"]),
DataLength: anyx.ConvInt64(re["dataLength"]),
IndexLength: anyx.ConvInt64(re["indexLength"]),
})
}
return tables
@@ -124,11 +124,11 @@ func (mm *MysqlMetadata) GetTableIndex(tableName string) []Index {
for _, re := range res {
indexs = append(indexs, Index{
IndexName: re["indexName"].(string),
ColumnName: utils.Any2String(re["columnName"]),
IndexType: utils.Any2String(re["indexType"]),
IndexComment: utils.Any2String(re["indexComment"]),
NonUnique: utils.Any2Int(re["nonUnique"]),
SeqInIndex: utils.Any2Int(re["seqInIndex"]),
ColumnName: anyx.ConvString(re["columnName"]),
IndexType: anyx.ConvString(re["indexType"]),
IndexComment: anyx.ConvString(re["indexComment"]),
NonUnique: anyx.ConvInt(re["nonUnique"]),
SeqInIndex: anyx.ConvInt(re["seqInIndex"]),
})
}
// 把查询结果以索引名分组,索引字段以逗号连接

View File

@@ -7,7 +7,8 @@ import (
"mayfly-go/internal/db/domain/entity"
machineapp "mayfly-go/internal/machine/application"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/anyx"
"mayfly-go/pkg/utils/collx"
"net"
"strings"
"time"
@@ -21,7 +22,7 @@ func getPgsqlDB(d *entity.Db, db string) (*sql.DB, error) {
if d.SshTunnelMachineId > 0 {
// 如果使用了隧道,则使用`postgres:ssh:隧道机器id`注册名
driverName = fmt.Sprintf("postgres:ssh:%d", d.SshTunnelMachineId)
if !utils.ArrContains(sql.Drivers(), driverName) {
if !collx.ArrayContains(sql.Drivers(), driverName) {
sql.Register(driverName, &PqSqlDialer{sshTunnelMachineId: d.SshTunnelMachineId})
}
sql.Drivers()
@@ -78,7 +79,7 @@ func (pm *PgsqlMetadata) GetTables() []Table {
for _, re := range res {
tables = append(tables, Table{
TableName: re["tableName"].(string),
TableComment: utils.Any2String(re["tableComment"]),
TableComment: anyx.ConvString(re["tableComment"]),
})
}
return tables
@@ -101,11 +102,11 @@ func (pm *PgsqlMetadata) GetColumns(tableNames ...string) []Column {
columns = append(columns, Column{
TableName: re["tableName"].(string),
ColumnName: re["columnName"].(string),
ColumnType: utils.Any2String(re["columnType"]),
ColumnComment: utils.Any2String(re["columnComment"]),
Nullable: utils.Any2String(re["nullable"]),
ColumnKey: utils.Any2String(re["columnKey"]),
ColumnDefault: utils.Any2String(re["columnDefault"]),
ColumnType: anyx.ConvString(re["columnType"]),
ColumnComment: anyx.ConvString(re["columnComment"]),
Nullable: anyx.ConvString(re["nullable"]),
ColumnKey: anyx.ConvString(re["columnKey"]),
ColumnDefault: anyx.ConvString(re["columnDefault"]),
})
}
return columns
@@ -132,11 +133,11 @@ func (pm *PgsqlMetadata) GetTableInfos() []Table {
for _, re := range res {
tables = append(tables, Table{
TableName: re["tableName"].(string),
TableComment: utils.Any2String(re["tableComment"]),
CreateTime: utils.Any2String(re["createTime"]),
TableRows: utils.Any2Int(re["tableRows"]),
DataLength: utils.Any2Int64(re["dataLength"]),
IndexLength: utils.Any2Int64(re["indexLength"]),
TableComment: anyx.ConvString(re["tableComment"]),
CreateTime: anyx.ConvString(re["createTime"]),
TableRows: anyx.ConvInt(re["tableRows"]),
DataLength: anyx.ConvInt64(re["dataLength"]),
IndexLength: anyx.ConvInt64(re["indexLength"]),
})
}
return tables
@@ -150,11 +151,11 @@ func (pm *PgsqlMetadata) GetTableIndex(tableName string) []Index {
for _, re := range res {
indexs = append(indexs, Index{
IndexName: re["indexName"].(string),
ColumnName: utils.Any2String(re["columnName"]),
IndexType: utils.Any2String(re["indexType"]),
IndexComment: utils.Any2String(re["indexComment"]),
NonUnique: utils.Any2Int(re["nonUnique"]),
SeqInIndex: utils.Any2Int(re["seqInIndex"]),
ColumnName: anyx.ConvString(re["columnName"]),
IndexType: anyx.ConvString(re["indexType"]),
IndexComment: anyx.ConvString(re["indexComment"]),
NonUnique: anyx.ConvInt(re["nonUnique"]),
SeqInIndex: anyx.ConvInt(re["seqInIndex"]),
})
}
return indexs

View File

@@ -14,7 +14,8 @@ import (
"mayfly-go/pkg/ginx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/stringx"
"mayfly-go/pkg/utils/structx"
"mayfly-go/pkg/ws"
"os"
"path"
@@ -82,7 +83,7 @@ func (m *Machine) TestConn(rc *req.Ctx) {
ginx.BindJsonAndValid(g, machineForm)
me := new(entity.Machine)
utils.Copy(me, machineForm)
structx.Copy(me, machineForm)
m.MachineApp.TestConn(me)
}
@@ -192,7 +193,7 @@ func (m *Machine) WsSSH(g *gin.Context) {
recorder = machine.NewRecorder(f)
}
mts, err := machine.NewTerminalSession(utils.RandString(16), wsConn, cli, rows, cols, recorder)
mts, err := machine.NewTerminalSession(stringx.Rand(16), wsConn, cli, rows, cols, recorder)
biz.ErrIsNilAppendErr(err, "\033[1;31m连接失败: %s\033[0m")
// 记录系统操作日志

View File

@@ -10,7 +10,8 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/ginx"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/jsonx"
"mayfly-go/pkg/utils/stringx"
"strconv"
"strings"
@@ -63,7 +64,7 @@ func (m *MachineScript) RunMachineScript(rc *req.Ctx) {
script := ms.Script
// 如果有脚本参数,则用脚本参数替换脚本中的模板占位符参数
if params := g.Query("params"); params != "" {
script = utils.TemplateParse(ms.Script, utils.Json2Map(params))
script = stringx.TemplateParse(ms.Script, jsonx.ToMap(params))
}
cli := m.MachineApp.GetCli(machineId)
biz.ErrIsNilAppendErr(m.TagApp.CanAccess(rc.LoginAccount.Id, cli.GetMachine().TagPath), "%s")

View File

@@ -5,8 +5,10 @@ import (
"mayfly-go/internal/machine/domain/repository"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/rediscli"
"mayfly-go/pkg/scheduler"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/collx"
"mayfly-go/pkg/utils/stringx"
"time"
)
@@ -107,7 +109,7 @@ func (m *machineCropJobAppImpl) GetRelateCronJobIds(machineId uint64) []uint64 {
func (m *machineCropJobAppImpl) CronJobRelateMachines(cronJobId uint64, machineIds []uint64, la *model.LoginAccount) {
oldMachineIds := m.machineCropJobRelateRepo.GetMachineIds(cronJobId)
addIds, delIds, _ := utils.ArrayCompare[uint64](machineIds, oldMachineIds, func(u1, u2 uint64) bool { return u1 == u2 })
addIds, delIds, _ := collx.ArrayCompare[uint64](machineIds, oldMachineIds, func(u1, u2 uint64) bool { return u1 == u2 })
addVals := make([]*entity.MachineCronJobRelate, 0)
now := time.Now()
@@ -129,7 +131,7 @@ func (m *machineCropJobAppImpl) CronJobRelateMachines(cronJobId uint64, machineI
func (m *machineCropJobAppImpl) MachineRelateCronJobs(machineId uint64, cronJobs []uint64, la *model.LoginAccount) {
oldCronIds := m.machineCropJobRelateRepo.GetCronJobIds(machineId)
addIds, delIds, _ := utils.ArrayCompare[uint64](cronJobs, oldCronIds, func(u1, u2 uint64) bool { return u1 == u2 })
addIds, delIds, _ := collx.ArrayCompare[uint64](cronJobs, oldCronIds, func(u1, u2 uint64) bool { return u1 == u2 })
addVals := make([]*entity.MachineCronJobRelate, 0)
now := time.Now()
@@ -186,7 +188,7 @@ func (m *machineCropJobAppImpl) addCronJob(mcj *entity.MachineCronJob) {
var key string
isDisable := mcj.Status == entity.MachineCronJobStatusDisable
if mcj.Id == 0 {
key = utils.RandString(16)
key = stringx.Rand(16)
mcj.Key = key
if isDisable {
return
@@ -201,11 +203,19 @@ func (m *machineCropJobAppImpl) addCronJob(mcj *entity.MachineCronJob) {
}
scheduler.AddFunByKey(key, mcj.Cron, func() {
m.runCronJob(key)
go m.runCronJob(key)
})
}
func (m *machineCropJobAppImpl) runCronJob(key string) {
// 简单使用redis分布式锁防止多实例同一时刻重复执行
if lock := rediscli.NewLock(key, 30*time.Second); lock != nil {
if !lock.Lock() {
return
}
defer lock.UnLock()
}
cronJob := new(entity.MachineCronJob)
cronJob.Key = key
err := m.machineCropJobRepo.GetBy(cronJob)

View File

@@ -2,7 +2,7 @@ package machine
import (
"fmt"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/stringx"
"strings"
"testing"
)
@@ -69,7 +69,7 @@ func TestTemplateRev(t *testing.T) {
//key := temp[index+1 : ei-1]
//value := SubString(str, index, UnicodeIndex(str, next))
res := make(map[string]any)
utils.ReverStrTemplate(temp, str, res)
stringx.ReverStrTemplate(temp, str, res)
fmt.Println(res)
}

View File

@@ -5,7 +5,7 @@ import (
"io"
"mayfly-go/pkg/global"
"mayfly-go/pkg/scheduler"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/netx"
"net"
"os"
"sync"
@@ -75,7 +75,7 @@ func (stm *SshTunnelMachine) OpenSshTunnel(id uint64, ip string, port int) (expo
stm.mutex.Lock()
defer stm.mutex.Unlock()
localPort, err := utils.GetAvailablePort()
localPort, err := netx.GetAvailablePort()
if err != nil {
return "", 0, err
}

View File

@@ -7,7 +7,7 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/collx"
"strconv"
"strings"
)
@@ -29,7 +29,7 @@ func (m *machineRepoImpl) GetMachineList(condition *entity.MachineQuery, pagePar
if condition.Ids != "" {
// ,分割id转为id数组
qd.In("id", utils.ArrayMap[string, uint64](strings.Split(condition.Ids, ","), func(val string) uint64 {
qd.In("id", collx.ArrayMap[string, uint64](strings.Split(condition.Ids, ","), func(val string) uint64 {
id, _ := strconv.Atoi(val)
return uint64(id)
}))

View File

@@ -12,7 +12,8 @@ import (
"mayfly-go/pkg/cache"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/netx"
"mayfly-go/pkg/utils/structx"
"net"
"regexp"
"time"
@@ -201,7 +202,7 @@ func connect(me *entity.Mongo) (*MongoInstance, error) {
func toMongiInfo(me *entity.Mongo) *MongoInfo {
mi := new(MongoInfo)
utils.Copy(mi, me)
structx.Copy(mi, me)
return mi
}
@@ -212,7 +213,7 @@ type MongoSshDialer struct {
func (sd *MongoSshDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
if sshConn, err := machineapp.GetMachineApp().GetSshTunnelMachine(sd.machineId).GetDialConn(network, address); err == nil {
// 将ssh conn包装否则内部部设置超时会报错,ssh conn不支持设置超时会返回错误: ssh: tcpChan: deadline not supported
return &utils.WrapSshConn{Conn: sshConn}, nil
return &netx.WrapSshConn{Conn: sshConn}, nil
} else {
return nil, err
}

View File

@@ -11,7 +11,8 @@ import (
"mayfly-go/pkg/ginx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/cryptox"
"mayfly-go/pkg/utils/stringx"
"strconv"
"strings"
@@ -47,7 +48,7 @@ func (r *Redis) Save(rc *req.Ctx) {
redis := ginx.BindJsonAndCopyTo[*entity.Redis](rc.GinCtx, form, new(entity.Redis))
// 密码解密,并使用解密后的赋值
originPwd, err := utils.DefaultRsaDecrypt(redis.Password, true)
originPwd, err := cryptox.DefaultRsaDecrypt(redis.Password, true)
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
redis.Password = originPwd
@@ -133,7 +134,7 @@ func (r *Redis) RedisInfo(rc *req.Ctx) {
break
}
if strings.Contains(datas[i], "#") {
key := utils.SubString(datas[i], strings.Index(datas[i], "#")+1, utils.StrLen(datas[i]))
key := stringx.SubString(datas[i], strings.Index(datas[i], "#")+1, stringx.Len(datas[i]))
i++
key = strings.Trim(key, " ")

View File

@@ -7,7 +7,7 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/ginx"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/stringx"
"time"
)
@@ -25,7 +25,7 @@ func (r *Redis) SetStringValue(rc *req.Ctx) {
ri := r.getRedisIns(rc)
cmd := ri.GetCmdable()
rc.ReqParam = fmt.Sprintf("%s -> %s", ri.Info.GetLogDesc(), utils.ToString(keyValue))
rc.ReqParam = fmt.Sprintf("%s -> %s", ri.Info.GetLogDesc(), stringx.AnyToStr(keyValue))
str, err := cmd.Set(context.TODO(), keyValue.Key, keyValue.Value, time.Second*time.Duration(keyValue.Timed)).Result()
biz.ErrIsNilAppendErr(err, "保存字符串值失败: %s")

View File

@@ -12,7 +12,8 @@ import (
"mayfly-go/pkg/cache"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/netx"
"mayfly-go/pkg/utils/structx"
"net"
"strconv"
"strings"
@@ -176,7 +177,7 @@ func getRedisCacheKey(id uint64, db int) string {
func toRedisInfo(re *entity.Redis, db int) *RedisInfo {
redisInfo := new(RedisInfo)
utils.Copy(redisInfo, re)
structx.Copy(redisInfo, re)
redisInfo.Db = db
return redisInfo
}
@@ -243,7 +244,7 @@ func getRedisDialer(machineId int) func(ctx context.Context, network, addr strin
return func(_ context.Context, network, addr string) (net.Conn, error) {
if sshConn, err := sshTunnel.GetDialConn(network, addr); err == nil {
// 将ssh conn包装否则redis内部设置超时会报错,ssh conn不支持设置超时会返回错误: ssh: tcpChan: deadline not supported
return &utils.WrapSshConn{Conn: sshConn}, nil
return &netx.WrapSshConn{Conn: sshConn}, nil
} else {
return nil, err
}

View File

@@ -16,7 +16,12 @@ import (
"mayfly-go/pkg/model"
"mayfly-go/pkg/otp"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/collx"
"mayfly-go/pkg/utils/cryptox"
"mayfly-go/pkg/utils/jsonx"
"mayfly-go/pkg/utils/netx"
"mayfly-go/pkg/utils/stringx"
"mayfly-go/pkg/utils/timex"
"regexp"
"strconv"
"strings"
@@ -55,7 +60,7 @@ func (a *Account) Login(rc *req.Ctx) {
clientIp := getIpAndRegion(rc)
rc.ReqParam = fmt.Sprintf("username: %s | ip: %s", username, clientIp)
originPwd, err := utils.DefaultRsaDecrypt(loginForm.Password, true)
originPwd, err := cryptox.DefaultRsaDecrypt(loginForm.Password, true)
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
account := &entity.Account{Username: username}
@@ -67,7 +72,7 @@ func (a *Account) Login(rc *req.Ctx) {
loginFailMin := accountLoginSecurity.LoginFailMin
biz.IsTrue(nowFailCount < loginFailCount, "登录失败超过%d次, 请%d分钟后再试", loginFailCount, loginFailMin)
if err != nil || !utils.CheckPwdHash(originPwd, account.Password) {
if err != nil || !cryptox.CheckPwdHash(originPwd, account.Password) {
nowFailCount++
cache.SetStr(failCountKey, strconv.Itoa(nowFailCount), time.Minute*time.Duration(loginFailMin))
panic(biz.NewBizErr(fmt.Sprintf("用户名或密码错误【当前登录失败%d次】", nowFailCount)))
@@ -96,7 +101,7 @@ func (a *Account) Login(rc *req.Ctx) {
// 修改状态为已注册
otpStatus = OtpStatusReg
// 该token用于otp双因素校验
token = utils.RandString(32)
token = stringx.Rand(32)
// 未注册otp secret或重置了秘钥
if otpSecret == "" || otpSecret == "-" {
otpStatus = OtpStatusNoReg
@@ -116,7 +121,7 @@ func (a *Account) Login(rc *req.Ctx) {
OtpSecret: otpSecret,
AccessToken: accessToken,
}
cache.SetStr(fmt.Sprintf("otp:token:%s", token), utils.ToJsonStr(otpInfo), time.Minute*time.Duration(3))
cache.SetStr(fmt.Sprintf("otp:token:%s", token), jsonx.ToStr(otpInfo), time.Minute*time.Duration(3))
} else {
// 不进行otp二次校验则直接返回accessToken
token = accessToken
@@ -133,7 +138,7 @@ func (a *Account) Login(rc *req.Ctx) {
// 获取ip与归属地信息
func getIpAndRegion(rc *req.Ctx) string {
clientIp := rc.GinCtx.ClientIP()
return fmt.Sprintf("%s %s", clientIp, utils.Ip2Region(clientIp))
return fmt.Sprintf("%s %s", clientIp, netx.Ip2Region(clientIp))
}
type OtpVerifyInfo struct {
@@ -214,22 +219,22 @@ func (a *Account) ChangePassword(rc *req.Ctx) {
form := new(form.AccountChangePasswordForm)
ginx.BindJsonAndValid(rc.GinCtx, form)
originOldPwd, err := utils.DefaultRsaDecrypt(form.OldPassword, true)
originOldPwd, err := cryptox.DefaultRsaDecrypt(form.OldPassword, true)
biz.ErrIsNilAppendErr(err, "解密旧密码错误: %s")
account := &entity.Account{Username: form.Username}
err = a.AccountApp.GetAccount(account, "Id", "Username", "Password", "Status")
biz.ErrIsNil(err, "旧密码错误")
biz.IsTrue(utils.CheckPwdHash(originOldPwd, account.Password), "旧密码错误")
biz.IsTrue(cryptox.CheckPwdHash(originOldPwd, account.Password), "旧密码错误")
biz.IsTrue(account.IsEnable(), "该账号不可用")
originNewPwd, err := utils.DefaultRsaDecrypt(form.NewPassword, true)
originNewPwd, err := cryptox.DefaultRsaDecrypt(form.NewPassword, true)
biz.ErrIsNilAppendErr(err, "解密新密码错误: %s")
biz.IsTrue(CheckPasswordLever(originNewPwd), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
updateAccount := new(entity.Account)
updateAccount.Id = account.Id
updateAccount.Password = utils.PwdHash(originNewPwd)
updateAccount.Password = cryptox.PwdHash(originNewPwd)
a.AccountApp.Update(updateAccount)
// 赋值loginAccount 主要用于记录操作日志,因为操作日志保存请求上下文没有该信息不保存日志
@@ -267,7 +272,7 @@ func (a *Account) saveLogin(account *entity.Account, ip string) {
// 创建登录消息
loginMsg := &msgentity.Msg{
RecipientId: int64(account.Id),
Msg: fmt.Sprintf("于[%s]-[%s]登录", ip, utils.DefaultTimeFormat(now)),
Msg: fmt.Sprintf("于[%s]-[%s]登录", ip, timex.DefaultFormat(now)),
Type: 1,
}
loginMsg.CreateTime = &now
@@ -295,7 +300,7 @@ func (a *Account) UpdateAccount(rc *req.Ctx) {
if updateAccount.Password != "" {
biz.IsTrue(CheckPasswordLever(updateAccount.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
updateAccount.Password = utils.PwdHash(updateAccount.Password)
updateAccount.Password = cryptox.PwdHash(updateAccount.Password)
}
a.AccountApp.Update(updateAccount)
}
@@ -323,7 +328,7 @@ func (a *Account) SaveAccount(rc *req.Ctx) {
} else {
if account.Password != "" {
biz.IsTrue(CheckPasswordLever(account.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
account.Password = utils.PwdHash(account.Password)
account.Password = cryptox.PwdHash(account.Password)
}
a.AccountApp.Update(account)
}
@@ -380,14 +385,14 @@ func (a *Account) SaveRoles(rc *req.Ctx) {
rc.ReqParam = form
// 将,拼接的字符串进行切割并转换
newIds := utils.ArrayMap[string, uint64](strings.Split(form.RoleIds, ","), func(val string) uint64 {
newIds := collx.ArrayMap[string, uint64](strings.Split(form.RoleIds, ","), func(val string) uint64 {
id, _ := strconv.Atoi(val)
return uint64(id)
})
oIds := a.RoleApp.GetAccountRoleIds(uint64(form.Id))
addIds, delIds, _ := utils.ArrayCompare(newIds, oIds, func(i1, i2 uint64) bool {
addIds, delIds, _ := collx.ArrayCompare(newIds, oIds, func(i1, i2 uint64) bool {
return i1 == i2
})

View File

@@ -9,7 +9,7 @@ import (
"mayfly-go/pkg/ginx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/collx"
"strconv"
"strings"
"time"
@@ -72,14 +72,14 @@ func (r *Role) SaveResource(rc *req.Ctx) {
rc.ReqParam = form
// 将,拼接的字符串进行切割并转换
newIds := utils.ArrayMap[string, uint64](strings.Split(form.ResourceIds, ","), func(val string) uint64 {
newIds := collx.ArrayMap[string, uint64](strings.Split(form.ResourceIds, ","), func(val string) uint64 {
id, _ := strconv.Atoi(val)
return uint64(id)
})
oIds := r.RoleApp.GetRoleResourceIds(uint64(form.Id))
addIds, delIds, _ := utils.ArrayCompare(newIds, oIds, func(i1, i2 uint64) bool {
addIds, delIds, _ := collx.ArrayCompare(newIds, oIds, func(i1, i2 uint64) bool {
return i1 == i2
})

View File

@@ -6,7 +6,7 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/cryptox"
"gorm.io/gorm"
)
@@ -45,7 +45,7 @@ func (a *accountAppImpl) GetPageList(condition *entity.Account, pageParam *model
func (a *accountAppImpl) Create(account *entity.Account) {
biz.IsTrue(a.GetAccount(&entity.Account{Username: account.Username}) != nil, "该账号用户名已存在")
// 默认密码为账号用户名
account.Password = utils.PwdHash(account.Username)
account.Password = cryptox.PwdHash(account.Username)
account.Status = entity.AccountEnableStatus
a.accountRepo.Insert(account)
}

View File

@@ -7,7 +7,7 @@ import (
"mayfly-go/pkg/cache"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/jsonx"
)
const SysConfigKeyPrefix = "sys:config:"
@@ -56,7 +56,7 @@ func (a *configAppImpl) GetConfig(key string) *entity.Config {
if err := a.configRepo.GetConfig(config, "Id", "Key", "Value"); err != nil {
global.Log.Warnf("不存在key = [%s] 的系统配置", key)
} else {
cache.SetStr(SysConfigKeyPrefix+key, utils.ToJsonStr(config), -1)
cache.SetStr(SysConfigKeyPrefix+key, jsonx.ToStr(config), -1)
}
return config
}

View File

@@ -5,7 +5,7 @@ import (
"mayfly-go/internal/sys/domain/repository"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/gormx"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/stringx"
"strings"
"time"
)
@@ -59,7 +59,7 @@ func (r *resourceAppImpl) Save(resource *entity.Resource) {
}
// 生成随机八位唯一标识符
ui := utils.RandString(8)
ui := stringx.Rand(8)
if pid := resource.Pid; pid != 0 {
pResource := r.GetById(uint64(pid))
biz.IsTrue(pResource != nil, "该父资源不存在")

View File

@@ -8,7 +8,7 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/anyx"
"time"
)
@@ -50,7 +50,7 @@ func (m *syslogAppImpl) SaveFromReq(req *req.Ctx) {
}
reqParam := req.ReqParam
if !utils.IsBlank(reqParam) {
if !anyx.IsBlank(reqParam) {
// 如果是字符串类型则不使用json序列化
if reqStr, ok := reqParam.(string); ok {
syslog.ReqParam = reqStr

View File

@@ -11,7 +11,7 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/ginx"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/collx"
"strconv"
"strings"
)
@@ -125,7 +125,7 @@ func (p *Team) SaveTags(rc *req.Ctx) {
oIds := p.TeamApp.ListTagIds(teamId)
// 比较新旧两合集
addIds, delIds, _ := utils.ArrayCompare(form.TagIds, oIds, func(i1, i2 uint64) bool {
addIds, delIds, _ := collx.ArrayCompare(form.TagIds, oIds, func(i1, i2 uint64) bool {
return i1 == i2
})