Skip to content

Commit

Permalink
feat: add error code resp (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tohrusky authored Jul 15, 2024
1 parent f0f7de4 commit 767000f
Show file tree
Hide file tree
Showing 17 changed files with 168 additions and 127 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
15 changes: 0 additions & 15 deletions internal/common/dao/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 新建用户
Expand All @@ -13,20 +12,6 @@ func CreateUser(user *model.User) (err error) {
return err
}

// SetUserPassword 设置用户密码
func SetUserPassword(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
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
}
}
8 changes: 4 additions & 4 deletions internal/service/user/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package user

import (
"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"
)

// 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))
log.Logger.Infof("Logout success, user ID: %v", userID)
}
26 changes: 12 additions & 14 deletions internal/service/user/profile.go
Original file line number Diff line number Diff line change
@@ -1,11 +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/util"
"github.com/TensoRaws/NuxBT-Backend/module/resp"
"github.com/gin-gonic/gin"
)

Expand All @@ -30,11 +29,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 +43,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 @@ -59,24 +58,24 @@ 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)
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 +87,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 +103,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 All @@ -120,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)
}
16 changes: 8 additions & 8 deletions internal/service/user/profile_update.go
Original file line number Diff line number Diff line change
@@ -1,10 +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"
)
Expand All @@ -23,11 +23,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 +39,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 +63,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)))
log.Logger.Infof("update user profile success, userID: %v", userID)
}
18 changes: 10 additions & 8 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,22 +68,22 @@ 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,
})
log.Logger.Info("register success: " + util.StructToString(user))
log.Logger.Infof("register success, userID: %v", user.UserID)
}
24 changes: 14 additions & 10 deletions internal/service/user/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ 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/util"
"github.com/TensoRaws/NuxBT-Backend/module/resp"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)

type ResetPasswordRequest struct {
Expand All @@ -16,24 +18,26 @@ 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)
password, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
if err != nil {
util.AbortWithMsg(c, "User not found")
resp.AbortWithMsg(c, code.UnknownError, "failed to hash password")
log.Logger.Error("failed to hash password: " + err.Error())
return
}

// 修改密码
err = dao.SetUserPassword(user, req.NewPassword)
err = dao.UpdateUserDataByUserID(userID, map[string]interface{}{
"password": password,
})
if err != nil {
util.AbortWithMsg(c, "reset password fail")
resp.AbortWithMsg(c, code.DatabaseErrorRecordUpdateFailed, "reset password fail")
}
// 返回
util.OKWithMsg(c, "reset password success")
log.Logger.Info("Reset password success: " + util.StructToString(user))
resp.OK(c)
log.Logger.Infof("Reset password success, user ID: %v", userID)
}
Loading

0 comments on commit 767000f

Please sign in to comment.