Skip to content

Commit

Permalink
feat: add error code resp
Browse files Browse the repository at this point in the history
  • Loading branch information
Tohrusky committed Jul 15, 2024
1 parent 22e5727 commit b783f6c
Show file tree
Hide file tree
Showing 14 changed files with 123 additions and 62 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,6 @@ $RECYCLE.BIN/

# Air
tmp

# build files
/nuxbt
4 changes: 2 additions & 2 deletions internal/common/dao/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 4 additions & 3 deletions internal/middleware/jwt/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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
Expand Down
11 changes: 6 additions & 5 deletions internal/service/user/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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
}

Expand All @@ -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
}
}
5 changes: 3 additions & 2 deletions internal/service/user/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
18 changes: 10 additions & 8 deletions internal/service/user/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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
}

Expand All @@ -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"),
Expand All @@ -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
}

Expand All @@ -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"),
Expand All @@ -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"),
Expand Down
12 changes: 7 additions & 5 deletions internal/service/user/profile_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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{})
Expand All @@ -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
Expand All @@ -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)))
}
16 changes: 9 additions & 7 deletions internal/service/user/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 {
Expand All @@ -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
}
Expand All @@ -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,
Expand Down
14 changes: 8 additions & 6 deletions internal/service/user/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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))
}
19 changes: 16 additions & 3 deletions module/code/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
13 changes: 10 additions & 3 deletions module/code/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@
export const enum ErrorCode {
InternalError = 10000,
UnknownError,
InvalidParams,
InvalidToken,
InvalidUserName
AuthErrorTokenHasBeenBlacklisted,
AuthErrorTokenIsInvalid,
RequestErrorInvalidParams,
DatabaseErrorRecordCreateFailed,
DatabaseErrorRecordNotFound,
DatabaseErrorRecordUpdateFailed,
UserErrorInvalidUsername,
UserErrorInvalidPassword,
UserErrorInvalidEmail,
UserErrorInvalidInvitationCode
}
Loading

0 comments on commit b783f6c

Please sign in to comment.