作者 陈志颖

Merge branch 'dev' of http://gitlab.fjmaimaimai.com/mmm-go-pp/partner01 into feat/order-domain

merge
@@ -21,9 +21,7 @@ metadata: @@ -21,9 +21,7 @@ metadata:
21 - ref: status 21 - ref: status
22 required: true 22 required: true
23 - ref: adminType 23 - ref: adminType
24 - required: true  
25 - - ref: status  
26 - required: true 24 + required: true
27 - ref: accessPartners 25 - ref: accessPartners
28 required: true 26 required: true
29 - ref: createAt 27 - ref: createAt
@@ -5,6 +5,7 @@ go 1.16 @@ -5,6 +5,7 @@ go 1.16
5 require ( 5 require (
6 github.com/ajg/form v1.5.1 // indirect 6 github.com/ajg/form v1.5.1 // indirect
7 github.com/beego/beego/v2 v2.0.1 7 github.com/beego/beego/v2 v2.0.1
  8 + github.com/dgrijalva/jwt-go v3.2.0+incompatible
8 github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect 9 github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
9 github.com/fatih/structs v1.1.0 // indirect 10 github.com/fatih/structs v1.1.0 // indirect
10 github.com/gavv/httpexpect v2.0.0+incompatible 11 github.com/gavv/httpexpect v2.0.0+incompatible
@@ -44,6 +44,7 @@ github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGii @@ -44,6 +44,7 @@ github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGii
44 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 44 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
45 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 45 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
46 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 46 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
  47 +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
47 github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= 48 github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
48 github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 49 github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
49 github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= 50 github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type AccessTokenCommand struct {
  10 + // Attribute描述
  11 + AuthCode string `json:"authCode,omitempty"`
  12 +}
  13 +
  14 +func (accessTokenCommand *AccessTokenCommand) Valid(validation *validation.Validation) {
  15 +
  16 +}
  17 +
  18 +func (accessTokenCommand *AccessTokenCommand) ValidateCommand() error {
  19 + valid := validation.Validation{}
  20 + b, err := valid.Valid(accessTokenCommand)
  21 + if err != nil {
  22 + return err
  23 + }
  24 + if !b {
  25 + for _, validErr := range valid.Errors {
  26 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  27 + }
  28 + }
  29 + return nil
  30 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type ChangePasswordCommand struct {
  10 + // 旧密码
  11 + OldPwd string `json:"oldPwd,omitempty"`
  12 + // 新密码
  13 + NewPwd string `json:"newPwd,omitempty"`
  14 + // 确认密码
  15 + ConfirmPwd string `json:"confirmPwd,omitempty"`
  16 + // 手机号
  17 + Phone string `json:"phone,omitempty"`
  18 +}
  19 +
  20 +func (changePasswordCommand *ChangePasswordCommand) Valid(validation *validation.Validation) {
  21 +
  22 +}
  23 +
  24 +func (changePasswordCommand *ChangePasswordCommand) ValidateCommand() error {
  25 + valid := validation.Validation{}
  26 + b, err := valid.Valid(changePasswordCommand)
  27 + if err != nil {
  28 + return err
  29 + }
  30 + if !b {
  31 + for _, validErr := range valid.Errors {
  32 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  33 + }
  34 + }
  35 + return nil
  36 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type LoginByCompanyCommand struct {
  10 + // 1.高管 2.合伙人 4:游客
  11 + UserType int `json:"userType" valid:"Required"`
  12 + // 凭证
  13 + Credentials string `json:"credentials" valid:"Required"`
  14 + // 用户id
  15 + UserId int64 `json:"userId" valid:"Required"`
  16 +}
  17 +
  18 +func (loginByCompanyCommand *LoginByCompanyCommand) Valid(validation *validation.Validation) {
  19 +
  20 +}
  21 +
  22 +func (loginByCompanyCommand *LoginByCompanyCommand) ValidateCommand() error {
  23 + valid := validation.Validation{}
  24 + b, err := valid.Valid(loginByCompanyCommand)
  25 + if err != nil {
  26 + return err
  27 + }
  28 + if !b {
  29 + for _, validErr := range valid.Errors {
  30 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  31 + }
  32 + }
  33 + return nil
  34 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type RefreshTokenCommand struct {
  10 + // refreshToken
  11 + RefreshToken string `json:"refreshToken,omitempty"`
  12 +}
  13 +
  14 +func (refreshTokenCommand *RefreshTokenCommand) Valid(validation *validation.Validation) {
  15 +
  16 +}
  17 +
  18 +func (refreshTokenCommand *RefreshTokenCommand) ValidateCommand() error {
  19 + valid := validation.Validation{}
  20 + b, err := valid.Valid(refreshTokenCommand)
  21 + if err != nil {
  22 + return err
  23 + }
  24 + if !b {
  25 + for _, validErr := range valid.Errors {
  26 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  27 + }
  28 + }
  29 + return nil
  30 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type RevokeCommand struct {
  10 +}
  11 +
  12 +func (revokeCommand *RevokeCommand) Valid(validation *validation.Validation) {
  13 + validation.SetError("CustomValid", "未实现的自定义认证")
  14 +}
  15 +
  16 +func (revokeCommand *RevokeCommand) ValidateCommand() error {
  17 + valid := validation.Validation{}
  18 + b, err := valid.Valid(revokeCommand)
  19 + if err != nil {
  20 + return err
  21 + }
  22 + if !b {
  23 + for _, validErr := range valid.Errors {
  24 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  25 + }
  26 + }
  27 + return nil
  28 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type SendSmsCodeCommand struct {
  10 + // 手机号
  11 + Phone string `json:"phone,omitempty"`
  12 +}
  13 +
  14 +func (sendSmsCodeCommand *SendSmsCodeCommand) Valid(validation *validation.Validation) {
  15 + validation.SetError("CustomValid", "未实现的自定义认证")
  16 +}
  17 +
  18 +func (sendSmsCodeCommand *SendSmsCodeCommand) ValidateCommand() error {
  19 + valid := validation.Validation{}
  20 + b, err := valid.Valid(sendSmsCodeCommand)
  21 + if err != nil {
  22 + return err
  23 + }
  24 + if !b {
  25 + for _, validErr := range valid.Errors {
  26 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  27 + }
  28 + }
  29 + return nil
  30 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 +
  6 + "github.com/beego/beego/v2/core/validation"
  7 +)
  8 +
  9 +type LoginQuery struct {
  10 + // 手机号
  11 + Phone string `json:"phone,omitempty"`
  12 + // signInPassword(密码登录) 或 signInCaptcha(验证码登录)或signInCredentials(凭证登录)
  13 + GrantType string `json:"grantType,omitempty"`
  14 + // 密码(grantType = signInPassword)
  15 + Password string `json:"password,omitempty"`
  16 + // 验证码(grantType = signInCaptcha)
  17 + Captcha string `json:"captcha,omitempty"`
  18 + // 凭证(grantType = signInCredentials)
  19 + Credentials string `json:"credentials,omitempty"`
  20 +}
  21 +
  22 +func (loginQuery *LoginQuery) Valid(validation *validation.Validation) {
  23 +
  24 +}
  25 +
  26 +func (loginQuery *LoginQuery) ValidateQuery() error {
  27 + valid := validation.Validation{}
  28 + b, err := valid.Valid(loginQuery)
  29 + if err != nil {
  30 + return err
  31 + }
  32 + if !b {
  33 + for _, validErr := range valid.Errors {
  34 + return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package service
  2 +
  3 +import (
  4 + "github.com/linmadan/egglib-go/core/application"
  5 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/command"
  6 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/query"
  7 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  9 + "math/rand"
  10 + "strconv"
  11 + "strings"
  12 +)
  13 +
  14 +// 认证服务
  15 +type AuthService struct {
  16 +}
  17 +
  18 +// 用户按公司登录
  19 +func (authService *AuthService) AccessToken(accessTokenCommand *command.AccessTokenCommand) (interface{}, error) {
  20 + if err := accessTokenCommand.ValidateCommand(); err != nil {
  21 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  22 + }
  23 + transactionContext, err := factory.CreateTransactionContext(nil)
  24 + if err != nil {
  25 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  26 + }
  27 + if err := transactionContext.StartTransaction(); err != nil {
  28 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  29 + }
  30 + defer func() {
  31 + transactionContext.RollbackTransaction()
  32 + }()
  33 + if err := transactionContext.CommitTransaction(); err != nil {
  34 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  35 + }
  36 + var claim = &domain.UserTokenClaim{}
  37 + var result bool
  38 + if result, err = domain.ValidToken(accessTokenCommand.AuthCode, claim); err != nil || !result {
  39 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  40 + }
  41 + userId := claim.UserId
  42 + companyId := claim.CompanyId
  43 + rspMapData := map[string]interface{}{
  44 + "accessToken": domain.SignToken(int64(userId), companyId),
  45 + "refreshToken": domain.SignToken(int64(userId), companyId),
  46 + }
  47 + return rspMapData, nil
  48 +}
  49 +
  50 +// 修改手机号密码
  51 +func (authService *AuthService) ChangePassword(changePasswordCommand *command.ChangePasswordCommand) (interface{}, error) {
  52 + if err := changePasswordCommand.ValidateCommand(); err != nil {
  53 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  54 + }
  55 + transactionContext, err := factory.CreateTransactionContext(nil)
  56 + if err != nil {
  57 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  58 + }
  59 + if err := transactionContext.StartTransaction(); err != nil {
  60 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  61 + }
  62 + defer func() {
  63 + transactionContext.RollbackTransaction()
  64 + }()
  65 + var (
  66 + userAuth *domain.UserAuth
  67 + )
  68 + UserAuthRepository, _ := factory.CreateUserAuthRepository(map[string]interface{}{"transactionContext": transactionContext})
  69 + userAuth, err = UserAuthRepository.FindOne(map[string]interface{}{"phone": changePasswordCommand.Phone})
  70 + if err != nil {
  71 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  72 + }
  73 + if !strings.EqualFold(userAuth.PhoneAuth.Password, changePasswordCommand.OldPwd) {
  74 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "密码有误!")
  75 + }
  76 + if err = userAuth.Update(map[string]interface{}{"password": changePasswordCommand.NewPwd}); err != nil {
  77 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  78 + }
  79 + if _, err = UserAuthRepository.Save(userAuth); err != nil {
  80 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  81 + }
  82 + if err := transactionContext.CommitTransaction(); err != nil {
  83 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  84 + }
  85 + return nil, nil
  86 +}
  87 +
  88 +// 用户登录 返回有权限的公司列表
  89 +func (authService *AuthService) Login(loginQuery *query.LoginQuery) (interface{}, error) {
  90 + if err := loginQuery.ValidateQuery(); err != nil {
  91 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  92 + }
  93 + transactionContext, err := factory.CreateTransactionContext(nil)
  94 + if err != nil {
  95 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  96 + }
  97 + if err := transactionContext.StartTransaction(); err != nil {
  98 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  99 + }
  100 + defer func() {
  101 + transactionContext.RollbackTransaction()
  102 + }()
  103 +
  104 + var (
  105 + userAuth *domain.UserAuth
  106 + users []*domain.User
  107 + rspMapData = make(map[string]interface{})
  108 + userCompanies []interface{}
  109 + )
  110 + UserAuthRepository, _ := factory.CreateUserAuthRepository(map[string]interface{}{"transactionContext": transactionContext})
  111 + UserRepository, _ := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
  112 + switch loginQuery.GrantType {
  113 + case "signInPassword":
  114 + if len(loginQuery.Password) == 0 {
  115 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "密码不能为空!")
  116 + }
  117 + userAuth, err = UserAuthRepository.FindOne(map[string]interface{}{"phone": loginQuery.Phone})
  118 + if err != nil {
  119 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  120 + }
  121 + if !strings.EqualFold(userAuth.PhoneAuth.Password, loginQuery.Password) {
  122 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "密码有误!")
  123 + }
  124 + case "signInCaptcha":
  125 + case "signInCredentials":
  126 + default:
  127 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "undefined grantType:"+loginQuery.GrantType)
  128 + }
  129 + _, users, err = UserRepository.Find(map[string]interface{}{"inUserIds": userAuth.Users, "status": domain.StatusEnable})
  130 +
  131 + if err := transactionContext.CommitTransaction(); err != nil {
  132 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  133 + }
  134 + credentials := "cred:" + strconv.Itoa(rand.Int())
  135 + rspMapData["credentials"] = credentials
  136 + CompanyRepository, _ := factory.CreateCompanyRepository(map[string]interface{}{"transactionContext": transactionContext})
  137 + for i := range users {
  138 + company, _ := CompanyRepository.FindOne(map[string]interface{}{"companyId": users[i].CompanyId, "status": domain.StatusEnable})
  139 + if company == nil {
  140 + continue
  141 + }
  142 + item := map[string]interface{}{
  143 + "user": users[i],
  144 + "company": company,
  145 + }
  146 + userCompanies = append(userCompanies, item)
  147 + }
  148 + return map[string]interface{}{"userCompanies": userCompanies, "credentials": credentials}, nil
  149 +}
  150 +
  151 +// 用户按公司登录
  152 +func (authService *AuthService) LoginByCompany(loginByCompanyCommand *command.LoginByCompanyCommand) (interface{}, error) {
  153 + if err := loginByCompanyCommand.ValidateCommand(); err != nil {
  154 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  155 + }
  156 + transactionContext, err := factory.CreateTransactionContext(nil)
  157 + if err != nil {
  158 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  159 + }
  160 + if err := transactionContext.StartTransaction(); err != nil {
  161 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  162 + }
  163 + defer func() {
  164 + transactionContext.RollbackTransaction()
  165 + }()
  166 +
  167 + //todo:valid/refresh credentials
  168 + if len(loginByCompanyCommand.Credentials) == 0 {
  169 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "credentials expire")
  170 + }
  171 +
  172 + var user *domain.User
  173 + UserRepository, _ := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
  174 + user, err = UserRepository.FindOne(map[string]interface{}{"userId": loginByCompanyCommand.UserId, "userType": loginByCompanyCommand.UserType})
  175 + if err != nil {
  176 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  177 + }
  178 + CompanyRepository, _ := factory.CreateCompanyRepository(map[string]interface{}{"transactionContext": transactionContext})
  179 + company, err := CompanyRepository.FindOne(map[string]interface{}{"companyId": user.CompanyId, "status": domain.StatusEnable})
  180 + if err != nil {
  181 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  182 + }
  183 + if err := transactionContext.CommitTransaction(); err != nil {
  184 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  185 + }
  186 + authCode := domain.SignToken(user.UserId, company.CompanyId)
  187 + return map[string]interface{}{"user": user, "company": company, "authCode": authCode}, nil
  188 +}
  189 +
  190 +// 更新授权令牌accessToken
  191 +func (authService *AuthService) RefreshToken(refreshTokenCommand *command.RefreshTokenCommand) (interface{}, error) {
  192 + if err := refreshTokenCommand.ValidateCommand(); err != nil {
  193 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  194 + }
  195 + transactionContext, err := factory.CreateTransactionContext(nil)
  196 + if err != nil {
  197 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  198 + }
  199 + if err := transactionContext.StartTransaction(); err != nil {
  200 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  201 + }
  202 + defer func() {
  203 + transactionContext.RollbackTransaction()
  204 + }()
  205 + if err := transactionContext.CommitTransaction(); err != nil {
  206 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  207 + }
  208 + var claim = &domain.UserTokenClaim{}
  209 + var result bool
  210 + if result, err = domain.ValidToken(refreshTokenCommand.RefreshToken, claim); err != nil || !result {
  211 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  212 + }
  213 + userId := claim.UserId
  214 + companyId := claim.CompanyId
  215 + rspMapData := map[string]interface{}{
  216 + "accessToken": domain.SignToken(int64(userId), companyId),
  217 + "refreshToken": domain.SignToken(int64(userId), companyId),
  218 + }
  219 + return rspMapData, nil
  220 +}
  221 +
  222 +// 注销登录
  223 +func (authService *AuthService) Revoke(revokeCommand *command.RevokeCommand) (interface{}, error) {
  224 + if err := revokeCommand.ValidateCommand(); err != nil {
  225 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  226 + }
  227 + transactionContext, err := factory.CreateTransactionContext(nil)
  228 + if err != nil {
  229 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  230 + }
  231 + if err := transactionContext.StartTransaction(); err != nil {
  232 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  233 + }
  234 + defer func() {
  235 + transactionContext.RollbackTransaction()
  236 + }()
  237 + if err := transactionContext.CommitTransaction(); err != nil {
  238 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  239 + }
  240 + return nil, nil
  241 +}
  242 +
  243 +// 发送验证码
  244 +func (authService *AuthService) SendSmsCode(sendSmsCodeCommand *command.SendSmsCodeCommand) (interface{}, error) {
  245 + if err := sendSmsCodeCommand.ValidateCommand(); err != nil {
  246 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  247 + }
  248 + transactionContext, err := factory.CreateTransactionContext(nil)
  249 + if err != nil {
  250 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  251 + }
  252 + if err := transactionContext.StartTransaction(); err != nil {
  253 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  254 + }
  255 + defer func() {
  256 + transactionContext.RollbackTransaction()
  257 + }()
  258 + if err := transactionContext.CommitTransaction(); err != nil {
  259 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  260 + }
  261 + return nil, nil
  262 +}
  263 +
  264 +func NewAuthService(options map[string]interface{}) *AuthService {
  265 + newAuthService := &AuthService{}
  266 + return newAuthService
  267 +}
@@ -45,3 +45,19 @@ func CreateGoodsRepository(options map[string]interface{}) (domain.GoodsReposito @@ -45,3 +45,19 @@ func CreateGoodsRepository(options map[string]interface{}) (domain.GoodsReposito
45 } 45 }
46 return repository.NewGoodsRepository(transactionContext) 46 return repository.NewGoodsRepository(transactionContext)
47 } 47 }
  48 +
  49 +func CreateUserRepository(options map[string]interface{}) (domain.UserRepository, error) {
  50 + var transactionContext *pg.TransactionContext
  51 + if value, ok := options["transactionContext"]; ok {
  52 + transactionContext = value.(*pg.TransactionContext)
  53 + }
  54 + return repository.NewUserRepository(transactionContext)
  55 +}
  56 +
  57 +func CreateCompanyRepository(options map[string]interface{}) (domain.CompanyRepository, error) {
  58 + var transactionContext *pg.TransactionContext
  59 + if value, ok := options["transactionContext"]; ok {
  60 + transactionContext = value.(*pg.TransactionContext)
  61 + }
  62 + return repository.NewCompanyRepository(transactionContext)
  63 +}
  1 +package domain
  2 +
  3 +import (
  4 + "github.com/dgrijalva/jwt-go"
  5 + eggJwt "github.com/linmadan/egglib-go/utils/jwt"
  6 + "time"
  7 +)
  8 +
  9 +const (
  10 + secret = "$^%$Rdefault&*^(*&"
  11 +)
  12 +
  13 +const (
  14 + AccessTokenExpire = 3600
  15 +)
  16 +
  17 +type UserTokenClaim struct {
  18 + jwt.StandardClaims
  19 + UserId int64 `json:"userId"`
  20 + CompanyId int64 `json:"companyId"`
  21 +}
  22 +
  23 +func NewUserTokenClaim(userId, companyId int64, expire int64) UserTokenClaim {
  24 + return UserTokenClaim{
  25 + UserId: userId,
  26 + CompanyId: companyId,
  27 + StandardClaims: jwt.StandardClaims{ExpiresAt: expire},
  28 + }
  29 +}
  30 +
  31 +func SignToken(userId int64, companyId int64) string {
  32 + claim := NewUserTokenClaim(int64(userId), companyId, time.Now().Add(time.Second*AccessTokenExpire).Unix())
  33 + token, _ := eggJwt.Sign(claim, secret, "")
  34 + return token
  35 +}
  36 +
  37 +func ValidToken(token string, claims *UserTokenClaim) (bool, error) {
  38 + result, c, err := eggJwt.Valid(token, claims, secret)
  39 + claims = c.Claims.(*UserTokenClaim)
  40 + return result, err
  41 +}
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 公司信息
  6 +type Company struct {
  7 + // 公司Id
  8 + CompanyId int64 `json:"companyId"`
  9 + // 公司信息
  10 + CompanyInfo *CompanyInfo `json:"companyInfo"`
  11 + // 创建时间
  12 + CreateAt time.Time `json:"createAt"`
  13 + // 更新时间
  14 + UpdateAt time.Time `json:"updateAt"`
  15 + // 删除时间
  16 + DeleteAt time.Time `json:"deleteAt"`
  17 +}
  18 +
  19 +type CompanyRepository interface {
  20 + Save(company *Company) (*Company, error)
  21 + Remove(company *Company) (*Company, error)
  22 + FindOne(queryOptions map[string]interface{}) (*Company, error)
  23 + Find(queryOptions map[string]interface{}) (int64, []*Company, error)
  24 +}
  25 +
  26 +func (company *Company) Identify() interface{} {
  27 + if company.CompanyId == 0 {
  28 + return nil
  29 + }
  30 + return company.CompanyId
  31 +}
  32 +
  33 +func (company *Company) Update(data map[string]interface{}) error {
  34 + if companyId, ok := data["companyId"]; ok {
  35 + company.CompanyId = companyId.(int64)
  36 + }
  37 + if companyId, ok := data["companyId"]; ok {
  38 + company.CompanyInfo.CompanyId = companyId.(int64)
  39 + }
  40 + if name, ok := data["name"]; ok {
  41 + company.CompanyInfo.Name = name.(string)
  42 + }
  43 + if abbreviation, ok := data["abbreviation"]; ok {
  44 + company.CompanyInfo.Abbreviation = abbreviation.(string)
  45 + }
  46 + if logo, ok := data["logo"]; ok {
  47 + company.CompanyInfo.Logo = logo.(string)
  48 + }
  49 + if phone, ok := data["phone"]; ok {
  50 + company.CompanyInfo.Phone = phone.(string)
  51 + }
  52 + if status, ok := data["status"]; ok {
  53 + company.CompanyInfo.Status = status.(int64)
  54 + }
  55 + if remarks, ok := data["remarks"]; ok {
  56 + company.CompanyInfo.Remarks = remarks.(string)
  57 + }
  58 + if enable, ok := data["enable"]; ok {
  59 + company.CompanyInfo.Enable = enable.(int64)
  60 + }
  61 + return nil
  62 +}
  1 +package domain
  2 +
  3 +// 公司信息
  4 +type CompanyInfo struct {
  5 + // 公司Id
  6 + CompanyId int64 `json:"companyId"`
  7 + // 公司名称
  8 + Name string `json:"name"`
  9 + // 公司简称
  10 + Abbreviation string `json:"abbreviation"`
  11 + // 公司logo
  12 + Logo string `json:"logo"`
  13 + // 公司联系电话
  14 + Phone string `json:"phone"`
  15 + // 状态 1正常 2禁用
  16 + Status int64 `json:"status"`
  17 + // 备注
  18 + Remarks string `json:"remarks"`
  19 + // 是否有效【1:有效】【2:无效】
  20 + Enable int64 `json:"enable"`
  21 + // 公司主管理员
  22 + Admin *UserInfo `json:"admin"`
  23 +}
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +const (
  6 + StatusEnable int64 = 1
  7 + StatusDisable int64 = 2
  8 +)
  9 +const (
  10 + SuperAdministrator = 1
  11 + EnterpriseAdministrator = 10
  12 + NormalUser = 100
  13 +)
  14 +
  15 +// UserType
  16 +const (
  17 + Manager = 1
  18 + Partner = 2
  19 + Guest = 3
  20 +)
  21 +
  22 +// 用户实体
  23 +type User struct {
  24 + // 用户id
  25 + UserId int64 `json:"userId"`
  26 + // 1.高管 2.合伙人 4:游客
  27 + UserType int `json:"userType"`
  28 + // 用户权限
  29 + Permissions []int `json:"permissions"`
  30 + // 公司Id
  31 + CompanyId int64 `json:"companyId"`
  32 + // 用户信息
  33 + UserInfo *UserInfo `json:"userInfo"`
  34 + // 合伙人信息
  35 + PartnerInfo *PartnerInfo `json:"partnerInfo"`
  36 + // 状态 1正常 2禁用
  37 + Status int64 `json:"status"`
  38 + // 管理员类型 1.超级管理员 10:企业管理员 100:普通用户
  39 + AdminType int `json:"adminType"`
  40 + // 合伙人列表 用户类型为高管时有效
  41 + AccessPartners []int64 `json:"accessPartners"`
  42 + // 创建时间
  43 + CreateAt time.Time `json:"createAt"`
  44 + // 更新时间
  45 + UpdateAt time.Time `json:"updateAt"`
  46 + // 删除时间
  47 + DeleteAt time.Time `json:"deleteAt"`
  48 +}
  49 +
  50 +type UserRepository interface {
  51 + Save(user *User) (*User, error)
  52 + Remove(user *User) (*User, error)
  53 + FindOne(queryOptions map[string]interface{}) (*User, error)
  54 + Find(queryOptions map[string]interface{}) (int64, []*User, error)
  55 +}
  56 +
  57 +func (user *User) Identify() interface{} {
  58 + if user.UserId == 0 {
  59 + return nil
  60 + }
  61 + return user.UserId
  62 +}
  63 +
  64 +func (user *User) Update(data map[string]interface{}) error {
  65 + if userId, ok := data["userId"]; ok {
  66 + user.UserId = userId.(int64)
  67 + }
  68 + if userType, ok := data["userType"]; ok {
  69 + user.UserType = userType.(int)
  70 + }
  71 + if permissions, ok := data["permissions"]; ok {
  72 + user.Permissions = permissions.([]int)
  73 + }
  74 + if companyId, ok := data["companyId"]; ok {
  75 + user.CompanyId = companyId.(int64)
  76 + }
  77 + if isPrincipal, ok := data["isPrincipal"]; ok {
  78 + user.UserInfo.IsPrincipal = isPrincipal.(bool)
  79 + }
  80 + if uid, ok := data["uid"]; ok {
  81 + user.UserInfo.Uid = uid.(int64)
  82 + }
  83 + if userAccount, ok := data["userAccount"]; ok {
  84 + user.UserInfo.UserAccount = userAccount.(string)
  85 + }
  86 + if userAvatarUrl, ok := data["userAvatarUrl"]; ok {
  87 + user.UserInfo.UserAvatarUrl = userAvatarUrl.(string)
  88 + }
  89 + if userName, ok := data["userName"]; ok {
  90 + user.UserInfo.UserName = userName.(string)
  91 + }
  92 + if email, ok := data["email"]; ok {
  93 + user.UserInfo.Email = email.(string)
  94 + }
  95 + if gender, ok := data["gender"]; ok {
  96 + user.UserInfo.Gender = gender.(int)
  97 + }
  98 + if entryTime, ok := data["entryTime"]; ok {
  99 + user.UserInfo.EntryTime = entryTime.(time.Time)
  100 + }
  101 + if extension, ok := data["extension"]; ok {
  102 + user.UserInfo.Extension = extension.(string)
  103 + }
  104 + if workplace, ok := data["workplace"]; ok {
  105 + user.UserInfo.Workplace = workplace.(string)
  106 + }
  107 + if privateNumber, ok := data["privateNumber"]; ok {
  108 + user.UserInfo.PrivateNumber = privateNumber.(string)
  109 + }
  110 + if jobNumber, ok := data["jobNumber"]; ok {
  111 + user.UserInfo.JobNumber = jobNumber.(string)
  112 + }
  113 + if partnerAccount, ok := data["partnerAccount"]; ok {
  114 + user.PartnerInfo.PartnerAccount = partnerAccount.(string)
  115 + }
  116 + if partnerName, ok := data["partnerName"]; ok {
  117 + user.PartnerInfo.PartnerName = partnerName.(string)
  118 + }
  119 + if regionName, ok := data["regionName"]; ok {
  120 + user.PartnerInfo.RegionInfo.RegionName = regionName.(string)
  121 + }
  122 + if status, ok := data["status"]; ok {
  123 + user.PartnerInfo.Status = status.(int64)
  124 + }
  125 + return nil
  126 +}
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 用户信息值对象
  6 +type UserInfo struct {
  7 + // 是否是公司负责人
  8 + IsPrincipal bool `json:"isPrincipal"`
  9 + // 统一用户id
  10 + Uid int64 `json:"uid"`
  11 + // 用户账号
  12 + UserAccount string `json:"userAccount"`
  13 + // 用户头像URL
  14 + UserAvatarUrl string `json:"userAvatarUrl"`
  15 + // 用户名称
  16 + UserName string `json:"userName"`
  17 + // 邮件地址
  18 + Email string `json:"email"`
  19 + // 性别
  20 + Gender int `json:"gender"`
  21 + // 入职时间
  22 + EntryTime time.Time `json:"entryTime"`
  23 + // 分机
  24 + Extension string `json:"extension"`
  25 + // 工作地
  26 + Workplace string `json:"workplace"`
  27 + // 私人电话
  28 + PrivateNumber string `json:"privateNumber"`
  29 + // 工号
  30 + JobNumber string `json:"jobNumber"`
  31 +}
@@ -29,6 +29,8 @@ func init() { @@ -29,6 +29,8 @@ func init() {
29 &models.UserAuth{}, 29 &models.UserAuth{},
30 &models.Goods{}, 30 &models.Goods{},
31 &models.Order{}, 31 &models.Order{},
  32 + &models.User{},
  33 + &models.Company{},
32 } { 34 } {
33 err := DB.Model(model).CreateTable(&orm.CreateTableOptions{ 35 err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
34 Temp: false, 36 Temp: false,
  1 +package models
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  5 + "time"
  6 +)
  7 +
  8 +type Company struct {
  9 + tableName string `pg:"companys,alias:company"`
  10 + // 公司Id
  11 + CompanyId int64 `pg:",pk"`
  12 + // 公司信息
  13 + CompanyInfo *domain.CompanyInfo
  14 + // 创建时间
  15 + CreateAt time.Time
  16 + // 更新时间
  17 + UpdateAt time.Time
  18 + // 删除时间
  19 + DeleteAt time.Time
  20 +}
  1 +package models
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  5 + "time"
  6 +)
  7 +
  8 +type User struct {
  9 + tableName string `pg:"users,alias:users"`
  10 + // 用户id
  11 + UserId int64 `pg:",pk"`
  12 + // 1.高管 2.合伙人 4:游客
  13 + UserType int
  14 + // 用户权限
  15 + Permissions []int `pg:",array"`
  16 + // 公司Id
  17 + CompanyId int64
  18 + // 用户信息
  19 + UserInfo *domain.UserInfo
  20 + // 合伙人信息
  21 + PartnerInfo *domain.PartnerInfo
  22 + // 状态 1正常 2禁用
  23 + Status int64
  24 + // 管理员类型 1.超级管理员 10:企业管理员 100:普通用户
  25 + AdminType int
  26 + // 合伙人列表 用户类型为高管时有效
  27 + AccessPartners []int64 `pg:",array"`
  28 + // 创建时间
  29 + CreateAt time.Time
  30 + // 更新时间
  31 + UpdateAt time.Time
  32 + // 删除时间
  33 + DeleteAt time.Time
  34 +}
@@ -6,9 +6,9 @@ import ( @@ -6,9 +6,9 @@ import (
6 ) 6 )
7 7
8 type UserAuth struct { 8 type UserAuth struct {
9 - tableName string `pg:"user_auth"` 9 + tableName string `pg:"user_auth,alias:user_auth"`
10 // 用户认证编号 10 // 用户认证编号
11 - UserAuthId int64 11 + UserAuthId int64 `pg:",pk"`
12 // 用户id列表 12 // 用户id列表
13 Users []int64 `pg:",array"` 13 Users []int64 `pg:",array"`
14 // 手机认证 14 // 手机认证
  1 +package transform
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
  6 +)
  7 +
  8 +func TransformToCompanyDomainModelFromPgModels(companyModel *models.Company) (*domain.Company, error) {
  9 + return &domain.Company{
  10 + CompanyId: companyModel.CompanyId,
  11 + CompanyInfo: companyModel.CompanyInfo,
  12 + CreateAt: companyModel.CreateAt,
  13 + UpdateAt: companyModel.UpdateAt,
  14 + DeleteAt: companyModel.DeleteAt,
  15 + }, nil
  16 +}
  1 +package transform
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
  6 +)
  7 +
  8 +func TransformToUserDomainModelFromPgModels(userModel *models.User) (*domain.User, error) {
  9 + return &domain.User{
  10 + UserId: userModel.UserId,
  11 + UserType: userModel.UserType,
  12 + Permissions: userModel.Permissions,
  13 + CompanyId: userModel.CompanyId,
  14 + UserInfo: userModel.UserInfo,
  15 + PartnerInfo: userModel.PartnerInfo,
  16 + Status: userModel.Status,
  17 + AdminType: userModel.AdminType,
  18 + AccessPartners: userModel.AccessPartners,
  19 + CreateAt: userModel.CreateAt,
  20 + UpdateAt: userModel.UpdateAt,
  21 + DeleteAt: userModel.DeleteAt,
  22 + }, nil
  23 +}
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 +
  7 + "github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
  8 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  9 + "github.com/linmadan/egglib-go/utils/snowflake"
  10 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  11 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
  12 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/transform"
  13 +)
  14 +
  15 +type CompanyRepository struct {
  16 + transactionContext *pgTransaction.TransactionContext
  17 +}
  18 +
  19 +func (repository *CompanyRepository) nextIdentify() (int64, error) {
  20 + IdWorker, err := snowflake.NewIdWorker(1)
  21 + if err != nil {
  22 + return 0, err
  23 + }
  24 + id, err := IdWorker.NextId()
  25 + return id, err
  26 +}
  27 +func (repository *CompanyRepository) Save(company *domain.Company) (*domain.Company, error) {
  28 + sqlBuildFields := []string{
  29 + "company_id",
  30 + "company_info",
  31 + "create_at",
  32 + "update_at",
  33 + "delete_at",
  34 + }
  35 + insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
  36 + insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
  37 + returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
  38 + updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "company_id")
  39 + updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
  40 + tx := repository.transactionContext.PgTx
  41 + if company.Identify() == nil {
  42 + companyId, err := repository.nextIdentify()
  43 + if err != nil {
  44 + return company, err
  45 + } else {
  46 + company.CompanyId = companyId
  47 + }
  48 + if _, err := tx.QueryOne(
  49 + pg.Scan(
  50 + &company.CompanyId,
  51 + &company.CompanyInfo,
  52 + &company.CreateAt,
  53 + &company.UpdateAt,
  54 + &company.DeleteAt,
  55 + ),
  56 + fmt.Sprintf("INSERT INTO companys (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
  57 + company.CompanyId,
  58 + company.CompanyInfo,
  59 + company.CreateAt,
  60 + company.UpdateAt,
  61 + company.DeleteAt,
  62 + ); err != nil {
  63 + return company, err
  64 + }
  65 + } else {
  66 + if _, err := tx.QueryOne(
  67 + pg.Scan(
  68 + &company.CompanyId,
  69 + &company.CompanyInfo,
  70 + &company.CreateAt,
  71 + &company.UpdateAt,
  72 + &company.DeleteAt,
  73 + ),
  74 + fmt.Sprintf("UPDATE companys SET %s WHERE company_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
  75 + company.CompanyId,
  76 + company.CompanyInfo,
  77 + company.CreateAt,
  78 + company.UpdateAt,
  79 + company.DeleteAt,
  80 + company.Identify(),
  81 + ); err != nil {
  82 + return company, err
  83 + }
  84 + }
  85 + return company, nil
  86 +}
  87 +func (repository *CompanyRepository) Remove(company *domain.Company) (*domain.Company, error) {
  88 + tx := repository.transactionContext.PgTx
  89 + companyModel := new(models.Company)
  90 + companyModel.CompanyId = company.Identify().(int64)
  91 + if _, err := tx.Model(companyModel).WherePK().Delete(); err != nil {
  92 + return company, err
  93 + }
  94 + return company, nil
  95 +}
  96 +func (repository *CompanyRepository) FindOne(queryOptions map[string]interface{}) (*domain.Company, error) {
  97 + tx := repository.transactionContext.PgTx
  98 + companyModel := new(models.Company)
  99 + query := sqlbuilder.BuildQuery(tx.Model(companyModel), queryOptions)
  100 + query.SetWhereByQueryOption("company.company_id = ?", "companyId")
  101 + query.SetWhereByQueryOption(`company.company_info @>'{"status":?}'`, "status")
  102 + if err := query.First(); err != nil {
  103 + if err.Error() == "pg: no rows in result set" {
  104 + return nil, fmt.Errorf("没有此资源")
  105 + } else {
  106 + return nil, err
  107 + }
  108 + }
  109 + if companyModel.CompanyId == 0 {
  110 + return nil, nil
  111 + } else {
  112 + return transform.TransformToCompanyDomainModelFromPgModels(companyModel)
  113 + }
  114 +}
  115 +func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Company, error) {
  116 + tx := repository.transactionContext.PgTx
  117 + var companyModels []*models.Company
  118 + companys := make([]*domain.Company, 0)
  119 + query := sqlbuilder.BuildQuery(tx.Model(&companyModels), queryOptions)
  120 + query.SetOffsetAndLimit(20)
  121 + query.SetOrderDirect("company_id", "DESC")
  122 + if count, err := query.SelectAndCount(); err != nil {
  123 + return 0, companys, err
  124 + } else {
  125 + for _, companyModel := range companyModels {
  126 + if company, err := transform.TransformToCompanyDomainModelFromPgModels(companyModel); err != nil {
  127 + return 0, companys, err
  128 + } else {
  129 + companys = append(companys, company)
  130 + }
  131 + }
  132 + return int64(count), companys, nil
  133 + }
  134 +}
  135 +func NewCompanyRepository(transactionContext *pgTransaction.TransactionContext) (*CompanyRepository, error) {
  136 + if transactionContext == nil {
  137 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  138 + } else {
  139 + return &CompanyRepository{
  140 + transactionContext: transactionContext,
  141 + }, nil
  142 + }
  143 +}
@@ -53,7 +53,7 @@ func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.U @@ -53,7 +53,7 @@ func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.U
53 &userAuth.CreateAt, 53 &userAuth.CreateAt,
54 &userAuth.UpdateAt, 54 &userAuth.UpdateAt,
55 ), 55 ),
56 - fmt.Sprintf("INSERT INTO user_auths (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet), 56 + fmt.Sprintf("INSERT INTO user_auth (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
57 userAuth.UserAuthId, 57 userAuth.UserAuthId,
58 pg.Array(userAuth.Users), 58 pg.Array(userAuth.Users),
59 userAuth.PhoneAuth, 59 userAuth.PhoneAuth,
@@ -71,7 +71,7 @@ func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.U @@ -71,7 +71,7 @@ func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.U
71 &userAuth.CreateAt, 71 &userAuth.CreateAt,
72 &userAuth.UpdateAt, 72 &userAuth.UpdateAt,
73 ), 73 ),
74 - fmt.Sprintf("UPDATE user_auths SET %s WHERE user_auth_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet), 74 + fmt.Sprintf("UPDATE user_auth SET %s WHERE user_auth_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
75 userAuth.UserAuthId, 75 userAuth.UserAuthId,
76 pg.Array(userAuth.Users), 76 pg.Array(userAuth.Users),
77 userAuth.PhoneAuth, 77 userAuth.PhoneAuth,
@@ -98,6 +98,9 @@ func (repository *UserAuthRepository) FindOne(queryOptions map[string]interface{ @@ -98,6 +98,9 @@ func (repository *UserAuthRepository) FindOne(queryOptions map[string]interface{
98 userAuthModel := new(models.UserAuth) 98 userAuthModel := new(models.UserAuth)
99 query := sqlbuilder.BuildQuery(tx.Model(userAuthModel), queryOptions) 99 query := sqlbuilder.BuildQuery(tx.Model(userAuthModel), queryOptions)
100 query.SetWhereByQueryOption("user_auth.user_auth_id = ?", "userAuthId") 100 query.SetWhereByQueryOption("user_auth.user_auth_id = ?", "userAuthId")
  101 + if v, ok := queryOptions["phone"]; ok {
  102 + query.Where(fmt.Sprintf(`user_auth.phone_auth @>'{"phone":"%v"}'`, v))
  103 + }
101 if err := query.First(); err != nil { 104 if err := query.First(); err != nil {
102 if err.Error() == "pg: no rows in result set" { 105 if err.Error() == "pg: no rows in result set" {
103 return nil, fmt.Errorf("没有此资源") 106 return nil, fmt.Errorf("没有此资源")
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 +
  7 + "github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
  8 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  9 + "github.com/linmadan/egglib-go/utils/snowflake"
  10 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  11 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
  12 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/transform"
  13 +)
  14 +
  15 +type UserRepository struct {
  16 + transactionContext *pgTransaction.TransactionContext
  17 +}
  18 +
  19 +func (repository *UserRepository) nextIdentify() (int64, error) {
  20 + IdWorker, err := snowflake.NewIdWorker(1)
  21 + if err != nil {
  22 + return 0, err
  23 + }
  24 + id, err := IdWorker.NextId()
  25 + return id, err
  26 +}
  27 +func (repository *UserRepository) Save(user *domain.User) (*domain.User, error) {
  28 + sqlBuildFields := []string{
  29 + "user_id",
  30 + "user_type",
  31 + "permissions",
  32 + "company_id",
  33 + "user_info",
  34 + "partner_info",
  35 + "status",
  36 + "admin_type",
  37 + "access_partners",
  38 + "create_at",
  39 + "update_at",
  40 + "delete_at",
  41 + }
  42 + insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
  43 + insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
  44 + returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
  45 + updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id")
  46 + updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
  47 + tx := repository.transactionContext.PgTx
  48 + if user.Identify() == nil {
  49 + userId, err := repository.nextIdentify()
  50 + if err != nil {
  51 + return user, err
  52 + } else {
  53 + user.UserId = userId
  54 + }
  55 + if _, err := tx.QueryOne(
  56 + pg.Scan(
  57 + &user.UserId,
  58 + &user.UserType,
  59 + pg.Array(&user.Permissions),
  60 + &user.CompanyId,
  61 + &user.UserInfo,
  62 + &user.PartnerInfo,
  63 + &user.Status,
  64 + &user.AdminType,
  65 + pg.Array(&user.AccessPartners),
  66 + &user.CreateAt,
  67 + &user.UpdateAt,
  68 + &user.DeleteAt,
  69 + ),
  70 + fmt.Sprintf("INSERT INTO users (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
  71 + user.UserId,
  72 + user.UserType,
  73 + pg.Array(user.Permissions),
  74 + user.CompanyId,
  75 + user.UserInfo,
  76 + user.PartnerInfo,
  77 + user.Status,
  78 + user.AdminType,
  79 + pg.Array(user.AccessPartners),
  80 + user.CreateAt,
  81 + user.UpdateAt,
  82 + user.DeleteAt,
  83 + ); err != nil {
  84 + return user, err
  85 + }
  86 + } else {
  87 + if _, err := tx.QueryOne(
  88 + pg.Scan(
  89 + &user.UserId,
  90 + &user.UserType,
  91 + pg.Array(&user.Permissions),
  92 + &user.CompanyId,
  93 + &user.UserInfo,
  94 + &user.PartnerInfo,
  95 + &user.Status,
  96 + &user.AdminType,
  97 + pg.Array(&user.AccessPartners),
  98 + &user.CreateAt,
  99 + &user.UpdateAt,
  100 + &user.DeleteAt,
  101 + ),
  102 + fmt.Sprintf("UPDATE users SET %s WHERE user_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
  103 + user.UserId,
  104 + user.UserType,
  105 + pg.Array(user.Permissions),
  106 + user.CompanyId,
  107 + user.UserInfo,
  108 + user.PartnerInfo,
  109 + user.Status,
  110 + user.AdminType,
  111 + pg.Array(user.AccessPartners),
  112 + user.CreateAt,
  113 + user.UpdateAt,
  114 + user.DeleteAt,
  115 + user.Identify(),
  116 + ); err != nil {
  117 + return user, err
  118 + }
  119 + }
  120 + return user, nil
  121 +}
  122 +func (repository *UserRepository) Remove(user *domain.User) (*domain.User, error) {
  123 + tx := repository.transactionContext.PgTx
  124 + userModel := new(models.User)
  125 + userModel.UserId = user.Identify().(int64)
  126 + if _, err := tx.Model(userModel).WherePK().Delete(); err != nil {
  127 + return user, err
  128 + }
  129 + return user, nil
  130 +}
  131 +func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
  132 + tx := repository.transactionContext.PgTx
  133 + userModel := new(models.User)
  134 + query := sqlbuilder.BuildQuery(tx.Model(userModel), queryOptions)
  135 + query.SetWhereByQueryOption("users.user_id = ?", "userId")
  136 + query.SetWhereByQueryOption("users.status = ?", "status")
  137 + query.SetWhereByQueryOption("users.user_type = ?", "userType")
  138 + if v, ok := queryOptions["inUserIds"]; ok {
  139 + query.Where("users.user_id in (?)", pg.Array(v))
  140 + }
  141 + if err := query.First(); err != nil {
  142 + if err.Error() == "pg: no rows in result set" {
  143 + return nil, fmt.Errorf("没有此资源")
  144 + } else {
  145 + return nil, err
  146 + }
  147 + }
  148 + if userModel.UserId == 0 {
  149 + return nil, nil
  150 + } else {
  151 + return transform.TransformToUserDomainModelFromPgModels(userModel)
  152 + }
  153 +}
  154 +func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
  155 + tx := repository.transactionContext.PgTx
  156 + var userModels []*models.User
  157 + users := make([]*domain.User, 0)
  158 + query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
  159 + query.SetOffsetAndLimit(20)
  160 + query.SetOrderDirect("user_id", "DESC")
  161 + if count, err := query.SelectAndCount(); err != nil {
  162 + return 0, users, err
  163 + } else {
  164 + for _, userModel := range userModels {
  165 + if user, err := transform.TransformToUserDomainModelFromPgModels(userModel); err != nil {
  166 + return 0, users, err
  167 + } else {
  168 + users = append(users, user)
  169 + }
  170 + }
  171 + return int64(count), users, nil
  172 + }
  173 +}
  174 +func NewUserRepository(transactionContext *pgTransaction.TransactionContext) (*UserRepository, error) {
  175 + if transactionContext == nil {
  176 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  177 + } else {
  178 + return &UserRepository{
  179 + transactionContext: transactionContext,
  180 + }, nil
  181 + }
  182 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "github.com/linmadan/egglib-go/web/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/command"
  6 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/query"
  7 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/service"
  8 +)
  9 +
  10 +type AuthController struct {
  11 + beego.BaseController
  12 +}
  13 +
  14 +func (controller *AuthController) Login() {
  15 + authService := service.NewAuthService(nil)
  16 + loginQuery := &query.LoginQuery{}
  17 + controller.Unmarshal(loginQuery)
  18 + data, err := authService.Login(loginQuery)
  19 + controller.Response(data, err)
  20 +}
  21 +
  22 +func (controller *AuthController) LoginByCompany() {
  23 + authService := service.NewAuthService(nil)
  24 + loginByCompanyCommand := &command.LoginByCompanyCommand{}
  25 + controller.Unmarshal(loginByCompanyCommand)
  26 + data, err := authService.LoginByCompany(loginByCompanyCommand)
  27 + controller.Response(data, err)
  28 +}
  29 +
  30 +func (controller *AuthController) AccessToken() {
  31 + authService := service.NewAuthService(nil)
  32 + accessTokenCommand := &command.AccessTokenCommand{}
  33 + controller.Unmarshal(accessTokenCommand)
  34 + data, err := authService.AccessToken(accessTokenCommand)
  35 + controller.Response(data, err)
  36 +}
  37 +
  38 +func (controller *AuthController) RefreshToken() {
  39 + authService := service.NewAuthService(nil)
  40 + refreshTokenCommand := &command.RefreshTokenCommand{}
  41 + controller.Unmarshal(refreshTokenCommand)
  42 + data, err := authService.RefreshToken(refreshTokenCommand)
  43 + controller.Response(data, err)
  44 +}
  45 +
  46 +func (controller *AuthController) SendSmsCode() {
  47 + authService := service.NewAuthService(nil)
  48 + sendSmsCodeCommand := &command.SendSmsCodeCommand{}
  49 + controller.Unmarshal(sendSmsCodeCommand)
  50 + data, err := authService.SendSmsCode(sendSmsCodeCommand)
  51 + controller.Response(data, err)
  52 +}
  53 +
  54 +func (controller *AuthController) Revoke() {
  55 + authService := service.NewAuthService(nil)
  56 + revokeCommand := &command.RevokeCommand{}
  57 + controller.Unmarshal(revokeCommand)
  58 + data, err := authService.Revoke(revokeCommand)
  59 + controller.Response(data, err)
  60 +}
  61 +
  62 +func (controller *AuthController) ChangePassword() {
  63 + authService := service.NewAuthService(nil)
  64 + changePasswordCommand := &command.ChangePasswordCommand{}
  65 + controller.Unmarshal(changePasswordCommand)
  66 + data, err := authService.ChangePassword(changePasswordCommand)
  67 + controller.Response(data, err)
  68 +}
  1 +package routers
  2 +
  3 +import (
  4 + "github.com/beego/beego/v2/server/web"
  5 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/port/beego/controllers"
  6 +)
  7 +
  8 +func init() {
  9 + web.Router("/auths/login", &controllers.AuthController{}, "Post:Login")
  10 + web.Router("/auths/loginByCompany", &controllers.AuthController{}, "Post:LoginByCompany")
  11 + web.Router("/auths/accessToken", &controllers.AuthController{}, "Post:AccessToken")
  12 + web.Router("/auths/refreshToken", &controllers.AuthController{}, "Post:RefreshToken")
  13 + web.Router("/auths/sendSmsCode", &controllers.AuthController{}, "Post:SendSmsCode")
  14 + web.Router("/auths/revoke", &controllers.AuthController{}, "Post:Revoke")
  15 + web.Router("/auths/changePhonePassword", &controllers.AuthController{}, "Post:ChangePassword")
  16 +}
  1 +package auth
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 +)
  10 +
  11 +var _ = Describe("用户按公司登录", func() {
  12 + //var Id int64
  13 + //return
  14 + BeforeEach(func() {
  15 + //_, err := pG.DB.QueryOne(
  16 + // pg.Scan(&Id),
  17 + // "INSERT INTO s () VALUES () RETURNING _id",
  18 + //)
  19 + //Expect(err).NotTo(HaveOccurred())
  20 + })
  21 + Describe("用户按公司登录", func() {
  22 + Context("", func() {
  23 + It("", func() {
  24 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  25 + body := map[string]interface{}{
  26 + "authCode": domain.SignToken(1, 1000),
  27 + }
  28 + httpExpect.POST("/auths/accessToken").
  29 + WithJSON(body).
  30 + Expect().
  31 + Status(http.StatusOK).
  32 + JSON().
  33 + Object().
  34 + ContainsKey("code").ValueEqual("code", 0).
  35 + ContainsKey("msg").ValueEqual("msg", "ok").
  36 + ContainsKey("data").Value("data").Object()
  37 + })
  38 + })
  39 + })
  40 + AfterEach(func() {
  41 + //_, err := pG.DB.Exec("DELETE FROM s WHERE true")
  42 + //Expect(err).NotTo(HaveOccurred())
  43 + })
  44 +})
  1 +package auth
  2 +
  3 +import (
  4 + "net/http"
  5 + "net/http/httptest"
  6 + "testing"
  7 +
  8 + "github.com/beego/beego/v2/server/web"
  9 + . "github.com/onsi/ginkgo"
  10 + . "github.com/onsi/gomega"
  11 + _ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
  12 + _ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/port/beego"
  13 +)
  14 +
  15 +func TestAuth(t *testing.T) {
  16 + RegisterFailHandler(Fail)
  17 + RunSpecs(t, "Beego Port Auth Correlations Test Case Suite")
  18 +}
  19 +
  20 +var handler http.Handler
  21 +var server *httptest.Server
  22 +
  23 +var _ = BeforeSuite(func() {
  24 + handler = web.BeeApp.Handlers
  25 + server = httptest.NewServer(handler)
  26 +})
  27 +
  28 +var _ = AfterSuite(func() {
  29 + server.Close()
  30 +})
  1 +package auth
  2 +
  3 +import (
  4 + "github.com/go-pg/pg/v10"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("修改手机号密码", func() {
  14 + var Id int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&Id),
  18 + `INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
  19 + )
  20 + Expect(err).NotTo(HaveOccurred())
  21 + })
  22 + Describe("修改手机号密码", func() {
  23 + Context("", func() {
  24 + It("", func() {
  25 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  26 + body := map[string]interface{}{
  27 + "oldPwd": "password",
  28 + "newPwd": "newPassword",
  29 + "confirmPwd": "newPassword",
  30 + "phone": "18800000001",
  31 + }
  32 + httpExpect.POST("/auths/changePhonePassword").
  33 + WithJSON(body).
  34 + Expect().
  35 + Status(http.StatusOK).
  36 + JSON().
  37 + Object().
  38 + ContainsKey("code").ValueEqual("code", 0).
  39 + ContainsKey("msg").ValueEqual("msg", "ok")
  40 + //ContainsKey("data").Value("data").Object()
  41 + })
  42 + })
  43 + })
  44 + AfterEach(func() {
  45 + _, err := pG.DB.Exec("DELETE FROM user_auth WHERE true")
  46 + Expect(err).NotTo(HaveOccurred())
  47 + })
  48 +})
  1 +package auth
  2 +
  3 +import (
  4 + "github.com/go-pg/pg/v10"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("用户按公司登录", func() {
  14 + var Id int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&Id),
  18 + "INSERT INTO users (user_id,user_type,company_id) VALUES (1,1,1000) RETURNING user_id",
  19 + )
  20 + _, err = pG.DB.QueryOne(
  21 + pg.Scan(&Id),
  22 + `INSERT INTO companys (company_id,company_info) VALUES (1000,'{"company_id":1000,"name":"company","status":1}') RETURNING company_id`,
  23 + )
  24 + _, err = pG.DB.QueryOne(
  25 + pg.Scan(&Id),
  26 + `INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
  27 + )
  28 + Expect(err).NotTo(HaveOccurred())
  29 + })
  30 + Describe("用户按公司登录", func() {
  31 + Context("", func() {
  32 + It("", func() {
  33 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  34 + body := map[string]interface{}{
  35 + "userType": 1,
  36 + "credentials": "string",
  37 + "userId": 1,
  38 + }
  39 + httpExpect.POST("/auths/loginByCompany").
  40 + WithJSON(body).
  41 + Expect().
  42 + Status(http.StatusOK).
  43 + JSON().
  44 + Object().
  45 + ContainsKey("code").ValueEqual("code", 0).
  46 + ContainsKey("msg").ValueEqual("msg", "ok").
  47 + ContainsKey("data").Value("data").Object()
  48 + })
  49 + })
  50 + })
  51 + AfterEach(func() {
  52 + _, err := pG.DB.Exec("DELETE FROM users WHERE true")
  53 + _, err = pG.DB.Exec("DELETE FROM companys WHERE true")
  54 + _, err = pG.DB.Exec("DELETE FROM user_auth WHERE true")
  55 + Expect(err).NotTo(HaveOccurred())
  56 + })
  57 +})
  1 +package auth
  2 +
  3 +import (
  4 + "github.com/go-pg/pg/v10"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("用户登录 返回有权限的公司列表", func() {
  14 + var Id int64
  15 + BeforeEach(func() {
  16 + _, err := pG.DB.QueryOne(
  17 + pg.Scan(&Id),
  18 + "INSERT INTO users (user_id,user_type,company_id) VALUES (1,1,1000) RETURNING user_id",
  19 + )
  20 + _, err = pG.DB.QueryOne(
  21 + pg.Scan(&Id),
  22 + `INSERT INTO companys (company_id,company_info) VALUES (1000,'{"company_id":1000,"name":"company"}') RETURNING company_id`,
  23 + )
  24 + _, err = pG.DB.QueryOne(
  25 + pg.Scan(&Id),
  26 + `INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
  27 + )
  28 + Expect(err).NotTo(HaveOccurred())
  29 + })
  30 + Describe("用户登录 返回有权限的公司列表", func() {
  31 + Context("", func() {
  32 + It("", func() {
  33 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  34 + body := map[string]interface{}{
  35 + "phone": "18800000001",
  36 + "grantType": "signInPassword",
  37 + "password": "password",
  38 + "captcha": "",
  39 + "credentials": "",
  40 + }
  41 + httpExpect.POST("/auths/login").
  42 + WithJSON(body).
  43 + Expect().
  44 + Status(http.StatusOK).
  45 + JSON().
  46 + Object().
  47 + ContainsKey("code").ValueEqual("code", 0).
  48 + ContainsKey("msg").ValueEqual("msg", "ok").
  49 + ContainsKey("data").Value("data").Object()
  50 + })
  51 + })
  52 + })
  53 + AfterEach(func() {
  54 + _, err := pG.DB.Exec("DELETE FROM users WHERE true")
  55 + _, err = pG.DB.Exec("DELETE FROM companys WHERE true")
  56 + _, err = pG.DB.Exec("DELETE FROM user_auth WHERE true")
  57 + Expect(err).NotTo(HaveOccurred())
  58 + })
  59 +})
  1 +package auth
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 +)
  10 +
  11 +var _ = Describe("更新授权令牌accessToken", func() {
  12 + //return
  13 + //var Id int64
  14 + BeforeEach(func() {
  15 + //_, err := pG.DB.QueryOne(
  16 + // pg.Scan(&Id),
  17 + // "INSERT INTO s () VALUES () RETURNING _id",
  18 + //)
  19 + //Expect(err).NotTo(HaveOccurred())
  20 + })
  21 + Describe("更新授权令牌accessToken", func() {
  22 + Context("", func() {
  23 + It("", func() {
  24 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  25 + body := map[string]interface{}{
  26 + "refreshToken": domain.SignToken(1, 1000),
  27 + }
  28 + httpExpect.POST("/auths/refreshToken").
  29 + WithJSON(body).
  30 + Expect().
  31 + Status(http.StatusOK).
  32 + JSON().
  33 + Object().
  34 + ContainsKey("code").ValueEqual("code", 0).
  35 + ContainsKey("msg").ValueEqual("msg", "ok").
  36 + ContainsKey("data").Value("data").Object()
  37 + })
  38 + })
  39 + })
  40 + AfterEach(func() {
  41 + //_, err := pG.DB.Exec("DELETE FROM s WHERE true")
  42 + //Expect(err).NotTo(HaveOccurred())
  43 + })
  44 +})
  1 +package auth
  2 +
  3 +import (
  4 + "github.com/go-pg/pg/v10"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("注销登录", func() {
  14 + return
  15 + var Id int64
  16 + BeforeEach(func() {
  17 + _, err := pG.DB.QueryOne(
  18 + pg.Scan(&Id),
  19 + "INSERT INTO s () VALUES () RETURNING _id",
  20 + )
  21 + Expect(err).NotTo(HaveOccurred())
  22 + })
  23 + Describe("注销登录", func() {
  24 + Context("", func() {
  25 + It("", func() {
  26 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  27 + body := map[string]interface{}{}
  28 + httpExpect.POST("/auths/revoke").
  29 + WithJSON(body).
  30 + Expect().
  31 + Status(http.StatusOK).
  32 + JSON().
  33 + Object().
  34 + ContainsKey("code").ValueEqual("code", 0).
  35 + ContainsKey("msg").ValueEqual("msg", "ok").
  36 + ContainsKey("data").Value("data").Object()
  37 + })
  38 + })
  39 + })
  40 + AfterEach(func() {
  41 + _, err := pG.DB.Exec("DELETE FROM s WHERE true")
  42 + Expect(err).NotTo(HaveOccurred())
  43 + })
  44 +})
  1 +package auth
  2 +
  3 +import (
  4 + "github.com/go-pg/pg/v10"
  5 + "net/http"
  6 +
  7 + "github.com/gavv/httpexpect"
  8 + . "github.com/onsi/ginkgo"
  9 + . "github.com/onsi/gomega"
  10 + pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
  11 +)
  12 +
  13 +var _ = Describe("发送验证码", func() {
  14 + return
  15 + var Id int64
  16 + BeforeEach(func() {
  17 + _, err := pG.DB.QueryOne(
  18 + pg.Scan(&Id),
  19 + "INSERT INTO s () VALUES () RETURNING _id",
  20 + )
  21 + Expect(err).NotTo(HaveOccurred())
  22 + })
  23 + Describe("发送验证码", func() {
  24 + Context("", func() {
  25 + It("", func() {
  26 + httpExpect := httpexpect.New(GinkgoT(), server.URL)
  27 + body := map[string]interface{}{
  28 + "phone": "string",
  29 + }
  30 + httpExpect.POST("/auths/sendSmsCode").
  31 + WithJSON(body).
  32 + Expect().
  33 + Status(http.StatusOK).
  34 + JSON().
  35 + Object().
  36 + ContainsKey("code").ValueEqual("code", 0).
  37 + ContainsKey("msg").ValueEqual("msg", "ok").
  38 + ContainsKey("data").Value("data").Object()
  39 + })
  40 + })
  41 + })
  42 + AfterEach(func() {
  43 + _, err := pG.DB.Exec("DELETE FROM s WHERE true")
  44 + Expect(err).NotTo(HaveOccurred())
  45 + })
  46 +})