12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package user
- import (
- "context"
- "cp-system-management/consts"
- "cp-system-management/errors"
- dbmodel "cp-system-management/model"
- pb_v1 "cp-system-management/pb/v1"
- "crypto/sha256"
- "encoding/json"
- "fmt"
- "github.com/jaryhe/gopkgs/util"
- "github.com/jaryhe/gopkgs/database"
- "github.com/jaryhe/gopkgs/logger"
- "go.uber.org/zap"
- "google.golang.org/grpc/status"
- )
- // 创建用户
- func CreateUser(ctx context.Context, req *pb_v1.CreateUserRequest) (reply *pb_v1.CreateUserReply, err error) {
- reply = &pb_v1.CreateUserReply{}
- // 捕获各个task中的异常并返回给调用者
- defer func() {
- if r := recover(); r != nil {
- err = fmt.Errorf("%+v", r)
- e := &status.Status{}
- if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
- logger.Error("err",
- zap.String("system_err", err.Error()),
- zap.Stack("stacktrace"))
- }
- }
- }()
- if req.Username == "" || req.Password == "" {
- return reply, errors.ParamsError
- }
- db := database.DB()
- p := &dbmodel.SystemUser{}
- where := map[string]interface{}{"username": req.Username}
- err = p.Find(db, where)
- if err == nil {
- return reply, errors.UserExist
- }
- passwd, _ := util.GetMd5Pass(req.Password, consts.CRYPTO_KEY)
- p.Username = req.Username
- p.Password = passwd
- err = p.Insert(db)
- if err != nil {
- return reply, errors.DataBaseError
- }
- reply.Uid = p.Id
- return reply, nil
- }
- func InitUser() {
- p := &dbmodel.SystemUser{}
- count, err := p.Count(database.DB(), nil, nil)
- if err != nil {
- panic(err.Error())
- return
- }
- if count > 0 {
- return
- }
- password := fmt.Sprintf("%x", sha256.Sum256([]byte("123456")))
- req := pb_v1.CreateUserRequest{
- Username:"admin",
- Password: password,
- }
- _, err = CreateUser(context.Background(), &req)
- if err != nil {
- panic(err.Error())
- }
- }
|