From 8aab7e60533d0bbf5ec29199b4ed95e5fee1370a Mon Sep 17 00:00:00 2001 From: "a624669980@163.com" Date: Tue, 14 Jun 2022 15:18:20 +0800 Subject: [PATCH] switch branches --- pkg/sqlite/db.go | 23 +++++-- pkg/utils/encryption/md5_helper.go | 22 +++++++ route/init.go | 24 +++++-- route/route.go | 9 ++- route/v1/user.go | 10 +-- service/github.go | 35 ---------- service/model/o_user.go | 26 ++++++++ service/redis.go | 102 ----------------------------- service/service.go | 2 +- service/user.go | 52 +++++++++++++-- 10 files changed, 137 insertions(+), 168 deletions(-) create mode 100644 pkg/utils/encryption/md5_helper.go delete mode 100644 service/github.go create mode 100644 service/model/o_user.go delete mode 100644 service/redis.go diff --git a/pkg/sqlite/db.go b/pkg/sqlite/db.go index 8c5701f..5367013 100644 --- a/pkg/sqlite/db.go +++ b/pkg/sqlite/db.go @@ -1,11 +1,22 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-05-13 18:15:46 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-06-14 13:40:21 + * @FilePath: /CasaOS/pkg/sqlite/db.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ package sqlite import ( - "fmt" "time" "github.com/IceWhaleTech/CasaOS/pkg/utils/file" + "github.com/IceWhaleTech/CasaOS/pkg/utils/loger" model2 "github.com/IceWhaleTech/CasaOS/service/model" + "go.uber.org/zap" "gorm.io/driver/sqlite" "gorm.io/gorm" ) @@ -16,7 +27,7 @@ func GetDb(dbPath string) *gorm.DB { if gdb != nil { return gdb } - // 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情 + // Refer https://github.com/go-sql-driver/mysql#dsn-data-source-name //dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", m.User, m.PWD, m.IP, m.Port, m.DBName) //db, err := gorm.Open(mysql2.Open(dsn), &gorm.Config{}) file.IsNotExistMkDir(dbPath) @@ -26,14 +37,14 @@ func GetDb(dbPath string) *gorm.DB { c.SetMaxOpenConns(100) c.SetConnMaxIdleTime(time.Second * 1000) if err != nil { - fmt.Println("连接数据失败!") - panic("数据库连接失败") + loger.Error("sqlite connect error", zap.Any("db connect error", err)) + panic("sqlite connect error") return nil } gdb = db - err = db.AutoMigrate(&model2.TaskDBModel{}, &model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.PersonDownloadDBModel{}, model2.FriendModel{}, model2.PersonDownRecordDBModel{}, model2.ApplicationModel{}) + err = db.AutoMigrate(&model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.PersonDownloadDBModel{}, model2.FriendModel{}, model2.PersonDownRecordDBModel{}, model2.ApplicationModel{}, model2.UserDBModel{}) if err != nil { - fmt.Println("检查和创建数据库出错", err) + loger.Error("check or create db error", zap.Any("error", err)) } return db } diff --git a/pkg/utils/encryption/md5_helper.go b/pkg/utils/encryption/md5_helper.go new file mode 100644 index 0000000..c28fe02 --- /dev/null +++ b/pkg/utils/encryption/md5_helper.go @@ -0,0 +1,22 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-06-14 14:33:25 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-06-14 14:33:49 + * @FilePath: /CasaOS/pkg/utils/encryption/md5_helper.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ +package encryption + +import ( + "crypto/md5" + "encoding/hex" +) + +func GetMD5ByStr(str string) string { + h := md5.New() + h.Write([]byte(str)) + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/route/init.go b/route/init.go index 14ab707..579f192 100644 --- a/route/init.go +++ b/route/init.go @@ -13,6 +13,7 @@ import ( "github.com/IceWhaleTech/CasaOS/model/system_app" "github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/utils/command" + "github.com/IceWhaleTech/CasaOS/pkg/utils/encryption" "github.com/IceWhaleTech/CasaOS/pkg/utils/env_helper" "github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/pkg/utils/port" @@ -31,6 +32,7 @@ func InitFunction() { ChangeAPIUrl() InitSystemApplication() + MoveUserToDB() } var syncIsExistence = false @@ -213,11 +215,7 @@ func CheckToken2_11() { config.AppInfo.RootPath = "/casaOS" config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) } - // if len(config.ServerInfo.Handshake) == 0 { - // config.Cfg.Section("app").Key("RootPath").SetValue("/casaOS") - // config.AppInfo.RootPath = "/casaOS" - // config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) - // } + sysType := runtime.GOOS if len(config.FileSettingInfo.DownloadDir) == 0 { downloadPath := "/DATA/Downloads" @@ -294,3 +292,19 @@ func InitSystemApplication() { service.MyService.App().CreateApplication(application) } } + +//0.3.3 +//Transferring user data to the database +func MoveUserToDB() { + + if service.MyService.User().GetUserInfoByUserName(config.UserInfo.UserName).Id == 0 { + user := model2.UserDBModel{} + user.UserName = config.UserInfo.UserName + user.Avatar = config.UserInfo.Avatar + user.Email = config.UserInfo.Email + user.NickName = config.UserInfo.NickName + user.Password = encryption.GetMD5ByStr(config.UserInfo.PWD) + user.Role = "admin" + service.MyService.User().CreateUser(user) + } +} diff --git a/route/route.go b/route/route.go index 00fd25b..407e122 100644 --- a/route/route.go +++ b/route/route.go @@ -64,9 +64,8 @@ func InitRouter() *gin.Engine { v1UserGroup.POST("/person/info", v1.PostUserPersonInfo) v1UserGroup.GET("/shareid", v1.GetUserShareID) - // v1UserGroup.GET("/custom/:name") - // v1UserGroup.POST("/custom/:name") - + v1UserGroup.GET("/custom/:name") + v1UserGroup.POST("/custom/:name") } v1AppGroup := v1Group.Group("/app") v1AppGroup.Use() @@ -119,10 +118,10 @@ func InitRouter() *gin.Engine { v1SysGroup.POST("/update", v1.SystemUpdate) v1SysGroup.GET("/wsssh", v1.WsSsh) v1SysGroup.GET("/config", v1.GetSystemConfig) + //v1SysGroup.POST("/config", v1.PostSetSystemConfig) v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs) - v1SysGroup.POST("/config", v1.PostSetSystemConfig) v1SysGroup.GET("/widget/config", v1.GetWidgetConfig) - v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig) + //v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig) v1SysGroup.GET("/port", v1.GetCasaOSPort) v1SysGroup.PUT("/port", v1.PutCasaOSPort) v1SysGroup.POST("/stop", v1.PostKillCasaOS) diff --git a/route/v1/user.go b/route/v1/user.go index 0ff05cd..12b0d82 100644 --- a/route/v1/user.go +++ b/route/v1/user.go @@ -13,18 +13,10 @@ import ( "github.com/gin-gonic/gin" ) -var user_service service.UserService - -func init() { - user_service = service.NewUserService() -} - -// @Summary 设置用户名和密码 +// @Summary set username and password // @Produce application/json // @Accept multipart/form-data // @Tags user -// @Param username formData string true "User name" -// @Param pwd formData string true "password" // @Security ApiKeyAuth // @Success 200 {string} string "ok" // @Router /user/setusernamepwd [post] diff --git a/service/github.go b/service/github.go deleted file mode 100644 index 0e1255b..0000000 --- a/service/github.go +++ /dev/null @@ -1,35 +0,0 @@ -package service - -import ( - "context" - "fmt" - "github.com/google/go-github/v36/github" - "github.com/tidwall/gjson" -) - -type GithubService interface { - GetManifestJsonByRepo() (image, tcp, udp string) -} - -type githubService struct { - cl *github.Client -} - -func (g *githubService) GetManifestJsonByRepo() (image, tcp, udp string) { - c, _, _, e := g.cl.Repositories.GetContents(context.Background(), "a624669980", "o_test_json", "/OasisManifest.json", &github.RepositoryContentGetOptions{}) - if e != nil { - fmt.Println(e) - } - str, e := c.GetContent() - if e != nil { - fmt.Println(e) - } - image = gjson.Get(str, "dockerImage").String() - tcp = gjson.Get(str, "tcp_ports").Raw - udp = gjson.Get(str, "udp_ports").Raw - return -} - -func GetNewGithubService(cl *github.Client) GithubService { - return &githubService{cl: cl} -} diff --git a/service/model/o_user.go b/service/model/o_user.go new file mode 100644 index 0000000..b52c848 --- /dev/null +++ b/service/model/o_user.go @@ -0,0 +1,26 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-05-13 18:15:46 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-06-14 14:29:30 + * @FilePath: /CasaOS/service/model/o_user.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ +package model + +//Soon to be removed +type UserDBModel struct { + Id int `gorm:"column:id;primary_key" json:"id"` + UserName string `json:"user_name"` + Password string `json:"password"` + Role string `json:"role"` + Email string `json:"email"` + Avatar string `json:"avatar"` + NickName string `json:"nick_name"` +} + +func (p *UserDBModel) UserDBModel() string { + return "o_user" +} diff --git a/service/redis.go b/service/redis.go deleted file mode 100644 index 004e5e7..0000000 --- a/service/redis.go +++ /dev/null @@ -1,102 +0,0 @@ -package service - -import ( - "encoding/json" - "github.com/gomodule/redigo/redis" -) - -type RedisService interface { - Set(key string, data interface{}, time int) error - Exists(key string) bool - Get(key string) ([]byte, error) - PutExpireTime(key string, time int) - Delete(key string) (bool, error) - LikeDeletes(key string) error -} - -type redisService struct { - rp *redis.Pool -} - -// Set a key/value -func (r *redisService) Set(key string, data interface{}, time int) error { - conn := r.rp.Get() - defer conn.Close() - - value, err := json.Marshal(data) - if err != nil { - return err - } - _, err = conn.Do("SET", key, value) - if err != nil { - return err - } - _, err = conn.Do("EXPIRE", key, time) - if err != nil { - return err - } - return nil -} - -//设置过期时间 -func (r *redisService) PutExpireTime(key string, time int) { - conn := r.rp.Get() - defer conn.Close() - conn.Do("EXPIRE", key, time) -} - -// Exists check a key -func (r *redisService) Exists(key string) bool { - conn := r.rp.Get() - defer conn.Close() - exists, err := redis.Bool(conn.Do("EXISTS", key)) - if err != nil { - return false - } - return exists -} - -// Get get a key -func (r *redisService) Get(key string) ([]byte, error) { - conn := r.rp.Get() - defer conn.Close() - - reply, err := redis.Bytes(conn.Do("GET", key)) - if err != nil { - return nil, err - } - - return reply, nil -} - -func NewRedisService(rp *redis.Pool) RedisService { - return &redisService{rp: rp} -} - -// Delete delete a kye -func (r *redisService) Delete(key string) (bool, error) { - conn := r.rp.Get() - defer conn.Close() - - return redis.Bool(conn.Do("DEL", key)) -} - -// LikeDeletes batch delete -func (r *redisService) LikeDeletes(key string) error { - conn := r.rp.Get() - defer conn.Close() - - keys, err := redis.Strings(conn.Do("KEYS", "*"+key+"*")) - if err != nil { - return err - } - - for _, key := range keys { - _, err = r.Delete(key) - if err != nil { - return err - } - } - - return nil -} diff --git a/service/service.go b/service/service.go index 82767e4..0e75470 100644 --- a/service/service.go +++ b/service/service.go @@ -40,7 +40,7 @@ func NewService(db *gorm.DB) Repository { return &store{ app: NewAppService(db), - user: NewUserService(), + user: NewUserService(db), docker: NewDockerService(), //redis: NewRedisService(rp), zima: NewZiMaService(), diff --git a/service/user.go b/service/user.go index 95519a4..068af4d 100644 --- a/service/user.go +++ b/service/user.go @@ -1,3 +1,13 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-03-18 11:40:55 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-06-14 14:04:53 + * @FilePath: /CasaOS/service/user.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ package service import ( @@ -6,18 +16,50 @@ import ( "os" "github.com/IceWhaleTech/CasaOS/pkg/config" + "github.com/IceWhaleTech/CasaOS/service/model" + "gorm.io/gorm" ) type UserService interface { SetUser(username, pwd, token, email, desc, nickName string) error UpLoadFile(file multipart.File, name string) error + CreateUser(m model.UserDBModel) model.UserDBModel + GetUserCount() (userCount int64) + UpdateUser(m model.UserDBModel) + GetUserInfoById(id string) (m model.UserDBModel) + GetUserInfoByUserName(userName string) (m model.UserDBModel) } -type user struct { +type userService struct { + db *gorm.DB +} + +func (u *userService) CreateUser(m model.UserDBModel) model.UserDBModel { + u.db.Create(&m) + return m +} + +func (u *userService) GetUserCount() (userCount int64) { + u.db.Find(&model.UserDBModel{}).Count(&userCount) + return +} + +func (u *userService) UpdateUser(m model.UserDBModel) { + u.db.Save(&m) +} + +func (u *userService) GetUserInfoById(id string) (m model.UserDBModel) { + u.db.Where("id= ?", id).First(&m) + return +} + +func (u *userService) GetUserInfoByUserName(userName string) (m model.UserDBModel) { + u.db.Where("user_name= ?", userName).First(&m) + return } //设置用户名密码 -func (c *user) SetUser(username, pwd, token, email, desc, nickName string) error { +func (u *userService) SetUser(username, pwd, token, email, desc, nickName string) error { if len(username) > 0 { config.Cfg.Section("user").Key("UserName").SetValue(username) config.UserInfo.UserName = username @@ -45,7 +87,7 @@ func (c *user) SetUser(username, pwd, token, email, desc, nickName string) error } //上传文件 -func (c *user) UpLoadFile(file multipart.File, url string) error { +func (c *userService) UpLoadFile(file multipart.File, url string) error { out, _ := os.OpenFile(url, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) defer out.Close() io.Copy(out, file) @@ -53,6 +95,6 @@ func (c *user) UpLoadFile(file multipart.File, url string) error { } //获取用户Service -func NewUserService() UserService { - return &user{} +func NewUserService(db *gorm.DB) UserService { + return &userService{db: db} }