Skip to content

Commit dc5a80d

Browse files
committed
feat:user
1 parent c2b2fa3 commit dc5a80d

22 files changed

Lines changed: 719 additions & 35 deletions

File tree

common/global/broadcast.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,8 @@ import (
1010
)
1111

1212
const (
13-
BroadcastRoleUser = "user"
14-
BroadcastRoleMerchant = "merchant"
15-
BroadcastRoleBranch = "branch"
16-
BroadcastRoleDriver = "driver"
17-
BroadcastRoleFreshBranch = "fresh_branch"
13+
BroadcastRoleUser = "user"
14+
BroadcastRoleMerchant = "merchant"
1815
)
1916

2017
/*

common/result/httpResult.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package result
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"github.com/pkg/errors"
7+
"github.com/sirupsen/logrus"
8+
"github.com/tespkg/bytes-be/common/xerr"
9+
10+
"net/http"
11+
)
12+
13+
func HttpResult(w http.ResponseWriter, resp interface{}, err error) {
14+
if err == nil {
15+
WriteJson(w, http.StatusOK, Success(resp))
16+
} else {
17+
errCode := xerr.ServerCommonError
18+
errMsg := "The server is out of service, try again later"
19+
20+
httpCode := http.StatusInternalServerError
21+
22+
causeErr := errors.Cause(err)
23+
if e, ok := causeErr.(*xerr.CodeError); ok {
24+
errCode = e.GetErrCode()
25+
errMsg = e.GetErrMsg()
26+
27+
httpCode = http.StatusOK
28+
}
29+
30+
if e, ok := causeErr.(*xerr.HttpError); ok {
31+
httpCode = e.GetHttpCode()
32+
errMsg = e.GetErrMsg()
33+
}
34+
35+
//WriteJson(w, http.StatusBadRequest, Error(errCode, errMsg))
36+
WriteJson(w, httpCode, Error(errCode, errMsg))
37+
}
38+
}
39+
40+
func ParamErrorResult(w http.ResponseWriter, err error) {
41+
errMsg := fmt.Sprintf("%s ,%s", xerr.MapErrMsg(xerr.RequestParamError), err.Error())
42+
WriteJson(w, http.StatusBadRequest, Error(xerr.RequestParamError, errMsg))
43+
}
44+
45+
// WriteJson writes v as json string into w with code.
46+
func WriteJson(w http.ResponseWriter, code int, v interface{}) {
47+
bs, err := json.Marshal(v)
48+
if err != nil {
49+
http.Error(w, err.Error(), http.StatusInternalServerError)
50+
return
51+
}
52+
53+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
54+
w.WriteHeader(code)
55+
56+
if n, err := w.Write(bs); err != nil {
57+
// http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
58+
// so it's ignored here.
59+
if !errors.Is(err, http.ErrHandlerTimeout) {
60+
logrus.Errorf("write response failed, error: %s", err)
61+
}
62+
} else if n < len(bs) {
63+
logrus.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
64+
}
65+
}
66+
67+
// Ok writes HTTP 200 OK into w.
68+
func Ok(w http.ResponseWriter) {
69+
w.WriteHeader(http.StatusOK)
70+
}
71+
72+
// OkJson writes v into w with 200 OK.
73+
func OkJson(w http.ResponseWriter, v interface{}) {
74+
WriteJson(w, http.StatusOK, v)
75+
}

common/result/responseBean.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package result
2+
3+
type ResponseSuccessBean[T any] struct {
4+
Code uint32 `json:"code"`
5+
Msg string `json:"msg"`
6+
Data T `json:"data"`
7+
}
8+
type NullJson struct{}
9+
10+
func Success[T any](data T) *ResponseSuccessBean[T] {
11+
return &ResponseSuccessBean[T]{0, "OK", data}
12+
}
13+
14+
type ResponseErrorBean struct {
15+
Code uint32 `json:"code"`
16+
Msg string `json:"msg"`
17+
}
18+
19+
func Error(errCode uint32, errMsg string) *ResponseErrorBean {
20+
return &ResponseErrorBean{errCode, errMsg}
21+
}

common/token/token.go

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package token
33
import (
44
"context"
55
"github.com/golang-jwt/jwt/v4"
6+
"github.com/google/uuid"
67
"github.com/pkg/errors"
78
"github.com/tespkg/bytes-be/common/global"
89
"gorm.io/gorm"
@@ -31,7 +32,7 @@ func GenClaims(dto *GenTokenDto) UserClaims {
3132
IssuedAt: jwt.NewNumericDate(time.Now()),
3233
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * time.Duration(defaultTokenExpireDuration))),
3334
Issuer: Issuer,
34-
ID: dto.UserId,
35+
ID: uuid.NewString(),
3536
Subject: dto.UserId,
3637
},
3738
Platform: dto.Platform,
@@ -77,21 +78,21 @@ func GenToken(dto *GenTokenDto) (string, error) {
7778
return signedToken, nil
7879
}
7980

80-
var TokenFormatError = errors.New("token format error")
81-
var TokenInvalidError = errors.New("invalid token")
82-
var TokenExpiredError = errors.New("expired token")
83-
var TokenUnknownError = errors.New("unknown token error")
84-
var TokenClaimsError = errors.New("token claims error")
85-
var TokenSignatureInvalidError = errors.New("token invalid signature error")
81+
var FormatError = errors.New("token format error")
82+
var InvalidError = errors.New("invalid token")
83+
var ExpiredError = errors.New("expired token")
84+
var UnknownError = errors.New("unknown token error")
85+
var ClaimsError = errors.New("token claims error")
86+
var SignatureInvalidError = errors.New("token invalid signature error")
8687

8788
func VerifyToken(ctx context.Context, session *gorm.DB, tokenString string) (context.Context, error) {
8889
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
8990
if claims, ok := token.Claims.(*UserClaims); !ok {
90-
return nil, TokenClaimsError
91+
return nil, ClaimsError
9192
} else {
9293
secret, err := GetUserSecret(&GenTokenDto{
9394
Session: session,
94-
UserId: claims.ID,
95+
UserId: claims.Subject,
9596
Platform: "",
9697
Imei: "",
9798
ClientVersion: "",
@@ -103,44 +104,30 @@ func VerifyToken(ctx context.Context, session *gorm.DB, tokenString string) (con
103104
}
104105
return []byte(secret), nil
105106
}
106-
107-
//if third.GlobalClients.EnableSingleLogin {
108-
// if claims, ok := token.Claims.(*WalletClaims); !ok {
109-
// return nil, TokenClaimsError
110-
// } else {
111-
// secret, err := GetUserSecret(session, claims.ID)
112-
// if err != nil {
113-
// return nil, err
114-
// }
115-
// return []byte(secret), nil
116-
// }
117-
//}
118-
//
119-
//return []byte(jwtSecret), nil
120107
})
121108
if err != nil {
122109
if errors.Is(err, jwt.ErrTokenMalformed) {
123-
return ctx, TokenFormatError
110+
return ctx, FormatError
124111
} else if errors.Is(err, jwt.ErrTokenExpired) {
125-
return ctx, TokenExpiredError
112+
return ctx, ExpiredError
126113
} else if errors.Is(err, jwt.ErrTokenNotValidYet) {
127-
return ctx, TokenExpiredError
114+
return ctx, ExpiredError
128115
} else if errors.Is(err, jwt.ErrTokenSignatureInvalid) {
129-
return ctx, TokenSignatureInvalidError
116+
return ctx, SignatureInvalidError
130117
} else {
131-
return ctx, TokenUnknownError
118+
return ctx, UnknownError
132119
}
133120
}
134121

135122
if !token.Valid {
136-
return ctx, TokenInvalidError
123+
return ctx, InvalidError
137124
}
138125

139126
if claims, ok := token.Claims.(*UserClaims); ok {
140127
// fmt.Printf("claims %+v\n", claims)
141128
ctx = context.WithValue(ctx, ClaimsCtx, claims)
142129
return ctx, nil
143130
} else {
144-
return ctx, TokenClaimsError
131+
return ctx, ClaimsError
145132
}
146133
}

common/xerr/errCode.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package xerr
2+
3+
const OK uint32 = 200
4+
5+
// ServerCommonError global error code
6+
const ServerCommonError uint32 = 100001
7+
const RequestParamError uint32 = 100002
8+
const TokenExpireError uint32 = 100003
9+
const TokenGenerateError uint32 = 100004
10+
const DbError uint32 = 100005
11+
12+
const DeliveryTimeOutOperatingHours uint32 = 40
13+
14+
const (
15+
UserNotExist = 100006
16+
UserPasswordInvalid = 100007
17+
TraveICAuthTokenError = 100008
18+
OrderNotExist = 100009
19+
TicketNotExist = 100010
20+
AccountSettingNotExist = 100011
21+
EmailRegistered = 100012
22+
ThirdPartyLoginFail = 100013
23+
)

common/xerr/errMsg.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package xerr
2+
3+
var message map[uint32]string
4+
5+
func init() {
6+
message = make(map[uint32]string)
7+
message[OK] = "SUCCESS"
8+
message[ServerCommonError] = "The server is out of service, try again later"
9+
message[RequestParamError] = "Parameter error"
10+
message[TokenExpireError] = "The token is invalid, please log in again"
11+
message[TokenGenerateError] = "Failed to generate token"
12+
}
13+
14+
func MapErrMsg(errcode uint32) string {
15+
if msg, ok := message[errcode]; ok {
16+
return msg
17+
} else {
18+
return "服务器开小差啦,稍后再来试一试"
19+
}
20+
}
21+
22+
func IsCodeErr(errcode uint32) bool {
23+
if _, ok := message[errcode]; ok {
24+
return true
25+
} else {
26+
return false
27+
}
28+
}

common/xerr/errors.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package xerr
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
type CodeError struct {
8+
errCode uint32
9+
errMsg string
10+
}
11+
12+
// GetErrCode Failed to generate token
13+
func (e *CodeError) GetErrCode() uint32 {
14+
return e.errCode
15+
}
16+
17+
// GetErrMsg Returns the error message to the front-end display
18+
func (e *CodeError) GetErrMsg() string {
19+
return e.errMsg
20+
}
21+
22+
func (e *CodeError) Error() string {
23+
return fmt.Sprintf("ErrCode:%d,ErrMsg:%s", e.errCode, e.errMsg)
24+
}
25+
26+
func NewErrCodeMsg(errCode uint32, errMsg string) *CodeError {
27+
return &CodeError{errCode: errCode, errMsg: errMsg}
28+
}
29+
func NewErrCode(errCode uint32) *CodeError {
30+
return &CodeError{errCode: errCode, errMsg: MapErrMsg(errCode)}
31+
}
32+
33+
func NewErrMsg(errMsg string) *CodeError {
34+
return &CodeError{errCode: ServerCommonError, errMsg: errMsg}
35+
}

common/xerr/httpErrors.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package xerr
2+
3+
import "fmt"
4+
5+
type HttpError struct {
6+
httpCode int
7+
errMsg string
8+
}
9+
10+
func (h *HttpError) GetHttpCode() int {
11+
return h.httpCode
12+
}
13+
14+
func (h *HttpError) GetErrMsg() string {
15+
return h.errMsg
16+
}
17+
18+
func (h *HttpError) Error() string {
19+
return fmt.Sprintf("HttpCode:%d,ErrMsg:%s", h.httpCode, h.errMsg)
20+
}
21+
22+
func NewHttpError(httpCode int, errMsg string) *HttpError {
23+
return &HttpError{
24+
httpCode: httpCode,
25+
errMsg: errMsg,
26+
}
27+
}

go.mod

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ require (
2020
github.com/sirupsen/logrus v1.9.2
2121
github.com/spf13/cast v1.10.0
2222
github.com/spf13/cobra v1.10.2
23+
github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14
24+
github.com/swaggo/gin-swagger v1.3.0
2325
github.com/tespkg/clickpay v0.1.4
2426
github.com/tespkg/smartpay v0.1.14
2527
github.com/tidwall/gjson v1.18.0
@@ -32,6 +34,8 @@ require (
3234
)
3335

3436
require (
37+
github.com/PuerkitoBio/purell v1.1.0 // indirect
38+
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
3539
github.com/andybalholm/brotli v1.1.0 // indirect
3640
github.com/bytedance/sonic v1.9.1 // indirect
3741
github.com/cespare/xxhash/v2 v2.3.0 // indirect
@@ -42,6 +46,10 @@ require (
4246
github.com/fsnotify/fsnotify v1.5.4 // indirect
4347
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
4448
github.com/gin-contrib/sse v0.1.0 // indirect
49+
github.com/go-openapi/jsonpointer v0.17.0 // indirect
50+
github.com/go-openapi/jsonreference v0.19.0 // indirect
51+
github.com/go-openapi/spec v0.19.0 // indirect
52+
github.com/go-openapi/swag v0.17.0 // indirect
4553
github.com/go-playground/locales v0.14.1 // indirect
4654
github.com/go-playground/universal-translator v0.18.1 // indirect
4755
github.com/go-playground/validator/v10 v10.14.0 // indirect
@@ -70,6 +78,7 @@ require (
7078
github.com/leodido/go-urn v1.2.4 // indirect
7179
github.com/lib/pq v1.10.9 // indirect
7280
github.com/lithammer/shortuuid v3.0.0+incompatible // indirect
81+
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 // indirect
7382
github.com/mattn/go-isatty v0.0.19 // indirect
7483
github.com/mitchellh/copystructure v1.2.0 // indirect
7584
github.com/mitchellh/mapstructure v1.5.0 // indirect
@@ -84,6 +93,7 @@ require (
8493
github.com/refraction-networking/utls v1.6.7 // indirect
8594
github.com/rs/cors v1.11.0 // indirect
8695
github.com/spf13/pflag v1.0.9 // indirect
96+
github.com/swaggo/swag v1.5.1 // indirect
8797
github.com/tidwall/match v1.1.1 // indirect
8898
github.com/tidwall/pretty v1.2.0 // indirect
8999
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
@@ -103,5 +113,6 @@ require (
103113
golang.org/x/tools v0.24.0 // indirect
104114
google.golang.org/genproto/googleapis/rpc v0.0.0-20231030173426-d783a09b4405 // indirect
105115
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
116+
gopkg.in/yaml.v2 v2.4.0 // indirect
106117
gopkg.in/yaml.v3 v3.0.1 // indirect
107118
)

0 commit comments

Comments
 (0)