update disk user authentication method

This commit is contained in:
a624669980@163.com 2022-09-06 10:44:24 +08:00
parent 402a734132
commit be3f418f9a
14 changed files with 155 additions and 335 deletions

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-24 17:36:00
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-31 17:20:26
* @LastEditTime: 2022-09-05 11:24:27
* @FilePath: /CasaOS/cmd/migration-tool/migration-034-035.go
* @Description:
* @Website: https://www.casaos.io
@ -11,6 +11,10 @@
package main
import (
"io"
"io/ioutil"
"os"
"path"
"strings"
interfaces "github.com/IceWhaleTech/CasaOS-Common"
@ -76,6 +80,95 @@ func (u *migrationTool) Migrate() error {
service.MyService.App().ImportApplications(true)
src := "/casaOS/server/conf/conf.ini"
if file.Exists(src) {
dst := "/etc/casaos/casaos.conf"
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
}
if file.Exists("/casaOS/server/db") {
var fds []os.FileInfo
var err error
to := "/var/lib/casaos/db"
file.IsNotExistMkDir(to)
from := "/casaOS/server/db"
if fds, err = ioutil.ReadDir(from); err != nil {
return err
}
for _, fd := range fds {
srcfp := path.Join(from, fd.Name())
dstfp := path.Join(to, fd.Name())
source, err := os.Open(srcfp)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dstfp)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
}
}
if file.Exists("/casaOS/server/conf") {
var fds []os.FileInfo
var err error
to := "/var/lib/casaos/conf"
file.IsNotExistMkDir(to)
from := "/casaOS/server/conf"
if fds, err = ioutil.ReadDir(from); err != nil {
return err
}
for _, fd := range fds {
fExt := path.Ext(fd.Name())
if fExt != ".json" {
continue
}
srcfp := path.Join(from, fd.Name())
dstfp := path.Join(to, fd.Name())
source, err := os.Open(srcfp)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dstfp)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
}
}
_logger.Info("update done")
return nil
}

5
go.mod
View File

