create.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package user
  4. import (
  5. "context"
  6. "cp-system-management/consts"
  7. "cp-system-management/errors"
  8. dbmodel "cp-system-management/model"
  9. pb_v1 "cp-system-management/pb/v1"
  10. "crypto/sha256"
  11. "encoding/json"
  12. "fmt"
  13. "github.com/jaryhe/gopkgs/util"
  14. "github.com/jaryhe/gopkgs/database"
  15. "github.com/jaryhe/gopkgs/logger"
  16. "go.uber.org/zap"
  17. "google.golang.org/grpc/status"
  18. )
  19. // 创建用户
  20. func CreateUser(ctx context.Context, req *pb_v1.CreateUserRequest) (reply *pb_v1.CreateUserReply, err error) {
  21. reply = &pb_v1.CreateUserReply{}
  22. // 捕获各个task中的异常并返回给调用者
  23. defer func() {
  24. if r := recover(); r != nil {
  25. err = fmt.Errorf("%+v", r)
  26. e := &status.Status{}
  27. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  28. logger.Error("err",
  29. zap.String("system_err", err.Error()),
  30. zap.Stack("stacktrace"))
  31. }
  32. }
  33. }()
  34. if req.Username == "" || req.Password == "" {
  35. return reply, errors.ParamsError
  36. }
  37. db := database.DB()
  38. p := &dbmodel.SystemUser{}
  39. where := map[string]interface{}{"username": req.Username}
  40. err = p.Find(db, where)
  41. if err == nil {
  42. return reply, errors.UserExist
  43. }
  44. passwd, _ := util.GetMd5Pass(req.Password, consts.CRYPTO_KEY)
  45. p.Username = req.Username
  46. p.Password = passwd
  47. err = p.Insert(db)
  48. if err != nil {
  49. return reply, errors.DataBaseError
  50. }
  51. reply.Uid = p.Id
  52. return reply, nil
  53. }
  54. func InitUser() {
  55. p := &dbmodel.SystemUser{}
  56. count, err := p.Count(database.DB(), nil, nil)
  57. if err != nil {
  58. panic(err.Error())
  59. return
  60. }
  61. if count > 0 {
  62. return
  63. }
  64. password := fmt.Sprintf("%x", sha256.Sum256([]byte("123456")))
  65. req := pb_v1.CreateUserRequest{
  66. Username:"admin",
  67. Password: password,
  68. }
  69. _, err = CreateUser(context.Background(), &req)
  70. if err != nil {
  71. panic(err.Error())
  72. }
  73. }