Skip to content

Commit 67dbf44

Browse files
committed
feat: 合并JWT中间件测试文件并修复本地化消息
- 将AuthMiddleware_test.go和auth_middleware_test.go合并为单一测试文件 - 修复unauthorized函数使用本地化的JWT认证失败消息 - 所有测试现在都通过,包括双语错误消息测试 - 测试覆盖JWT中间件的完整功能:初始化、认证、授权、响应处理等
1 parent c7b7305 commit 67dbf44

File tree

2 files changed

+654
-4
lines changed

2 files changed

+654
-4
lines changed

internal/pkg/middleware/AuthMiddleware.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,17 @@ func login(c *gin.Context) (interface{}, error) {
8484
userRepository := repository.NewAdminRepository()
8585
user, err := userRepository.Login(u)
8686
if err != nil {
87+
// 检查是否为RepositoryError,如果是则返回本地化错误消息
88+
if repoErr, ok := err.(*common.RepositoryError); ok {
89+
localizedMsg := repoErr.GetLocalizedMessage(c)
90+
return nil, fmt.Errorf("%s", localizedMsg)
91+
}
8792
return nil, err
8893
}
8994
// 将用户以json格式写入, payloadFunc/authorizator会使用到
9095
userJson, err := util.JSONUtil.Struct2Json(user)
9196
if err != nil {
92-
return nil, fmt.Errorf("用户信息序列化失败: %v", err)
97+
return nil, fmt.Errorf("%s: %v", common.Msg(c, common.MsgUserSerializeFail), err)
9398
}
9499
return map[string]interface{}{
95100
"user": userJson,
@@ -113,13 +118,15 @@ func authorizator(data interface{}, c *gin.Context) bool {
113118
// 用户登录校验失败处理
114119
func unauthorized(c *gin.Context, code int, message string) {
115120
common.Log.Debugf("JWT认证失败, 错误码: %d, 错误信息: %s", code, message)
116-
response.ResponseFunc(c, code, code, nil, fmt.Sprintf("JWT认证失败, 错误码: %d, 错误信息: %s", code, message))
121+
// 使用本地化的JWT认证失败消息,并包含具体的错误信息
122+
localizedMsg := fmt.Sprintf("%s: %s", common.Msg(c, common.MsgJWTAuthFail), message)
123+
response.Unauthorized(c, localizedMsg)
117124
}
118125

119126
// 登录成功后的响应
120127
func loginResponse(c *gin.Context, code int, token string, expires time.Time) {
121128
msg := common.Msg(c, common.MsgLoginSuccess)
122-
response.ResponseFunc(c, code, code,
129+
response.Success(c,
123130
gin.H{
124131
"token": token,
125132
"expires": expires.Format(known.TIME_FORMAT),
@@ -136,7 +143,7 @@ func logoutResponse(c *gin.Context, code int) {
136143
// 刷新token后的响应
137144
func refreshResponse(c *gin.Context, code int, token string, expires time.Time) {
138145
msg := common.Msg(c, common.MsgRefreshTokenSuccess)
139-
response.ResponseFunc(c, code, code,
146+
response.Success(c,
140147
gin.H{
141148
"token": token,
142149
"expires": expires,

0 commit comments

Comments
 (0)