switch branches

This commit is contained in:
a624669980@163.com 2022-06-14 15:18:20 +08:00
parent 3f53e6f33b
commit 8aab7e6053
10 changed files with 137 additions and 168 deletions

View File

@ -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 package sqlite
import ( import (
"fmt"
"time" "time"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
model2 "github.com/IceWhaleTech/CasaOS/service/model" model2 "github.com/IceWhaleTech/CasaOS/service/model"
"go.uber.org/zap"
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -16,7 +27,7 @@ func GetDb(dbPath string) *gorm.DB {
if gdb != nil { if gdb != nil {
return gdb 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) //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{}) //db, err := gorm.Open(mysql2.Open(dsn), &gorm.Config{})
file.IsNotExistMkDir(dbPath) file.IsNotExistMkDir(dbPath)
@ -26,14 +37,14 @@ func GetDb(dbPath string) *gorm.DB {
c.SetMaxOpenConns(100) c.SetMaxOpenConns(100)
c.SetConnMaxIdleTime(time.Second * 1000) c.SetConnMaxIdleTime(time.Second * 1000)
if err != nil { if err != nil {
fmt.Println("连接数据失败!") loger.Error("sqlite connect error", zap.Any("db connect error", err))
panic("数据库连接失败") panic("sqlite connect error")
return nil return nil
} }
gdb = db 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 { if err != nil {
fmt.Println("检查和创建数据库出错", err) loger.Error("check or create db error", zap.Any("error", err))
} }
return db return db
} }

View File

@ -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))
}

View File

@ -13,6 +13,7 @@ import (
"github.com/IceWhaleTech/CasaOS/model/system_app" "github.com/IceWhaleTech/CasaOS/model/system_app"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command" "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/env_helper"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/port" "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
@ -31,6 +32,7 @@ func InitFunction() {
ChangeAPIUrl() ChangeAPIUrl()
InitSystemApplication() InitSystemApplication()
MoveUserToDB()
} }
var syncIsExistence = false var syncIsExistence = false
@ -213,11 +215,7 @@ func CheckToken2_11() {
config.AppInfo.RootPath = "/casaOS" config.AppInfo.RootPath = "/casaOS"
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) 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 sysType := runtime.GOOS
if len(config.FileSettingInfo.DownloadDir) == 0 { if len(config.FileSettingInfo.DownloadDir) == 0 {
downloadPath := "/DATA/Downloads" downloadPath := "/DATA/Downloads"
@ -294,3 +292,19 @@ func InitSystemApplication() {
service.MyService.App().CreateApplication(application) 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)
}
}

View File

@ -64,9 +64,8 @@ func InitRouter() *gin.Engine {
v1UserGroup.POST("/person/info", v1.PostUserPersonInfo) v1UserGroup.POST("/person/info", v1.PostUserPersonInfo)
v1UserGroup.GET("/shareid", v1.GetUserShareID) v1UserGroup.GET("/shareid", v1.GetUserShareID)
// v1UserGroup.GET("/custom/:name") v1UserGroup.GET("/custom/:name")
// v1UserGroup.POST("/custom/:name") v1UserGroup.POST("/custom/:name")
} }
v1AppGroup := v1Group.Group("/app") v1AppGroup := v1Group.Group("/app")
v1AppGroup.Use() v1AppGroup.Use()
@ -119,10 +118,10 @@ func InitRouter() *gin.Engine {
v1SysGroup.POST("/update", v1.SystemUpdate) v1SysGroup.POST("/update", v1.SystemUpdate)
v1SysGroup.GET("/wsssh", v1.WsSsh) v1SysGroup.GET("/wsssh", v1.WsSsh)
v1SysGroup.GET("/config", v1.GetSystemConfig) v1SysGroup.GET("/config", v1.GetSystemConfig)
//v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs) v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs)
v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/widget/config", v1.GetWidgetConfig) v1SysGroup.GET("/widget/config", v1.GetWidgetConfig)
v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig) //v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)
v1SysGroup.GET("/port", v1.GetCasaOSPort) v1SysGroup.GET("/port", v1.GetCasaOSPort)
v1SysGroup.PUT("/port", v1.PutCasaOSPort) v1SysGroup.PUT("/port", v1.PutCasaOSPort)
v1SysGroup.POST("/stop", v1.PostKillCasaOS) v1SysGroup.POST("/stop", v1.PostKillCasaOS)

View File

@ -13,18 +13,10 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
var user_service service.UserService // @Summary set username and password
func init() {
user_service = service.NewUserService()
}
// @Summary 设置用户名和密码
// @Produce application/json // @Produce application/json
// @Accept multipart/form-data // @Accept multipart/form-data
// @Tags user // @Tags user
// @Param username formData string true "User name"
// @Param pwd formData string true "password"
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/setusernamepwd [post] // @Router /user/setusernamepwd [post]

View File

@ -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}
}

26
service/model/o_user.go Normal file
View File

@ -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"
}

View File

@ -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
}

View File

@ -40,7 +40,7 @@ func NewService(db *gorm.DB) Repository {
return &store{ return &store{
app: NewAppService(db), app: NewAppService(db),
user: NewUserService(), user: NewUserService(db),
docker: NewDockerService(), docker: NewDockerService(),
//redis: NewRedisService(rp), //redis: NewRedisService(rp),
zima: NewZiMaService(), zima: NewZiMaService(),

View File

@ -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 package service
import ( import (
@ -6,18 +16,50 @@ import (
"os" "os"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/service/model"
"gorm.io/gorm"
) )
type UserService interface { type UserService interface {
SetUser(username, pwd, token, email, desc, nickName string) error SetUser(username, pwd, token, email, desc, nickName string) error
UpLoadFile(file multipart.File, name 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 { if len(username) > 0 {
config.Cfg.Section("user").Key("UserName").SetValue(username) config.Cfg.Section("user").Key("UserName").SetValue(username)
config.UserInfo.UserName = 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) out, _ := os.OpenFile(url, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
defer out.Close() defer out.Close()
io.Copy(out, file) io.Copy(out, file)
@ -53,6 +95,6 @@ func (c *user) UpLoadFile(file multipart.File, url string) error {
} }
//获取用户Service //获取用户Service
func NewUserService() UserService { func NewUserService(db *gorm.DB) UserService {
return &user{} return &userService{db: db}
} }