@ -4,8 +4,8 @@ go 1.16
require (
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220830042034-a4df79c84ce6
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha4
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220901034123-ca130f6b5ce9
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6
github.com/Microsoft/go-winio v0.5.0 // indirect
github.com/ambelovsky/go-structs v1.1.0 // indirect
github.com/ambelovsky/gosf v0.0.0-20201109201340-237aea4d6109
@ -20,7 +20,6 @@ require (
github.com/gin-contrib/gzip v0.0.6
github.com/gin-gonic/gin v1.8.1
github.com/go-ini/ini v1.62.0
github.com/golang-jwt/jwt/v4 v4.4.2
github.com/golang/mock v1.6.0
github.com/gomodule/redigo v1.8.5
github.com/google/go-github/v36 v36.0.0

11
go.sum
View File

@ -83,10 +83,10 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d h1:62lEBImTxZ83pgzywgDNIrPPuQ+j4ep9QjqrWBn1hrU=
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d/go.mod h1:lW9x+yEjqKdPbE3+cf2fGPJXCw/hChX3Omi9QHTLFsQ=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220830042034-a4df79c84ce6 h1:ICitt/XvD1oh3BTdQbzV95G48TFY/aiZr55iA8dMD8M=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220830042034-a4df79c84ce6/go.mod h1:5sqNKg5cEH7IUnCklLSTrVoGx1dMBhm9DFDsCYVPvPQ=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha4 h1:fSlA5kNBS/Q4D6bFWiNZTwUfsYQ5F/78vJLvUoowXao=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha4/go.mod h1:8E5T8HJn2OUXz+KBZRD84CzwhBdCWsIBuQChZJ7XDwE=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220901034123-ca130f6b5ce9 h1:q4I/lSsCooxdd6LxinGy90y0n6V8EcaPBV1JCfpEnV4=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220901034123-ca130f6b5ce9/go.mod h1:2MiivEMzvh41codhEKUcn46WK3Ffesop/04qa9jsvQk=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6 h1:2tQQo85+jzbbjqIsKKn77QlAA73bc7vZsVCFvWnK4mg=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6/go.mod h1:hnZwGUzcOyiufMpVO7l3gu2gAm6Ws4TY4Nlj3kMshXA=
github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw=
@ -1678,8 +1678,9 @@ gorm.io/gorm v1.22.5/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0=
gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8=
gotest.tools/v3 v3.3.0 h1:MfDY1b1/0xN1CyMlQDac0ziEy9zJQd9CXBRRDHw2jJo=
gotest.tools/v3 v3.3.0/go.mod h1:Mcr9QNxkg0uMvy/YElmo4SpXgJKWgQvYrT7Kw5RzJ1A=
grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-18 14:32:16
* @LastEditTime: 2022-09-02 22:12:34
* @FilePath: /CasaOS/model/sys_common.go
* @Description:
* @Website: https://www.casaos.io
@ -17,20 +17,6 @@ type SysInfoModel struct {
Name string //系统名称
}
//用户相关
type UserModel struct {
UserName string
PWD string
Token string
Head string
Email string
Description string
Initialized bool
Avatar string
NickName string
Public string
}
//服务配置
type ServerModel struct {
HttpPort string

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong
* @LastEditTime: 2022-09-01 22:05:32
* @LastEditTime: 2022-09-05 11:58:02
* @FilePath: /CasaOS/pkg/config/init.go
* @Description:
* @Website: https://www.casaos.io
@ -26,9 +26,6 @@ import (
//系统配置
var SysInfo = &model.SysInfoModel{}
//用户相关
var UserInfo = &model.UserModel{}
//用户相关
var AppInfo = &model.APPModel{}
@ -63,12 +60,13 @@ func InitSetup(config string) {
if err != nil {
Cfg, err = ini.Load("/etc/casaos.conf")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
Cfg, err = ini.Load("/casaOS/server/conf/conf.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
}
}
mapTo("user", UserInfo)
mapTo("app", AppInfo)
//mapTo("redis", RedisInfo)
mapTo("server", ServerInfo)

View File

@ -1,63 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2021-09-30 18:18:14
* @LastEditors: LinkLeong
* @LastEditTime: 2022-07-18 17:30:38
* @FilePath: /CasaOS/pkg/utils/jwt/jwt.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package jwt
import (
"time"
jwt "github.com/golang-jwt/jwt/v4"
)
type Claims struct {
Username string `json:"username"`
PassWord string `json:"password"`
Id int `json:"id"`
jwt.RegisteredClaims
}
var jwtSecret []byte
//创建token
func GenerateToken(username, password string, id int, issuer string, t time.Duration) (string, error) {
clims := Claims{
username,
password,
id,
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(t)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: issuer,
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, clims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
//解析token
func ParseToken(token string, valid bool) (*Claims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if tokenClaims != nil {
if clims, ok := tokenClaims.Claims.(*Claims); ok {
if valid && tokenClaims.Valid {
return clims, nil
} else if !valid {
return clims, nil
}
}
}
return nil, err
}

View File

@ -1,75 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-06-17 14:01:25
* @LastEditors: LinkLeong
* @LastEditTime: 2022-07-29 16:22:25
* @FilePath: /CasaOS/pkg/utils/jwt/jwt_helper.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package jwt
import (
"fmt"
"strconv"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/gin-gonic/gin"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var code int
code = common_err.SUCCESS
token := c.GetHeader("Authorization")
if len(token) == 0 {
token = c.Query("token")
}
if token == "" {
code = common_err.INVALID_PARAMS
}
claims, err := ParseToken(token, false)
//_, err := ParseToken(token)
if err != nil {
code = common_err.ERROR_AUTH_TOKEN
} else if (c.Request.URL.Path == "/v1/file" || c.Request.URL.Path == "/v1/image" || c.Request.URL.Path == "/v1/file/upload" || c.Request.URL.Path == "/v1/batch") && claims.VerifyIssuer("casaos", true) {
//Special treatment
} else if !claims.VerifyExpiresAt(time.Now(), true) || !claims.VerifyIssuer("casaos", true) {
code = common_err.ERROR_AUTH_TOKEN
}
if code != common_err.SUCCESS {
c.JSON(code, model.Result{Success: code, Message: common_err.GetMsg(code)})
c.Abort()
return
}
c.Request.Header.Add("user_id", strconv.Itoa(claims.Id))
c.Next()
}
}
//get AccessToken
func GetAccessToken(username, pwd string, id int) string {
token, err := GenerateToken(username, pwd, id, "casaos", 3*time.Hour*time.Duration(1))
if err == nil {
return token
} else {
loger2.Error(fmt.Sprintf("Get Token Fail: %V", err))
return ""
}
}
func GetRefreshToken(username, pwd string, id int) string {
token, err := GenerateToken(username, pwd, id, "refresh", 7*24*time.Hour*time.Duration(1))
if err == nil {
return token
} else {
loger2.Error(fmt.Sprintf("Get Token Fail: %V", err))
return ""
}
}

View File

@ -5,7 +5,7 @@
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-12 14:22:28
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-31 16:02:31
* @LastEditTime: 2022-09-05 16:27:55
* @FilePath: /CasaOS/route/darwin.go
* @Description:
* @Website: https://www.casaos.io
@ -14,12 +14,12 @@
package route
// func MonitoryUSB() {
func MonitoryUSB() {
// }
// func SendAllHardwareStatusBySocket() {
}
func SendAllHardwareStatusBySocket() {
// }
// func SendUSBBySocket() {
}
func SendUSBBySocket() {
// }
}

View File

@ -1,8 +1,11 @@
//go:build !darwin
// +build !darwin
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-07-01 15:11:36
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-31 17:20:54
* @LastEditTime: 2022-09-05 16:28:46
* @FilePath: /CasaOS/route/periodical.go
* @Description:
* @Website: https://www.casaos.io

View File

@ -14,6 +14,8 @@ import (
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
"github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/gin-gonic/gin"
@ -229,7 +231,6 @@ func GetDisksUSBList(c *gin.Context) {
}
func DeleteDisksUmount(c *gin.Context) {
id := c.GetHeader("user_id")
js := make(map[string]string)
c.ShouldBind(&js)
@ -240,12 +241,17 @@ func DeleteDisksUmount(c *gin.Context) {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
return
}
user := service.MyService.User().GetUserAllInfoById(id)
if user.Id == 0 {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
token := c.GetHeader("Authorization")
if len(token) == 0 {
token = c.Query("token")
}
claims, err := jwt.ParseToken(token, true)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}
if encryption.GetMD5ByStr(pwd) != user.Password {
if encryption.GetMD5ByStr(pwd) != claims.Password {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}
@ -471,19 +477,23 @@ func PostDiskAddPartition(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /disk/format [post]
func PostDiskFormat(c *gin.Context) {
id := c.GetHeader("user_id")
js := make(map[string]string)
c.ShouldBind(&js)
path := js["path"]
t := "ext4"
pwd := js["password"]
volume := js["volume"]
user := service.MyService.User().GetUserAllInfoById(id)
if user.Id == 0 {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
token := c.GetHeader("Authorization")
if len(token) == 0 {
token = c.Query("token")
}
claims, err := jwt.ParseToken(token, true)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}
if encryption.GetMD5ByStr(pwd) != user.Password {
if encryption.GetMD5ByStr(pwd) != claims.Password {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}
@ -521,7 +531,6 @@ func PostDiskFormat(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /disk/umount [post]
func PostDiskUmount(c *gin.Context) {
id := c.GetHeader("user_id")
js := make(map[string]string)
c.ShouldBind(&js)
@ -533,12 +542,17 @@ func PostDiskUmount(c *gin.Context) {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
return
}
user := service.MyService.User().GetUserAllInfoById(id)
if user.Id == 0 {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
token := c.GetHeader("Authorization")
if len(token) == 0 {
token = c.Query("token")
}
claims, err := jwt.ParseToken(token, true)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}
if encryption.GetMD5ByStr(pwd) != user.Password {
if encryption.GetMD5ByStr(pwd) != claims.Password {
c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}

View File

@ -144,7 +144,7 @@ func (o *casaService) AsyncGetServerList() (collection model.ServerAppListCollec
listModel := []model.ServerAppList{}
communityModel := []model.ServerAppList{}
recommendModel := []model.ServerAppList{}
json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &listModel)
err = json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &listModel)
json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommendModel)
json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &communityModel)

View File

@ -1,31 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong
* @LastEditTime: 2022-07-11 17:57:00
* @FilePath: /CasaOS/service/model/o_user.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package model
import "time"
//Soon to be removed
type UserDBModel struct {
Id int `gorm:"column:id;primary_key" json:"id"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
Role string `json:"role"`
Email string `json:"email"`
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
Description string `json:"description"`
CreatedAt time.Time `gorm:"<-:create;autoCreateTime" json:"created_at,omitempty"`
UpdatedAt time.Time `gorm:"<-:create;<-:update;autoUpdateTime" json:"updated_at,omitempty"`
}
func (p *UserDBModel) TableName() string {
return "o_users"
}

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-07-12 09:48:56
* @LastEditors: LinkLeong
* @LastEditTime: 2022-09-02 10:57:12
* @LastEditTime: 2022-09-02 22:10:05
* @FilePath: /CasaOS/service/service.go
* @Description:
* @Website: https://www.casaos.io
@ -47,9 +47,8 @@ func NewService(db *gorm.DB, RuntimePath string) Repository {
}
return &store{
gateway: gatewayManagement,
app: NewAppService(db),
//user: NewUserService(db),
gateway: gatewayManagement,
app: NewAppService(db),
docker: NewDockerService(),
casa: NewCasaService(),
disk: NewDiskService(db),
@ -62,9 +61,8 @@ func NewService(db *gorm.DB, RuntimePath string) Repository {
}
type store struct {
db *gorm.DB
app AppService
//user UserService
db *gorm.DB
app AppService
docker DockerService
casa CasaService
disk DiskService
@ -102,10 +100,6 @@ func (c *store) App() AppService {
return c.app
}
// func (c *store) User() UserService {
// return c.user
// }
func (c *store) Docker() DockerService {
return c.docker
}

View File

@ -1,99 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-03-18 11:40:55
* @LastEditors: LinkLeong
* @LastEditTime: 2022-07-12 10:05:37
* @FilePath: /CasaOS/service/user.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package service
import (
"io"
"mime/multipart"
"os"
"github.com/IceWhaleTech/CasaOS/service/model"
"gorm.io/gorm"
)
type UserService interface {
UpLoadFile(file multipart.File, name string) error
CreateUser(m model.UserDBModel) model.UserDBModel
GetUserCount() (userCount int64)
UpdateUser(m model.UserDBModel)
UpdateUserPassword(m model.UserDBModel)
GetUserInfoById(id string) (m model.UserDBModel)
GetUserAllInfoById(id string) (m model.UserDBModel)
GetUserAllInfoByName(userName string) (m model.UserDBModel)
DeleteUserById(id string)
DeleteAllUser()
GetUserInfoByUserName(userName string) (m model.UserDBModel)
GetAllUserName() (list []model.UserDBModel)
}
var UserRegisterHash = make(map[string]string)
type userService struct {
db *gorm.DB
}
func (u *userService) DeleteAllUser() {
u.db.Where("1=1").Delete(&model.UserDBModel{})
}
func (u *userService) DeleteUserById(id string) {
u.db.Where("id= ?", id).Delete(&model.UserDBModel{})
}
func (u *userService) GetAllUserName() (list []model.UserDBModel) {
u.db.Select("username").Find(&list)
return
}
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.Model(&m).Omit("password").Updates(&m)
}
func (u *userService) UpdateUserPassword(m model.UserDBModel) {
u.db.Model(&m).Update("password", m.Password)
}
func (u *userService) GetUserAllInfoById(id string) (m model.UserDBModel) {
u.db.Where("id= ?", id).First(&m)
return
}
func (u *userService) GetUserAllInfoByName(userName string) (m model.UserDBModel) {
u.db.Where("username= ?", userName).First(&m)
return
}
func (u *userService) GetUserInfoById(id string) (m model.UserDBModel) {
u.db.Select("username", "id", "role", "nickname", "description", "avatar", "email").Where("id= ?", id).First(&m)
return
}
func (u *userService) GetUserInfoByUserName(userName string) (m model.UserDBModel) {
u.db.Select("username", "id", "role", "nickname", "description", "avatar", "email").Where("username= ?", userName).First(&m)
return
}
//上传文件
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)
return nil
}
//获取用户Service
func NewUserService(db *gorm.DB) UserService {
return &userService{db: db}
}