From 22e5727971e741dcf48e214b2ea729536478fd06 Mon Sep 17 00:00:00 2001 From: Tohrusky <65994850+Tohrusky@users.noreply.github.com> Date: Mon, 15 Jul 2024 19:10:10 +0800 Subject: [PATCH 1/4] feat: error code gen --- module/{error => code}/code.go | 2 +- module/{error => code}/code.ts | 0 module/{error => code}/code_map.go | 2 +- module/{error => code}/gen/map.go | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename module/{error => code}/code.go (95%) rename module/{error => code}/code.ts (100%) rename module/{error => code}/code_map.go (96%) rename module/{error => code}/gen/map.go (99%) diff --git a/module/error/code.go b/module/code/code.go similarity index 95% rename from module/error/code.go rename to module/code/code.go index 5d1b801..33d7b48 100644 --- a/module/error/code.go +++ b/module/code/code.go @@ -1,4 +1,4 @@ -package error +package code type Code uint32 diff --git a/module/error/code.ts b/module/code/code.ts similarity index 100% rename from module/error/code.ts rename to module/code/code.ts diff --git a/module/error/code_map.go b/module/code/code_map.go similarity index 96% rename from module/error/code_map.go rename to module/code/code_map.go index 9bf694d..13f3a46 100644 --- a/module/error/code_map.go +++ b/module/code/code_map.go @@ -1,7 +1,7 @@ // Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT. -package error +package code // codeToString use a map to store the string representation of Code var codeToString = map[Code]string{ diff --git a/module/error/gen/map.go b/module/code/gen/map.go similarity index 99% rename from module/error/gen/map.go rename to module/code/gen/map.go index f17de72..c20a039 100644 --- a/module/error/gen/map.go +++ b/module/code/gen/map.go @@ -85,7 +85,7 @@ func generateMap(constBlock []string) string { mapLines = append(mapLines, "// Code generated by go generate; DO NOT EDIT.") mapLines = append(mapLines, "// Code generated by go generate; DO NOT EDIT.") mapLines = append(mapLines, "// Code generated by go generate; DO NOT EDIT.") - mapLines = append(mapLines, "package error") + mapLines = append(mapLines, "package code") mapLines = append(mapLines, "") mapLines = append(mapLines, "// codeToString use a map to store the string representation of Code") mapLines = append(mapLines, "var codeToString = map[Code]string{") From b783f6c3ca8bd7c51dd0b44369dda744af5df9d0 Mon Sep 17 00:00:00 2001 From: Tohrusky <65994850+Tohrusky@users.noreply.github.com> Date: Tue, 16 Jul 2024 00:57:17 +0800 Subject: [PATCH 2/4] feat: add error code resp --- .gitignore | 3 ++ internal/common/dao/user.go | 4 +-- internal/middleware/jwt/auth.go | 7 ++-- internal/service/user/login.go | 11 ++++--- internal/service/user/logout.go | 5 +-- internal/service/user/profile.go | 18 ++++++----- internal/service/user/profile_update.go | 12 ++++--- internal/service/user/register.go | 16 +++++---- internal/service/user/reset.go | 14 ++++---- module/code/code.go | 19 +++++++++-- module/code/code.ts | 13 ++++++-- module/code/code_map.go | 17 +++++++--- module/code/gen/map.go | 3 ++ module/{util => resp}/gin.go | 43 +++++++++++++++++-------- 14 files changed, 123 insertions(+), 62 deletions(-) rename module/{util => resp}/gin.go (56%) diff --git a/.gitignore b/.gitignore index 8d63a33..446b5ec 100644 --- a/.gitignore +++ b/.gitignore @@ -118,3 +118,6 @@ $RECYCLE.BIN/ # Air tmp + +# build files +/nuxbt diff --git a/internal/common/dao/user.go b/internal/common/dao/user.go index e58755d..e7d97f6 100644 --- a/internal/common/dao/user.go +++ b/internal/common/dao/user.go @@ -13,8 +13,8 @@ func CreateUser(user *model.User) (err error) { return err } -// SetUserPassword 设置用户密码 -func SetUserPassword(user *model.User, newPassword string) (err error) { +// UpdateUserPassword 设置用户密码 +func UpdateUserPassword(user *model.User, newPassword string) (err error) { u := query.User password, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) if err != nil { diff --git a/internal/middleware/jwt/auth.go b/internal/middleware/jwt/auth.go index ffba746..0c02921 100644 --- a/internal/middleware/jwt/auth.go +++ b/internal/middleware/jwt/auth.go @@ -2,8 +2,9 @@ package jwt import ( "github.com/TensoRaws/NuxBT-Backend/module/cache" + "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" - "github.com/TensoRaws/NuxBT-Backend/module/util" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/gin-gonic/gin" ) @@ -20,13 +21,13 @@ func RequireAuth(redisClient *cache.Client, addBlacklist bool) gin.HandlerFunc { exists := redisClient.Exists(token).Val() if exists > 0 { log.Logger.Info("Token has been blacklisted") - util.AbortWithMsg(c, "Token has been blacklisted") + resp.Abort(c, code.AuthErrorTokenHasBeenBlacklisted) return } // 如果 Token 不在黑名单中,继续处理请求 claims, err := ParseToken(token) if err != nil { - util.AbortWithMsg(c, "TOKEN IS INVALID, Please Log In") + resp.AbortWithMsg(c, code.AuthErrorTokenIsInvalid, "Please Log In") return } userID := claims.ID diff --git a/internal/service/user/login.go b/internal/service/user/login.go index 05bfc87..640bb42 100644 --- a/internal/service/user/login.go +++ b/internal/service/user/login.go @@ -3,7 +3,8 @@ package user import ( "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" "github.com/TensoRaws/NuxBT-Backend/internal/middleware/jwt" - "github.com/TensoRaws/NuxBT-Backend/module/util" + "github.com/TensoRaws/NuxBT-Backend/module/code" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" ) @@ -21,14 +22,14 @@ type LoginResponse struct { func Login(c *gin.Context) { var req LoginRequest if err := c.ShouldBindJSON(&req); err != nil { - util.AbortWithMsg(c, "invalid request: "+err.Error()) + resp.AbortWithMsg(c, code.RequestErrorInvalidParams, err.Error()) return } // GORM 查询 user, err := dao.GetUserByEmail(req.Email) if err != nil { - util.AbortWithMsg(c, "User not found") + resp.AbortWithMsg(c, code.DatabaseErrorRecordNotFound, "User not found") return } @@ -38,11 +39,11 @@ func Login(c *gin.Context) { // 注册之后的下次登录成功,才会为其生成 token token := jwt.GenerateToken(user) // 打印相应信息和用户信息以及生成的 token 值 - util.OKWithData(c, LoginResponse{ + resp.OKWithData(c, LoginResponse{ Token: token, }) } else { - util.AbortWithMsg(c, "Invalid Username or Password") + resp.Abort(c, code.UserErrorInvalidPassword) return } } diff --git a/internal/service/user/logout.go b/internal/service/user/logout.go index 1e547fc..c73380b 100644 --- a/internal/service/user/logout.go +++ b/internal/service/user/logout.go @@ -2,15 +2,16 @@ package user import ( "github.com/TensoRaws/NuxBT-Backend/module/log" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" ) // Logout 用户登出 (POST /logout) func Logout(c *gin.Context) { - userID, _ := util.GetUserIDFromGinContext(c) + userID, _ := resp.GetUserIDFromGinContext(c) - util.OKWithMsg(c, "Logout success") + resp.OK(c) log.Logger.Info("Logout success, user ID: " + util.StructToString(userID)) } diff --git a/internal/service/user/profile.go b/internal/service/user/profile.go index 914f184..63d72db 100644 --- a/internal/service/user/profile.go +++ b/internal/service/user/profile.go @@ -4,7 +4,9 @@ import ( "strconv" "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" + "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" ) @@ -30,11 +32,11 @@ type ProfileOthersRequest struct { // ProfileMe 获取用户自己的信息 (GET /profile/me) func ProfileMe(c *gin.Context) { - userID, _ := util.GetUserIDFromGinContext(c) + userID, _ := resp.GetUserIDFromGinContext(c) user, err := dao.GetUserByID(userID) if err != nil { - util.AbortWithMsg(c, "User not found") + resp.AbortWithMsg(c, code.DatabaseErrorRecordNotFound, "User not found") return } @@ -44,7 +46,7 @@ func ProfileMe(c *gin.Context) { roles = []string{} } - util.OKWithData(c, ProfileResponse{ + resp.OKWithData(c, ProfileResponse{ Avatar: user.Avatar, Background: user.Background, CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"), @@ -67,16 +69,16 @@ func ProfileOthers(c *gin.Context) { // 绑定参数 var req ProfileOthersRequest if err := c.ShouldBindQuery(&req); err != nil { - util.AbortWithMsg(c, "invalid request: "+err.Error()) + resp.AbortWithMsg(c, code.RequestErrorInvalidParams, err.Error()) return } - userID, _ := util.GetUserIDFromGinContext(c) + userID, _ := resp.GetUserIDFromGinContext(c) // 获取信息 user, err := dao.GetUserByID(req.UserID) if err != nil { - util.AbortWithMsg(c, "User not found") + resp.AbortWithMsg(c, code.DatabaseErrorRecordNotFound, "User not found") return } @@ -88,7 +90,7 @@ func ProfileOthers(c *gin.Context) { // 判断是否为隐私账号 if user.Private { // 只显示最基础信息 - util.OKWithData(c, ProfileResponse{ + resp.OKWithData(c, ProfileResponse{ Avatar: user.Avatar, Background: user.Background, CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"), @@ -104,7 +106,7 @@ func ProfileOthers(c *gin.Context) { }) } else { // 显示全部信息 - util.OKWithData(c, ProfileResponse{ + resp.OKWithData(c, ProfileResponse{ Avatar: user.Avatar, Background: user.Background, CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"), diff --git a/internal/service/user/profile_update.go b/internal/service/user/profile_update.go index f1d1123..79ff386 100644 --- a/internal/service/user/profile_update.go +++ b/internal/service/user/profile_update.go @@ -4,7 +4,9 @@ import ( "strconv" "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" + "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" ) @@ -23,11 +25,11 @@ func ProfileUpdate(c *gin.Context) { // 参数绑定 var req ProfileUpdateRequest if err := c.ShouldBindJSON(&req); err != nil { - util.AbortWithMsg(c, "invalid request: "+err.Error()) + resp.AbortWithMsg(c, code.RequestErrorInvalidParams, err.Error()) return } - userID, _ := util.GetUserIDFromGinContext(c) + userID, _ := resp.GetUserIDFromGinContext(c) // 准备更新数据 updates := make(map[string]interface{}) @@ -39,7 +41,7 @@ func ProfileUpdate(c *gin.Context) { if req.Username != nil && *req.Username != "" { err := util.CheckUsername(*req.Username) if err != nil { - util.AbortWithMsg(c, "invalid username: "+err.Error()) + resp.AbortWithMsg(c, code.UserErrorInvalidUsername, err.Error()) return } updates["username"] = *req.Username @@ -63,11 +65,11 @@ func ProfileUpdate(c *gin.Context) { // 执行更新 err := dao.UpdateUserDataByUserID(userID, updates) if err != nil { - util.AbortWithMsg(c, "update failed: "+err.Error()) + resp.AbortWithMsg(c, code.DatabaseErrorRecordUpdateFailed, err.Error()) return } - util.OKWithMsg(c, "update success") + resp.OK(c) log.Logger.Info("update user profile success: " + strconv.Itoa(int(userID))) } diff --git a/internal/service/user/register.go b/internal/service/user/register.go index bc0d33f..0d01430 100644 --- a/internal/service/user/register.go +++ b/internal/service/user/register.go @@ -5,8 +5,10 @@ import ( "github.com/TensoRaws/NuxBT-Backend/dal/model" "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" + "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/config" "github.com/TensoRaws/NuxBT-Backend/module/log" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" @@ -31,20 +33,20 @@ type RegisterDataResponse struct { func Register(c *gin.Context) { var req RegisterRequest if err := c.ShouldBindJSON(&req); err != nil { - util.AbortWithMsg(c, "invalid request: "+err.Error()) + resp.AbortWithMsg(c, code.RequestErrorInvalidParams, err.Error()) return } err := util.CheckUsername(req.Username) if err != nil { - util.AbortWithMsg(c, "invalid username: "+err.Error()) + resp.AbortWithMsg(c, code.UserErrorInvalidUsername, err.Error()) return } // 无邀请码注册,检查是否允许无邀请码注册 if req.InvitationCode == nil || *req.InvitationCode == "" { if config.ServerConfig.UseInvitationCode { - util.AbortWithMsg(c, "invitation code is required") + resp.AbortWithMsg(c, code.UserErrorInvalidInvitationCode, "invitation code is required") return } } else { @@ -54,7 +56,7 @@ func Register(c *gin.Context) { } password, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { - util.AbortWithMsg(c, "failed to hash password") + resp.AbortWithMsg(c, code.UnknownError, "failed to hash password") log.Logger.Error("failed to hash password: " + err.Error()) return } @@ -66,19 +68,19 @@ func Register(c *gin.Context) { LastActive: time.Now(), }) if err != nil { - util.AbortWithMsg(c, "failed to register: "+err.Error()) + resp.AbortWithMsg(c, code.DatabaseErrorRecordCreateFailed, "failed to register "+err.Error()) log.Logger.Error("failed to register: " + err.Error()) return } user, err := dao.GetUserByEmail(req.Email) if err != nil { - util.AbortWithMsg(c, "failed to get user by email") + resp.AbortWithMsg(c, code.DatabaseErrorRecordNotFound, "failed to get user by email") log.Logger.Error("failed to get user by email: " + err.Error()) return } - util.OKWithData(c, RegisterDataResponse{ + resp.OKWithData(c, RegisterDataResponse{ Email: user.Email, UserID: user.UserID, Username: user.Username, diff --git a/internal/service/user/reset.go b/internal/service/user/reset.go index 842a69f..81fa748 100644 --- a/internal/service/user/reset.go +++ b/internal/service/user/reset.go @@ -2,7 +2,9 @@ package user import ( "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" + "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" + "github.com/TensoRaws/NuxBT-Backend/module/resp" "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" ) @@ -16,24 +18,24 @@ func ResetPassword(c *gin.Context) { // 绑定参数 var req ResetPasswordRequest if err := c.ShouldBindJSON(&req); err != nil { - util.AbortWithMsg(c, "invalid request: "+err.Error()) + resp.AbortWithMsg(c, code.RequestErrorInvalidParams, err.Error()) return } - userID, _ := util.GetUserIDFromGinContext(c) + userID, _ := resp.GetUserIDFromGinContext(c) user, err := dao.GetUserByID(userID) if err != nil { - util.AbortWithMsg(c, "User not found") + resp.AbortWithMsg(c, code.DatabaseErrorRecordNotFound, "User not found") return } // 修改密码 - err = dao.SetUserPassword(user, req.NewPassword) + err = dao.UpdateUserPassword(user, req.NewPassword) if err != nil { - util.AbortWithMsg(c, "reset password fail") + resp.AbortWithMsg(c, code.DatabaseErrorRecordUpdateFailed, "reset password fail") } // 返回 - util.OKWithMsg(c, "reset password success") + resp.OK(c) log.Logger.Info("Reset password success: " + util.StructToString(user)) } diff --git a/module/code/code.go b/module/code/code.go index 33d7b48..1ee34fe 100644 --- a/module/code/code.go +++ b/module/code/code.go @@ -2,14 +2,27 @@ package code type Code uint32 +// 请勿修改,常量之间不要有空行! +// DO NOT EDIT, no empty line between constants! const ( // DO NOT EDIT // gen code start InternalError Code = 10000 + iota UnknownError - InvalidParams - InvalidToken - InvalidUserName + // AuthError 鉴权错误 + AuthErrorTokenHasBeenBlacklisted + AuthErrorTokenIsInvalid + // RequestError 请求错误 + RequestErrorInvalidParams + // DatabaseError 数据库错误 + DatabaseErrorRecordCreateFailed + DatabaseErrorRecordNotFound + DatabaseErrorRecordUpdateFailed + // UserError 用户侧错误 + UserErrorInvalidUsername + UserErrorInvalidPassword + UserErrorInvalidEmail + UserErrorInvalidInvitationCode // gen code end // DO NOT EDIT ) diff --git a/module/code/code.ts b/module/code/code.ts index b586bfc..27aaba4 100644 --- a/module/code/code.ts +++ b/module/code/code.ts @@ -5,7 +5,14 @@ export const enum ErrorCode { InternalError = 10000, UnknownError, - InvalidParams, - InvalidToken, - InvalidUserName + AuthErrorTokenHasBeenBlacklisted, + AuthErrorTokenIsInvalid, + RequestErrorInvalidParams, + DatabaseErrorRecordCreateFailed, + DatabaseErrorRecordNotFound, + DatabaseErrorRecordUpdateFailed, + UserErrorInvalidUsername, + UserErrorInvalidPassword, + UserErrorInvalidEmail, + UserErrorInvalidInvitationCode } diff --git a/module/code/code_map.go b/module/code/code_map.go index 13f3a46..ced9358 100644 --- a/module/code/code_map.go +++ b/module/code/code_map.go @@ -5,9 +5,16 @@ package code // codeToString use a map to store the string representation of Code var codeToString = map[Code]string{ - InternalError: "Internal error", - UnknownError: "Unknown error", - InvalidParams: "Invalid params", - InvalidToken: "Invalid token", - InvalidUserName: "Invalid user name", + InternalError: "Internal error", + UnknownError: "Unknown error", + AuthErrorTokenHasBeenBlacklisted: "Auth error token has been blacklisted", + AuthErrorTokenIsInvalid: "Auth error token is invalid", + RequestErrorInvalidParams: "Request error invalid params", + DatabaseErrorRecordCreateFailed: "Database error record create failed", + DatabaseErrorRecordNotFound: "Database error record not found", + DatabaseErrorRecordUpdateFailed: "Database error record update failed", + UserErrorInvalidUsername: "User error invalid username", + UserErrorInvalidPassword: "User error invalid password", + UserErrorInvalidEmail: "User error invalid email", + UserErrorInvalidInvitationCode: "User error invalid invitation code", } diff --git a/module/code/gen/map.go b/module/code/gen/map.go index c20a039..aa12cbb 100644 --- a/module/code/gen/map.go +++ b/module/code/gen/map.go @@ -37,6 +37,9 @@ func buildConstBlock(filename string) ([]string, uint32) { if strings.Contains(line, "gen code end") { break } + if line == "" || strings.Contains(line, "//") { + continue + } if buildBlockFlag { if strings.Contains(line, "iota") { // OK Code = 10000 + iota l := strings.Split(line, " ") diff --git a/module/util/gin.go b/module/resp/gin.go similarity index 56% rename from module/util/gin.go rename to module/resp/gin.go index d9a2211..d8c032b 100644 --- a/module/util/gin.go +++ b/module/resp/gin.go @@ -1,7 +1,8 @@ -package util +package resp import ( "fmt" + "github.com/TensoRaws/NuxBT-Backend/module/code" "net/http" "strconv" @@ -21,30 +22,46 @@ func GetUserIDFromGinContext(c *gin.Context) (int32, error) { return int32(userID), err } -// OKWithMsg 返回成功信息 -func OKWithMsg(c *gin.Context, ok string) { +// OK 返回成功信息 +func OK(c *gin.Context) { resp := map[string]interface{}{ "success": true, - "message": ok, } c.JSON(http.StatusOK, resp) } -func AbortWithMsg(c *gin.Context, msg string) { - resp := map[string]interface{}{ - "success": false, - "message": msg, - } - c.AbortWithStatusJSON(http.StatusOK, resp) -} - // OKWithData 返回成功信息,携带自定义数据(结构体) func OKWithData(c *gin.Context, data interface{}) { resp := map[string]interface{}{ "success": true, - "message": "ok", "data": data, } c.JSON(http.StatusOK, resp) } + +// Abort 返回错误码 +func Abort(c *gin.Context, code code.Code) { + errorResp := map[string]interface{}{ + "code": code, + "message": code.String(), + } + resp := map[string]interface{}{ + "success": false, + "error": errorResp, + } + c.AbortWithStatusJSON(http.StatusOK, resp) +} + +// AbortWithMsg 返回错误码,自定义错误信息 +func AbortWithMsg(c *gin.Context, code code.Code, msg string) { + errorResp := map[string]interface{}{ + "code": code, + "message": code.String() + ": " + msg, + } + resp := map[string]interface{}{ + "success": false, + "error": errorResp, + } + c.AbortWithStatusJSON(http.StatusOK, resp) +} From 17eea963cbd0db0cbb59730f02dfa329e156478e Mon Sep 17 00:00:00 2001 From: Tohrusky <65994850+Tohrusky@users.noreply.github.com> Date: Tue, 16 Jul 2024 01:21:19 +0800 Subject: [PATCH 3/4] feat: add error code resp --- internal/common/dao/user.go | 15 --------------- internal/service/user/logout.go | 3 +-- internal/service/user/profile.go | 8 ++------ internal/service/user/profile_update.go | 4 +--- internal/service/user/register.go | 2 +- internal/service/user/reset.go | 15 ++++++--------- module/resp/gin.go | 2 +- 7 files changed, 12 insertions(+), 37 deletions(-) diff --git a/internal/common/dao/user.go b/internal/common/dao/user.go index e7d97f6..5eefb25 100644 --- a/internal/common/dao/user.go +++ b/internal/common/dao/user.go @@ -3,7 +3,6 @@ package dao import ( "github.com/TensoRaws/NuxBT-Backend/dal/model" "github.com/TensoRaws/NuxBT-Backend/dal/query" - "golang.org/x/crypto/bcrypt" ) // CreateUser 新建用户 @@ -13,20 +12,6 @@ func CreateUser(user *model.User) (err error) { return err } -// UpdateUserPassword 设置用户密码 -func UpdateUserPassword(user *model.User, newPassword string) (err error) { - u := query.User - password, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) - if err != nil { - return err - } - _, err = u.Where(u.UserID.Eq(user.UserID)).Update(u.Password, string(password)) - if err != nil { - return err - } - return err -} - // UpdateUserDataByUserID 根据 map 更新用户信息,map 中的 key 为字段名 func UpdateUserDataByUserID(userID int32, maps map[string]interface{}) (err error) { u := query.User diff --git a/internal/service/user/logout.go b/internal/service/user/logout.go index c73380b..2eacb5b 100644 --- a/internal/service/user/logout.go +++ b/internal/service/user/logout.go @@ -3,7 +3,6 @@ package user import ( "github.com/TensoRaws/NuxBT-Backend/module/log" "github.com/TensoRaws/NuxBT-Backend/module/resp" - "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" ) @@ -13,5 +12,5 @@ func Logout(c *gin.Context) { resp.OK(c) - log.Logger.Info("Logout success, user ID: " + util.StructToString(userID)) + log.Logger.Infof("Logout success, user ID: %v", userID) } diff --git a/internal/service/user/profile.go b/internal/service/user/profile.go index 63d72db..0cf07a3 100644 --- a/internal/service/user/profile.go +++ b/internal/service/user/profile.go @@ -1,13 +1,10 @@ package user import ( - "strconv" - "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" "github.com/TensoRaws/NuxBT-Backend/module/resp" - "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" ) @@ -61,7 +58,7 @@ func ProfileMe(c *gin.Context) { Username: user.Username, }) - log.Logger.Info("get user profile success: " + util.StructToString(user)) + log.Logger.Infof("get user profile success, userID: %v", userID) } // ProfileOthers 用户查询他人信息 (GET /profile) @@ -122,6 +119,5 @@ func ProfileOthers(c *gin.Context) { }) } - log.Logger.Info("Get user profile success: " + strconv.Itoa(int(req.UserID)) + - ", by user ID: " + strconv.Itoa(int(userID))) + log.Logger.Infof("Get user %v profile success, by user ID: %v", req.UserID, userID) } diff --git a/internal/service/user/profile_update.go b/internal/service/user/profile_update.go index 79ff386..81c092d 100644 --- a/internal/service/user/profile_update.go +++ b/internal/service/user/profile_update.go @@ -1,8 +1,6 @@ package user import ( - "strconv" - "github.com/TensoRaws/NuxBT-Backend/internal/common/dao" "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" @@ -71,5 +69,5 @@ func ProfileUpdate(c *gin.Context) { resp.OK(c) - log.Logger.Info("update user profile success: " + strconv.Itoa(int(userID))) + log.Logger.Infof("update user profile success, userID: %v", userID) } diff --git a/internal/service/user/register.go b/internal/service/user/register.go index 0d01430..c9aa631 100644 --- a/internal/service/user/register.go +++ b/internal/service/user/register.go @@ -85,5 +85,5 @@ func Register(c *gin.Context) { UserID: user.UserID, Username: user.Username, }) - log.Logger.Info("register success: " + util.StructToString(user)) + log.Logger.Infof("register success, userID: %v", user.UserID) } diff --git a/internal/service/user/reset.go b/internal/service/user/reset.go index 81fa748..ec89651 100644 --- a/internal/service/user/reset.go +++ b/internal/service/user/reset.go @@ -5,8 +5,8 @@ import ( "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/TensoRaws/NuxBT-Backend/module/log" "github.com/TensoRaws/NuxBT-Backend/module/resp" - "github.com/TensoRaws/NuxBT-Backend/module/util" "github.com/gin-gonic/gin" + "golang.org/x/crypto/bcrypt" ) type ResetPasswordRequest struct { @@ -24,18 +24,15 @@ func ResetPassword(c *gin.Context) { userID, _ := resp.GetUserIDFromGinContext(c) - user, err := dao.GetUserByID(userID) - if err != nil { - resp.AbortWithMsg(c, code.DatabaseErrorRecordNotFound, "User not found") - return - } - + password, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) // 修改密码 - err = dao.UpdateUserPassword(user, req.NewPassword) + err = dao.UpdateUserDataByUserID(userID, map[string]interface{}{ + "password": password, + }) if err != nil { resp.AbortWithMsg(c, code.DatabaseErrorRecordUpdateFailed, "reset password fail") } // 返回 resp.OK(c) - log.Logger.Info("Reset password success: " + util.StructToString(user)) + log.Logger.Infof("Reset password success, user ID: %v", userID) } diff --git a/module/resp/gin.go b/module/resp/gin.go index d8c032b..f0492b3 100644 --- a/module/resp/gin.go +++ b/module/resp/gin.go @@ -2,10 +2,10 @@ package resp import ( "fmt" - "github.com/TensoRaws/NuxBT-Backend/module/code" "net/http" "strconv" + "github.com/TensoRaws/NuxBT-Backend/module/code" "github.com/gin-gonic/gin" ) From ae87efd38cc212e3ffb9aecbc65156a7cc21159a Mon Sep 17 00:00:00 2001 From: Tohrusky <65994850+Tohrusky@users.noreply.github.com> Date: Tue, 16 Jul 2024 01:23:55 +0800 Subject: [PATCH 4/4] feat: add error code resp --- internal/service/user/reset.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/service/user/reset.go b/internal/service/user/reset.go index ec89651..baa233c 100644 --- a/internal/service/user/reset.go +++ b/internal/service/user/reset.go @@ -25,6 +25,11 @@ func ResetPassword(c *gin.Context) { userID, _ := resp.GetUserIDFromGinContext(c) password, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) + if err != nil { + resp.AbortWithMsg(c, code.UnknownError, "failed to hash password") + log.Logger.Error("failed to hash password: " + err.Error()) + return + } // 修改密码 err = dao.UpdateUserDataByUserID(userID, map[string]interface{}{ "password": password,