Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(oauth,user)finish the logout and users functions #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

cqhasy
Copy link
Collaborator

@cqhasy cqhasy commented Feb 3, 2025

Summary by CodeRabbit

  • New Features

    • Introduced endpoints for user registration, logout, profile updates, and role management.
    • Enabled enhanced user retrieval and role assignment functionality.
    • Added project management capabilities, including project creation and detail retrieval.
  • Improvements

    • Upgraded error handling and request data processing for more reliable interactions.
    • Expanded the data migration process to support additional user and project associations.

Copy link

coderabbitai bot commented Feb 3, 2025

Walkthrough

The changes introduce new request types, controller methods, and services to handle user updates and role management. Updates were made to authentication endpoints by adding logout and user info update functionalities. Additionally, a new user management controller and routes were created to support operations like retrieving and updating users. The data layer has been enhanced with new models, DAO methods, and migrations. Auxiliary packages like ginx and the dependency injection configuration have been updated for better error handling and integration of the new user features.

Changes

Files / Groups Change Summary
api/request/request.go Added new request types: UpdateUserReq, GetUserReq, UpdateUserRoleReq, CreateProject, and GetProjectDetail.
controller/Auth.go & service/Auth.go Introduced Logout and UpdateMyInfo methods in AuthController and AuthService with updated interface signatures.
controller/controller.go & service/User.go Added a new UserController struct and UserService with methods for user retrieval (GetUsers) and role updates (UpdateUserRole).
router/Auth.go, router/User.go & router/router.go Expanded routing: Updated OAuth routes (renamed group from /auth to /user) and added new routes for registration, logout, updating user info, and user management endpoints.
repository/dao/dao.go, repository/dao/user.go & repository/model/model.go Expanded migrations to include Project, UserProject; new DAO methods (FindByProjectID, FindByUserIDs, GetResponse, ChangeProjectRole, GetProjectList, CreateProject, GetProjectDetails); new data models (Project, UserProject, ProjectPermit, UserResponse, ProjectList, Item, plus additional fields in User).
pkg/ginx/ginx.go, wire.go & wire_gen.go Enhanced error checking and corrected request binding in ginx; updated dependency injection to integrate the new user service and controller.
controller/Project.go & router/Project.go Introduced ProjectController and ProjectService with methods for project management (GetProjectList, Create, Detail).

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant AC as AuthController
    participant AS as AuthService
    participant R as RedisJWTHandler

    C->>AC: Logout Request
    AC->>AS: Logout(ctx)
    AS->>R: ClearToken()
    R-->>AS: Confirmation/Error
    AS-->>AC: Logout Result
    AC-->>C: Logout Response
Loading
sequenceDiagram
    participant C as Client
    participant UC as UserController
    participant US as UserService
    participant DAO as UserDAO

    C->>UC: GetUsers Request
    UC->>US: GetUsers(ctx, id)
    US->>DAO: FindByProjectID(ctx, id)
    DAO-->>US: Users List
    US->>DAO: GetResponse(users)
    DAO-->>US: Formatted Data
    US-->>UC: User Data
    UC-->>C: Response

    Note over C,UC: Alternatively, for updating user roles:
    C->>UC: UpdateUsers Request
    UC->>US: UpdateUserRole(ctx, userId, projectPermit)
    US->>DAO: ChangeProjectRole(ctx, userId, projectPermit)
    DAO-->>US: Update Result
    US-->>UC: Confirmation
    UC-->>C: Response
Loading

Poem

I'm a rabbit in a code-filled glen,
Hopping through changes time and again.
New routes and services make my ears spin,
With controllers and models, let the magic begin.
Bugs hop away as features glow in the den. 🐰
Happy coding, one hop at a time!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (7)
router/User.go (2)

22-22: Consider using GET method for retrieving users.

The /getUsers endpoint uses POST method but since it's retrieving data, consider using GET method to align with REST principles.

Apply this diff to use GET method:

-  UserGroup.POST("/getUsers", authMiddleware, ginx.WrapReq(c.GetUsers))
+  UserGroup.GET("/users", authMiddleware, ginx.WrapReq(c.GetUsers))

23-23: Consider renaming updateUser endpoint for consistency.

For consistency with REST principles and the previous suggestion, consider renaming the endpoint.

Apply this diff to rename the endpoint:

-  UserGroup.POST("/updateUser", authMiddleware, ginx.WrapReq(c.UpdateUsers))
+  UserGroup.PUT("/users", authMiddleware, ginx.WrapReq(c.UpdateUsers))
router/Auth.go (1)

23-23: Consider keeping the route group as /auth for authentication-related endpoints.

The route group has been changed from /auth to /user, but this seems inconsistent since this is in the authentication controller and handles authentication-related operations like login, logout, and registration.

-	authGroup := s.Group("/user")
+	authGroup := s.Group("/auth")
service/User.go (1)

30-36: Simplify error handling in UpdateUserRole.

The error handling can be simplified by directly returning the error from ChangeProjectRole.

 func (userService *UserService) UpdateUserRole(ctx context.Context, userId int, projectPermit []model.ProjectPermit) error {
-	err := userService.userDAO.ChangeProjectRole(ctx, userId, projectPermit)
-	if err != nil {
-		return err
-	}
-	return nil
+	return userService.userDAO.ChangeProjectRole(ctx, userId, projectPermit)
 }
repository/model/model.go (1)

23-34: Add documentation for new structs.

Consider adding documentation comments for ProjectPermit and UserResponse structs to explain their purpose and usage.

+// ProjectPermit represents the permissions a user has for a specific project
 type ProjectPermit struct {
     ProjectID   uint   `json:"project_id"`
     ProjectName string `json:"project_name"`
     ProjectRole int    `json:"project_role"`
 }

+// UserResponse represents the API response structure for user data
 type UserResponse struct {
     Name          string          `json:"name"`
     UserID        uint            `json:"user_id"`
     Avatar        string          `json:"avatar"`
     ProjectPermit []ProjectPermit `json:"project_permit"`
     Role          int            `json:"role"`
 }
service/Auth.go (1)

55-61: Consider cleaning up user session data during logout.

The logout implementation only clears the token. Consider cleaning up any additional session data.

controller/Auth.go (1)

95-117: Improve error messages and reduce code duplication.

The Logout method has empty error messages and duplicated error response structure.

 func (c *AuthController) Logout(ctx *gin.Context) (response.Response, error) {
     _, err := ginx.GetClaims[jwt.UserClaims](ctx)
     if err != nil {
         return response.Response{
-            Msg:  "",
+            Msg:  "Invalid or expired token",
             Code: 40001,
             Data: nil,
         }, err
     }
     err = c.service.Logout(ctx)
     if err != nil {
         return response.Response{
-            Msg:  "",
+            Msg:  "Failed to logout",
             Code: 40001,
             Data: nil,
         }, err
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e6047a2 and 9143a0e.

📒 Files selected for processing (14)
  • api/request/request.go (1 hunks)
  • controller/Auth.go (3 hunks)
  • controller/controller.go (1 hunks)
  • pkg/ginx/ginx.go (5 hunks)
  • repository/dao/dao.go (1 hunks)
  • repository/dao/user.go (1 hunks)
  • repository/model/model.go (1 hunks)
  • router/Auth.go (2 hunks)
  • router/User.go (1 hunks)
  • router/router.go (2 hunks)
  • service/Auth.go (2 hunks)
  • service/User.go (1 hunks)
  • wire.go (1 hunks)
  • wire_gen.go (1 hunks)
🔇 Additional comments (14)
repository/dao/dao.go (1)

9-9: LGTM! Verify model dependencies.

The migration logic is correct. However, let's verify that all required model dependencies are properly defined.

✅ Verification successful

Model dependencies verified successfully.

  • The definitions for User, Project, and UserProject are present in repository/model/model.go and include the expected fields and relationships.
  • The many-to-many relationship in Project (via Users []User gorm:"many2many:user_projects;") confirms proper dependency mapping without circular references.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify model dependencies and their relationships.

# Test: Check model definitions and their relationships.
ast-grep --pattern $'type (User|Project|UserProject) struct {
  $$$
}'

# Test: Check for any circular dependencies between models.
rg -A 5 $'type (User|Project|UserProject) struct'

Length of output: 1132

api/request/request.go (1)

21-25: Verify the ProjectPermit type definition.

The struct uses model.ProjectPermit type. Let's verify its definition and usage.

✅ Verification successful

ProjectPermit type definition and usage are confirmed to be correct.

  • The ProjectPermit struct is defined in repository/model/model.go with fields ProjectID, ProjectName, and ProjectRole.
  • Its usage across the codebase (e.g., in api/request/request.go, controller, service, and DAO layers) is consistent with the definition.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify ProjectPermit type definition and its usage.

# Test: Check ProjectPermit type definition
ast-grep --pattern $'type ProjectPermit struct {
  $$$
}'

# Test: Check for any other usages of ProjectPermit
rg -A 5 $'ProjectPermit'

Length of output: 3349

router/router.go (1)

12-12: LGTM!

The integration of UserController and user routes is clean and well-structured.

Also applies to: 31-31

router/Auth.go (1)

12-14: LGTM! New authentication endpoints are well-structured.

The new methods and routes for registration, logout, and user info updates are properly implemented with appropriate middleware protection where needed.

Also applies to: 25-27

service/User.go (1)

19-29: Verify the GetUsers implementation logic.

The method name GetUsers suggests returning multiple users, but it's using FindByID which typically returns a single user. This seems inconsistent.

Consider either:

  1. Renaming the method to GetUser if it's meant to return a single user
  2. Modifying the implementation to fetch multiple users if that's the intended behavior
-func (userService *UserService) GetUsers(ctx context.Context, id int) ([]model.UserResponse, error) {
+func (userService *UserService) GetUser(ctx context.Context, id int) (*model.UserResponse, error) {
repository/model/model.go (1)

5-12: LGTM! Well-structured model definitions.

The model definitions are well-organized with appropriate GORM tags and relationships.

Also applies to: 13-17, 18-22

wire.go (1)

40-42: LGTM! Proper dependency injection setup.

The new user service and controller are correctly integrated into the wire dependency injection setup.

wire_gen.go (1)

39-41: LGTM! Dependencies are properly wired.

The dependency injection setup for userService and userController looks correct.

Also applies to: 47-47

pkg/ginx/ginx.go (6)

16-20: LGTM!

Good addition of middleware error checking to prevent further processing when errors exist.


23-23: LGTM!

Correct fix to pass request by reference for proper binding.


51-54: LGTM!

Good improvements:

  • Added middleware error checking.
  • Fixed request binding by reference.

Also applies to: 57-57


78-81: LGTM!

Good addition of middleware error checking.


96-99: LGTM!

Good addition of middleware error checking.


122-124: LGTM!

Good improvement to use appropriate binding methods based on the request method:

  • ShouldBindQuery for GET requests.
  • ShouldBind for other methods.

Comment on lines 17 to 20
type GetUserReq struct {
Role int `json:"role"`
Projecet_id int `json:"project_id"`
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix typo in field name Projecet_id.

The field name contains a typo and should be corrected to maintain consistency.

Apply this diff to fix the typo:

 type GetUserReq struct {
   Role        int `json:"role"`
-  Projecet_id int `json:"project_id"`
+  Project_id  int `json:"project_id"`
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type GetUserReq struct {
Role int `json:"role"`
Projecet_id int `json:"project_id"`
}
type GetUserReq struct {
Role int `json:"role"`
Project_id int `json:"project_id"`
}

Comment on lines 26 to 33
if req.Role != 2 {
return response.Response{
Msg: "无权限",
Code: 40001,
Data: nil,
}, nil

}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Replace hardcoded role check with constants.

The role check is hardcoded to value 2. This makes the code less maintainable and prone to errors.

Consider creating an enum or constants for roles:

+const (
+    ADMIN_ROLE = 2
+)

-    if req.Role != 2 {
+    if req.Role != ADMIN_ROLE {

Also applies to: 46-52

}, nil

}
userResponse, err := uc.service.GetUsers(ctx, req.Projecet_id)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix typo in field name.

The field name Projecet_id contains a typo.

-    userResponse, err := uc.service.GetUsers(ctx, req.Projecet_id)
+    userResponse, err := uc.service.GetUsers(ctx, req.Project_id)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
userResponse, err := uc.service.GetUsers(ctx, req.Projecet_id)
userResponse, err := uc.service.GetUsers(ctx, req.Project_id)

service/Auth.go Outdated
Comment on lines 62 to 71
func (s *AuthService) UpdateMyInfo(ctx context.Context, req request.UpdateUserReq) error {
var user model.User
user.Email = req.Email
user.Name = req.Name
err := s.userDAO.Update(ctx, &user)
if err != nil {
return err
}
return nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation and user existence check.

The UpdateMyInfo method should validate input data and check if the user exists before updating.

 func (s *AuthService) UpdateMyInfo(ctx context.Context, req request.UpdateUserReq) error {
+    // Validate input
+    if req.Email == "" || req.Name == "" {
+        return errors.New("email and name are required")
+    }
+
+    // Check if user exists
+    existingUser, err := s.userDAO.FindByEmail(ctx, req.Email)
+    if err != nil {
+        return err
+    }
+    if existingUser == nil {
+        return errors.New("user not found")
+    }
+
     var user model.User
+    user.ID = existingUser.ID
     user.Email = req.Email
     user.Name = req.Name
     err := s.userDAO.Update(ctx, &user)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *AuthService) UpdateMyInfo(ctx context.Context, req request.UpdateUserReq) error {
var user model.User
user.Email = req.Email
user.Name = req.Name
err := s.userDAO.Update(ctx, &user)
if err != nil {
return err
}
return nil
}
func (s *AuthService) UpdateMyInfo(ctx context.Context, req request.UpdateUserReq) error {
// Validate input
if req.Email == "" || req.Name == "" {
return errors.New("email and name are required")
}
// Check if user exists
existingUser, err := s.userDAO.FindByEmail(ctx, req.Email)
if err != nil {
return err
}
if existingUser == nil {
return errors.New("user not found")
}
var user model.User
user.ID = existingUser.ID
user.Email = req.Email
user.Name = req.Name
err := s.userDAO.Update(ctx, &user)
if err != nil {
return err
}
return nil
}

Comment on lines 118 to 128
func (c *AuthController) UpdateMyInfo(ctx *gin.Context, req request.UpdateUserReq) (response.Response, error) {
err := c.service.UpdateMyInfo(ctx, req)
if err != nil {
return response.Response{}, err
}
return response.Response{
Msg: "更新用户信息成功",
Code: 200,
Data: nil,
}, nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add claims validation for UpdateMyInfo.

The UpdateMyInfo method should validate user claims before updating information.

 func (c *AuthController) UpdateMyInfo(ctx *gin.Context, req request.UpdateUserReq) (response.Response, error) {
+    claims, err := ginx.GetClaims[jwt.UserClaims](ctx)
+    if err != nil {
+        return response.Response{
+            Msg:  "Invalid or expired token",
+            Code: 40001,
+            Data: nil,
+        }, err
+    }
+
     err := c.service.UpdateMyInfo(ctx, req)
     if err != nil {
-        return response.Response{}, err
+        return response.Response{
+            Msg:  "Failed to update user info",
+            Code: 40001,
+            Data: nil,
+        }, err
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (c *AuthController) UpdateMyInfo(ctx *gin.Context, req request.UpdateUserReq) (response.Response, error) {
err := c.service.UpdateMyInfo(ctx, req)
if err != nil {
return response.Response{}, err
}
return response.Response{
Msg: "更新用户信息成功",
Code: 200,
Data: nil,
}, nil
}
func (c *AuthController) UpdateMyInfo(ctx *gin.Context, req request.UpdateUserReq) (response.Response, error) {
claims, err := ginx.GetClaims[jwt.UserClaims](ctx)
if err != nil {
return response.Response{
Msg: "Invalid or expired token",
Code: 40001,
Data: nil,
}, err
}
err = c.service.UpdateMyInfo(ctx, req)
if err != nil {
return response.Response{
Msg: "Failed to update user info",
Code: 40001,
Data: nil,
}, err
}
return response.Response{
Msg: "更新用户信息成功",
Code: 200,
Data: nil,
}, nil
}

Comment on lines 68 to 76
func (d *UserDAO) FindByID(ctx context.Context, id int) ([]model.User, error) {
var users []model.User
err := d.DB.WithContext(ctx).Preload("Projects").Joins("JOIN user_projects ON user_projects.user_id = users.id").
Where("user_projects.project_id = ? AND user_projects.role = ?", id, 1).Find(&users).Error
if err != nil {
return nil, err
}
return users, nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance flexibility and error handling.

The function has the following issues:

  • The role value is hardcoded to 1, limiting reusability.
  • Missing error handling for gorm.ErrRecordNotFound.

Apply this diff to improve the function:

-func (d *UserDAO) FindByID(ctx context.Context, id int) ([]model.User, error) {
+func (d *UserDAO) FindByID(ctx context.Context, id int, role int) ([]model.User, error) {
 	var users []model.User
 	err := d.DB.WithContext(ctx).Preload("Projects").Joins("JOIN user_projects ON user_projects.user_id = users.id").
-		Where("user_projects.project_id = ? AND user_projects.role = ?", id, 1).Find(&users).Error
+		Where("user_projects.project_id = ? AND user_projects.role = ?", id, role).Find(&users).Error
 	if err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return nil, nil
+		}
 		return nil, err
 	}
 	return users, nil
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (d *UserDAO) FindByID(ctx context.Context, id int) ([]model.User, error) {
var users []model.User
err := d.DB.WithContext(ctx).Preload("Projects").Joins("JOIN user_projects ON user_projects.user_id = users.id").
Where("user_projects.project_id = ? AND user_projects.role = ?", id, 1).Find(&users).Error
if err != nil {
return nil, err
}
return users, nil
}
func (d *UserDAO) FindByID(ctx context.Context, id int, role int) ([]model.User, error) {
var users []model.User
err := d.DB.WithContext(ctx).Preload("Projects").
Joins("JOIN user_projects ON user_projects.user_id = users.id").
Where("user_projects.project_id = ? AND user_projects.role = ?", id, role).
Find(&users).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return users, nil
}

Comment on lines 103 to 117
func (d *UserDAO) ChangeProjectRole(ctx context.Context, userId int, projectPermit []model.ProjectPermit) error {
var user model.User
err := d.DB.WithContext(ctx).Preload("Projects").Where("user_id = ?", userId).First(&user).Error
if err != nil {
return errors.New("未找到该用户")
}
var userProject model.UserProject
for _, project := range projectPermit {
userProject.Role = project.ProjectRole
userProject.UserID = user.ID
userProject.ProjectID = project.ProjectID
d.DB.WithContext(ctx).Save(&userProject)
}
return nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix data consistency and error handling issues.

The function has several critical issues:

  • Missing transaction for batch updates.
  • Missing error handling for DB queries.
  • Incorrect user lookup using "user_id" field.

Apply this diff to improve the function:

 func (d *UserDAO) ChangeProjectRole(ctx context.Context, userId int, projectPermit []model.ProjectPermit) error {
 	var user model.User
-	err := d.DB.WithContext(ctx).Preload("Projects").Where("user_id = ?", userId).First(&user).Error
+	err := d.DB.WithContext(ctx).Preload("Projects").Where("id = ?", userId).First(&user).Error
 	if err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return errors.New("未找到该用户")
+		}
 		return errors.New("未找到该用户")
 	}
-	var userProject model.UserProject
-	for _, project := range projectPermit {
-		userProject.Role = project.ProjectRole
-		userProject.UserID = user.ID
-		userProject.ProjectID = project.ProjectID
-		d.DB.WithContext(ctx).Save(&userProject)
+
+	// Start transaction
+	tx := d.DB.WithContext(ctx).Begin()
+	if tx.Error != nil {
+		return tx.Error
+	}
+	defer func() {
+		if r := recover(); r != nil {
+			tx.Rollback()
+		}
+	}()
+
+	for _, project := range projectPermit {
+		var userProject model.UserProject
+		err := tx.Where("user_id = ? AND project_id = ?", user.ID, project.ProjectID).
+			FirstOrCreate(&userProject).Error
+		if err != nil {
+			tx.Rollback()
+			return err
+		}
+
+		userProject.Role = project.ProjectRole
+		if err := tx.Save(&userProject).Error; err != nil {
+			tx.Rollback()
+			return err
+		}
 	}
+
+	if err := tx.Commit().Error; err != nil {
+		return err
+	}
+
 	return nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (d *UserDAO) ChangeProjectRole(ctx context.Context, userId int, projectPermit []model.ProjectPermit) error {
var user model.User
err := d.DB.WithContext(ctx).Preload("Projects").Where("user_id = ?", userId).First(&user).Error
if err != nil {
return errors.New("未找到该用户")
}
var userProject model.UserProject
for _, project := range projectPermit {
userProject.Role = project.ProjectRole
userProject.UserID = user.ID
userProject.ProjectID = project.ProjectID
d.DB.WithContext(ctx).Save(&userProject)
}
return nil
}
func (d *UserDAO) ChangeProjectRole(ctx context.Context, userId int, projectPermit []model.ProjectPermit) error {
var user model.User
err := d.DB.WithContext(ctx).Preload("Projects").Where("id = ?", userId).First(&user).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("未找到该用户")
}
return errors.New("未找到该用户")
}
// Start transaction
tx := d.DB.WithContext(ctx).Begin()
if tx.Error != nil {
return tx.Error
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
for _, project := range projectPermit {
var userProject model.UserProject
err := tx.Where("user_id = ? AND project_id = ?", user.ID, project.ProjectID).
FirstOrCreate(&userProject).Error
if err != nil {
tx.Rollback()
return err
}
userProject.Role = project.ProjectRole
if err := tx.Save(&userProject).Error; err != nil {
tx.Rollback()
return err
}
}
if err := tx.Commit().Error; err != nil {
return err
}
return nil
}

Comment on lines 77 to 102
func (d *UserDAO) GetResponse(ctx context.Context, users []model.User) ([]model.UserResponse, error) {
var userResponses []model.UserResponse
for _, user := range users {
var projectPermits []model.ProjectPermit
for _, project := range user.Projects {
var userProject model.UserProject
d.DB.Where("user_id = ? AND project_id = ?", user.ID, project.ID).First(&userProject)

projectPermits = append(projectPermits, model.ProjectPermit{
ProjectID: project.ID,
ProjectName: project.ProjectName,
ProjectRole: userProject.Role,
})
}

userResponses = append(userResponses, model.UserResponse{
Name: user.Name,
UserID: user.ID,
Avatar: user.Avatar,
ProjectPermit: projectPermits,
Role: user.UserRole,
})
}

return userResponses, nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix N+1 query problem and add error handling.

The function has performance and reliability issues:

  • N+1 query problem: DB query inside loop.
  • Missing error handling for DB queries.
  • Missing context in DB queries.

Apply this diff to improve the function:

 func (d *UserDAO) GetResponse(ctx context.Context, users []model.User) ([]model.UserResponse, error) {
 	var userResponses []model.UserResponse
+	// Get all user IDs and project IDs for batch query
+	var userIDs []uint
+	var projectIDs []uint
+	for _, user := range users {
+		userIDs = append(userIDs, user.ID)
+		for _, project := range user.Projects {
+			projectIDs = append(projectIDs, project.ID)
+		}
+	}
+
+	// Batch query user_projects
+	var userProjects []model.UserProject
+	if err := d.DB.WithContext(ctx).Where("user_id IN ? AND project_id IN ?", userIDs, projectIDs).Find(&userProjects).Error; err != nil {
+		return nil, err
+	}
+
+	// Create a map for quick lookup
+	userProjectMap := make(map[string]model.UserProject)
+	for _, up := range userProjects {
+		key := fmt.Sprintf("%d-%d", up.UserID, up.ProjectID)
+		userProjectMap[key] = up
+	}
+
 	for _, user := range users {
 		var projectPermits []model.ProjectPermit
 		for _, project := range user.Projects {
-			var userProject model.UserProject
-			d.DB.Where("user_id = ? AND project_id = ?", user.ID, project.ID).First(&userProject)
+			key := fmt.Sprintf("%d-%d", user.ID, project.ID)
+			userProject, exists := userProjectMap[key]
+			if !exists {
+				continue
+			}
 
 			projectPermits = append(projectPermits, model.ProjectPermit{
 				ProjectID:   project.ID,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (d *UserDAO) GetResponse(ctx context.Context, users []model.User) ([]model.UserResponse, error) {
var userResponses []model.UserResponse
for _, user := range users {
var projectPermits []model.ProjectPermit
for _, project := range user.Projects {
var userProject model.UserProject
d.DB.Where("user_id = ? AND project_id = ?", user.ID, project.ID).First(&userProject)
projectPermits = append(projectPermits, model.ProjectPermit{
ProjectID: project.ID,
ProjectName: project.ProjectName,
ProjectRole: userProject.Role,
})
}
userResponses = append(userResponses, model.UserResponse{
Name: user.Name,
UserID: user.ID,
Avatar: user.Avatar,
ProjectPermit: projectPermits,
Role: user.UserRole,
})
}
return userResponses, nil
}
func (d *UserDAO) GetResponse(ctx context.Context, users []model.User) ([]model.UserResponse, error) {
var userResponses []model.UserResponse
// Get all user IDs and project IDs for batch query
var userIDs []uint
var projectIDs []uint
for _, user := range users {
userIDs = append(userIDs, user.ID)
for _, project := range user.Projects {
projectIDs = append(projectIDs, project.ID)
}
}
// Batch query user_projects
var userProjects []model.UserProject
if err := d.DB.WithContext(ctx).Where("user_id IN ? AND project_id IN ?", userIDs, projectIDs).Find(&userProjects).Error; err != nil {
return nil, err
}
// Create a map for quick lookup
userProjectMap := make(map[string]model.UserProject)
for _, up := range userProjects {
key := fmt.Sprintf("%d-%d", up.UserID, up.ProjectID)
userProjectMap[key] = up
}
for _, user := range users {
var projectPermits []model.ProjectPermit
for _, project := range user.Projects {
key := fmt.Sprintf("%d-%d", user.ID, project.ID)
userProject, exists := userProjectMap[key]
if !exists {
continue
}
projectPermits = append(projectPermits, model.ProjectPermit{
ProjectID: project.ID,
ProjectName: project.ProjectName,
ProjectRole: userProject.Role,
})
}
userResponses = append(userResponses, model.UserResponse{
Name: user.Name,
UserID: user.ID,
Avatar: user.Avatar,
ProjectPermit: projectPermits,
Role: user.UserRole,
})
}
return userResponses, nil
}

Copy link
Contributor

@sunjunnan79 sunjunnan79 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

加油写啊,写的完吗?写不完可以呼叫我

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (18)
pkg/jwt/jwt.go (1)

68-70: Improve field naming consistency and comments.

Consider these improvements:

  1. Rename UserRule to UserRole to match the parameter name in SetJWTToken.
  2. Make comment style consistent by adding periods to all comments.

Apply this diff:

-	Uid      uint   // 用户 ID
-	Email    string //用户名称
-	UserRule int
+	Uid      uint   // 用户 ID.
+	Email    string // 用户名称.
+	UserRole int    // 用户角色.
controller/User.go (3)

14-20: Use consistent naming and ensure a clear interface contract.
Your struct field is named "service UserService" while your constructor accepts a "*service.UserService". This might be confusing. Also validate that all methods in "service.UserService" match the "UserService" interface methods.


22-26: Consider dependency injection improvements.
The constructor ties the controller directly to the implementation in "service.UserService". If you want to keep it more flexible, consider depending on the interface instead of the concrete struct to improve testability.


47-68: Rename "UpdateUsers" to reflect single-user role updates.
The method updates one user's role, so "UpdateUser" or "UpdateUserRole" might be more precise. This improves clarity and consistency with "UpdateUserRoleReq".

api/response/response.go (1)

13-19: Fix spelling of "TotleNumber".
"TotleNumber" is likely a typo. Change it to "TotalNumber" for clarity and correctness.

Apply this diff to correct the field name:

-	TotleNumber   int                  `json:"totle_number"`
+	TotalNumber   int                  `json:"total_number"`
router/Project.go (1)

16-26: Consider adding input validation middleware.

While the routes are properly protected with authentication middleware, consider adding input validation middleware to ensure request data meets requirements before reaching the controller.

pkg/apikey/apikey.go (1)

12-27: Make token expiration configurable.

The token expiration time is hardcoded to 24 hours. Consider making this configurable through environment variables or configuration files for different environments.

router/router.go (1)

10-18: Improve parameter ordering for better readability.

Consider grouping related parameters together. Move Project controller next to User controller:

 func NewRouter(
   OAuth *controller.AuthController,
   User *controller.UserController,
+  Project *controller.ProjectController,
   AuthMiddleware *middleware.AuthMiddleware,
   corsMiddleware *middleware.CorsMiddleware,
   loggerMiddleware *middleware.LoggerMiddleware,
-  Project *controller.ProjectController,
 ) *gin.Engine {
service/User.go (2)

19-29: Consider adding input validation.

While the error handling is good, consider validating the project ID before making the DAO call.

 func (userService *UserService) GetUsers(ctx context.Context, id int) ([]model.UserResponse, error) {
+    if id <= 0 {
+        return nil, fmt.Errorf("invalid project ID: %d", id)
+    }
     users, err := userService.userDAO.FindByProjectID(ctx, id)

30-36: Add role validation and logging.

The method should validate the role value and consider adding logging for audit purposes.

 func (userService *UserService) UpdateUserRole(ctx context.Context, userId int, projectPermit []model.ProjectPermit, role int) error {
+    if userId <= 0 {
+        return fmt.Errorf("invalid user ID: %d", userId)
+    }
+    if role < 0 {
+        return fmt.Errorf("invalid role value: %d", role)
+    }
+    if len(projectPermit) == 0 {
+        return fmt.Errorf("project permits cannot be empty")
+    }
     err := userService.userDAO.ChangeProjectRole(ctx, userId, projectPermit, role)
service/service.go (1)

41-56: Consider implementing caching for frequently accessed data.

Both GetProjectList and Detail methods could benefit from caching to improve performance, especially if these endpoints are frequently accessed.

Consider implementing a caching layer using the existing Redis infrastructure:

  1. Cache project lists with appropriate TTL
  2. Implement cache invalidation on project updates
  3. Use cache-aside pattern for project details
repository/model/model.go (1)

7-12: Add indexes for frequently queried fields.

Consider adding indexes to improve query performance on frequently accessed fields.

-    Name     string    `gorm:"column:name;unique;not null"`
+    Name     string    `gorm:"column:name;unique;not null;index"`
-    Email    string    `gorm:"column:email;not null"`
+    Email    string    `gorm:"column:email;not null;index"`
controller/Project.go (2)

28-42: Improve error handling and response consistency.

Consider the following improvements:

  • Use consistent error messages in English.
  • Maintain consistent response structure between success and error cases.

Apply this diff:

 func (ctrl *ProjectController) GetProjectList(ctx *gin.Context) (response.Response, error) {
 	list, err := ctrl.service.GetProjectList(ctx)
 	if err != nil {
 		return response.Response{
 			Code: 400,
-			Msg:  "获取列表失败",
+			Msg:  "Failed to retrieve project list",
 			Data: nil,
 		}, err
 	}
 	return response.Response{
 		Data: list,
 		Code: 200,
-		Msg:  "获取列表成功",
+		Msg:  "Successfully retrieved project list",
 	}, nil
 }

43-70: Extract role constant and improve error messages.

The hardcoded role value reduces maintainability. Consider extracting it as a constant and improving error messages.

Apply this diff:

+const (
+    ADMIN_ROLE = 2
+)
+
 func (ctrl *ProjectController) Create(ctx *gin.Context, req request.CreateProject) (response.Response, error) {
 	token, err := ginx.GetClaims[jwt.UserClaims](ctx)
 	if err != nil {
 		return response.Response{
-			Msg:  "",
+			Msg:  "Invalid or expired token",
 			Code: 40001,
 			Data: nil,
 		}, err
 	}
-	if token.UserRule != 2 {
+	if token.UserRule != ADMIN_ROLE {
 		return response.Response{
 			Code: 400,
-			Msg:  "无权限",
+			Msg:  "Insufficient permissions: admin role required",
 		}, nil
 	}
controller/Auth.go (2)

95-117: Add descriptive error messages.

The error messages are empty, which makes debugging harder.

Apply this diff:

 func (c *AuthController) Logout(ctx *gin.Context) (response.Response, error) {
 	_, err := ginx.GetClaims[jwt.UserClaims](ctx)
 	if err != nil {
 		return response.Response{
-			Msg:  "",
+			Msg:  "Invalid or expired token",
 			Code: 40001,
 			Data: nil,
 		}, err
 	}
 	err = c.service.Logout(ctx)
 	if err != nil {
 		return response.Response{
-			Msg:  "",
+			Msg:  "Failed to logout user",
 			Code: 40001,
 			Data: nil,
 		}, err
 	}
 	return response.Response{
-		Msg:  "成功登出",
+		Msg:  "Successfully logged out",
 		Code: 200,
 		Data: nil,
 	}, nil
 }

118-136: Add error message for update failure.

The error response is empty, which makes debugging harder.

Apply this diff:

 	err = c.service.UpdateMyInfo(ctx, req, token.Uid)
 	if err != nil {
-		return response.Response{}, err
+		return response.Response{
+			Msg:  "Failed to update user information",
+			Code: 40001,
+			Data: nil,
+		}, err
 	}
 	return response.Response{
-		Msg:  "更新用户信息成功",
+		Msg:  "Successfully updated user information",
 		Code: 200,
 		Data: nil,
 	}, nil
repository/dao/user.go (2)

131-144: Optimize performance and improve error handling.

Consider the following improvements:

  • Use English error messages for better internationalization.
  • Avoid unnecessary intermediate slice creation.

Apply this diff:

 func (d *UserDAO) GetProjectList(ctx context.Context) ([]model.ProjectList, error) {
-	var projects []model.Project
-	if err := d.DB.WithContext(ctx).Find(&projects).Error; err != nil {
-		return nil, errors.New("查询数据库错误")
+	var projectList []model.ProjectList
+	if err := d.DB.WithContext(ctx).Model(&model.Project).Select("id as project_id, project_name").Find(&projectList).Error; err != nil {
+		return nil, errors.New("failed to query database")
 	}
-	var projectlist []model.ProjectList
-	for _, project := range projects {
-		projectlist = append(projectlist, model.ProjectList{
-			ProjectId:   project.ID,
-			ProjectName: project.ProjectName,
-		})
-	}
-	return projectlist, nil
+	return projectList, nil
 }

145-159: Improve error messages and add explicit transaction.

Consider the following improvements:

  • Use English error messages for better internationalization.
  • Add explicit transaction for atomic operations.

Apply this diff:

 func (d *UserDAO) CreateProject(ctx context.Context, project *model.Project) error {
-	if err := d.DB.WithContext(ctx).Create(project).Error; err != nil {
-		return errors.New("创建项目失败")
+	tx := d.DB.WithContext(ctx).Begin()
+	if tx.Error != nil {
+		return errors.New("failed to begin transaction")
 	}
+	defer func() {
+		if r := recover(); r != nil {
+			tx.Rollback()
+		}
+	}()
+
+	if err := tx.Create(project).Error; err != nil {
+		tx.Rollback()
+		return errors.New("failed to create project")
 	}
+
 	key, err := apikey.GenerateAPIKey(strconv.Itoa(int(project.ID)))
 	if err != nil {
-		return errors.New("生成apikey失败")
+		tx.Rollback()
+		return errors.New("failed to generate API key")
 	}
 	project.Apikey = key
-	if err := d.DB.WithContext(ctx).Save(project).Error; err != nil {
+	if err := tx.Save(project).Error; err != nil {
+		tx.Rollback()
 		return err
 	}
+
+	if err := tx.Commit().Error; err != nil {
+		return errors.New("failed to commit transaction")
+	}
+
 	return nil
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9143a0e and d1bd9c2.

📒 Files selected for processing (18)
  • api/request/request.go (1 hunks)
  • api/response/response.go (2 hunks)
  • controller/Auth.go (3 hunks)
  • controller/Project.go (1 hunks)
  • controller/User.go (1 hunks)
  • pkg/apikey/apikey.go (1 hunks)
  • pkg/jwt/jwt.go (2 hunks)
  • pkg/jwt/redis_handler.go (1 hunks)
  • repository/dao/dao.go (1 hunks)
  • repository/dao/user.go (2 hunks)
  • repository/model/model.go (1 hunks)
  • router/Project.go (1 hunks)
  • router/router.go (2 hunks)
  • service/Auth.go (3 hunks)
  • service/User.go (1 hunks)
  • service/service.go (1 hunks)
  • wire.go (1 hunks)
  • wire_gen.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • wire.go
  • service/Auth.go
🔇 Additional comments (14)
pkg/jwt/jwt.go (1)

47-56: LGTM! Clean integration of user role information.

The changes correctly integrate the user role information into the JWT claims while maintaining backward compatibility.

pkg/jwt/redis_handler.go (1)

66-68: LGTM! Clean propagation of user role information.

The changes correctly integrate with the updated JWT package while maintaining proper error handling.

repository/dao/dao.go (1)

9-9: Check for related constraints and dependencies.
Auto-migrating multiple models is convenient but make sure any necessary foreign key constraints or indexes are correctly created. Consider a more controlled migration flow if your schema evolves frequently.

api/response/response.go (1)

3-4: Import from “model” confirmed.
The import appears to be necessary for referencing "model.UserResponse" and is implemented correctly.

router/Project.go (1)

10-14: LGTM! Well-defined interface with consistent method signatures.

The ProjectController interface is well-structured with consistent method signatures, following the pattern of taking gin.Context and returning response.Response, error.

pkg/apikey/apikey.go (1)

28-37: LGTM! Proper signing method validation.

The ParseAPIKey function correctly validates the signing method before returning the token.

service/User.go (1)

10-17: LGTM! Well-structured service with proper dependency injection.

The UserService struct is well-designed with clear dependencies and a clean constructor function.

service/service.go (1)

11-18: Remove unused Count struct.

The Count struct appears to be unused in the codebase. Consider removing it if it's not needed.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for usages of the Count struct
rg "Count\s*{|Count\s*struct" -A 2

Length of output: 152


🏁 Script executed:

#!/bin/bash
# First, search for the Count struct declaration (definition) in the codebase.
rg "type Count\s*\{" -A 2

# Next, search for any references to the Count identifier to see if it is used elsewhere.
# This search includes any usage of the word 'Count' excluding comments might appear.
rg "\bCount\b"

Length of output: 83


Unused Count Struct Detected
Our search results show that the only occurrence of the Count struct is its declaration in service/service.go with no additional references elsewhere. It appears to be unused in the codebase and can be safely removed.

wire_gen.go (1)

39-49: LGTM! Proper dependency initialization order.

The initialization order is correct, with dependencies being created before they are needed. The router initialization properly includes all required controllers.

controller/Project.go (1)

14-21: LGTM! Well-structured interface design.

The interface design follows good separation of concerns and has clear method signatures.

controller/Auth.go (1)

21-26: LGTM! Clear interface definition.

The interface is well-defined with clear method signatures for authentication operations.

repository/dao/user.go (3)

71-79: Enhance flexibility and error handling.

The function has the following issues:

  • The role value is hardcoded to 1, limiting reusability.
  • Missing error handling for gorm.ErrRecordNotFound.

89-114: Fix N+1 query problem and add error handling.

The function has performance and reliability issues:

  • N+1 query problem: DB query inside loop.
  • Missing error handling for DB queries.

115-130: Fix data consistency and error handling issues.

The function has several critical issues:

  • Missing transaction for batch updates.
  • Missing error handling for DB queries.
  • Incorrect user lookup using "user_id" field.

Comment on lines +27 to +46
func (uc *UserController) GetUsers(ctx *gin.Context, req request.GetUserReq) (response.Response, error) {
if req.Role != 2 {
return response.Response{
Msg: "无权限",
Code: 40001,
Data: nil,
}, nil

}
userResponse, err := uc.service.GetUsers(ctx, req.Project_id)
if err != nil {
return response.Response{}, err
}

return response.Response{
Msg: "获取成功",
Code: 200,
Data: userResponse,
}, nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Validate role checks and messages.
"req.Role != 2 → 无权限" is a hard-coded comparison. Consider using configurable role constants or enumerations to avoid magic numbers. Also review the response message to see if a localized or more descriptive error would be better.

"github.com/dgrijalva/jwt-go"
)

var SecretKey = []byte("Muxi-Team-Auditor-Backend")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Move secret key to configuration.

Hardcoding sensitive values like secret keys is a security risk. Consider moving this to environment variables or a secure configuration management system.

Comment on lines +17 to +20
type GetUserReq struct {
Role int `json:"role"`
Project_id int `json:"project_id"`
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use consistent field naming convention.

The Project_id field uses snake_case while other fields use camelCase. Consider using consistent camelCase for all JSON field names:

 type GetUserReq struct {
   Role       int `json:"role"`
-  Project_id int `json:"project_id"`
+  ProjectId  int `json:"projectId"`
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type GetUserReq struct {
Role int `json:"role"`
Project_id int `json:"project_id"`
}
type GetUserReq struct {
Role int `json:"role"`
ProjectId int `json:"projectId"`
}

Comment on lines +12 to +34
type UpdateUserReq struct {
Name string `json:"name"`
Email string `json:"email"`
Avatar string `json:"avatar"`
}
type GetUserReq struct {
Role int `json:"role"`
Project_id int `json:"project_id"`
}
type UpdateUserRoleReq struct {
Role int `json:"role"`
UserId int `json:"user_id"`
ProjectPermit []model.ProjectPermit `json:"project_permit"`
}
type CreateProject struct {
Name string `json:"name"`
Logo string `json:"logo"`
AudioRule string `json:"audio_rule"`
UserIds []uint `json:"user_ids"`
}
type GetProjectDetail struct {
ProjectId uint `json:"project_id"`
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation tags for request fields.

Consider adding validation tags to ensure request data meets requirements. For example:

  • Email format validation
  • Required fields
  • Min/max length for strings
  • Range validation for numeric fields

Example:

 type UpdateUserReq struct {
-  Name   string `json:"name"`
-  Email  string `json:"email"`
-  Avatar string `json:"avatar"`
+  Name   string `json:"name" binding:"required,min=1,max=100"`
+  Email  string `json:"email" binding:"required,email"`
+  Avatar string `json:"avatar" binding:"url"`
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type UpdateUserReq struct {
Name string `json:"name"`
Email string `json:"email"`
Avatar string `json:"avatar"`
}
type GetUserReq struct {
Role int `json:"role"`
Project_id int `json:"project_id"`
}
type UpdateUserRoleReq struct {
Role int `json:"role"`
UserId int `json:"user_id"`
ProjectPermit []model.ProjectPermit `json:"project_permit"`
}
type CreateProject struct {
Name string `json:"name"`
Logo string `json:"logo"`
AudioRule string `json:"audio_rule"`
UserIds []uint `json:"user_ids"`
}
type GetProjectDetail struct {
ProjectId uint `json:"project_id"`
}
type UpdateUserReq struct {
Name string `json:"name" binding:"required,min=1,max=100"`
Email string `json:"email" binding:"required,email"`
Avatar string `json:"avatar" binding:"url"`
}
type GetUserReq struct {
Role int `json:"role"`
Project_id int `json:"project_id"`
}
type UpdateUserRoleReq struct {
Role int `json:"role"`
UserId int `json:"user_id"`
ProjectPermit []model.ProjectPermit `json:"project_permit"`
}
type CreateProject struct {
Name string `json:"name"`
Logo string `json:"logo"`
AudioRule string `json:"audio_rule"`
UserIds []uint `json:"user_ids"`
}
type GetProjectDetail struct {
ProjectId uint `json:"project_id"`
}

Comment on lines +23 to +40
func (s *ProjectService) Create(ctx context.Context, name string, logo string, audioRule string, ids []uint) error {

users, err := s.userDAO.FindByUserIDs(ctx, ids)
if err != nil {
return err
}
project := model.Project{
ProjectName: name,
Logo: logo,
AudioRule: audioRule,
Users: users,
}
err = s.userDAO.CreateProject(ctx, &project)
if err != nil {
return err
}
return nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add transaction handling and input validation.

The Create method should use a transaction to ensure atomic operations, and validate input parameters.

 func (s *ProjectService) Create(ctx context.Context, name string, logo string, audioRule string, ids []uint) error {
+    if name == "" {
+        return fmt.Errorf("project name cannot be empty")
+    }
+    if len(ids) == 0 {
+        return fmt.Errorf("user IDs cannot be empty")
+    }
+
+    tx := s.userDAO.DB.Begin()
+    defer func() {
+        if r := recover(); r != nil {
+            tx.Rollback()
+        }
+    }()
 
     users, err := s.userDAO.FindByUserIDs(ctx, ids)
     if err != nil {
+        tx.Rollback()
         return err
     }
     project := model.Project{
         ProjectName: name,
         Logo:        logo,
         AudioRule:   audioRule,
         Users:       users,
     }
-    err = s.userDAO.CreateProject(ctx, &project)
+    err = s.userDAO.CreateProject(ctx, tx, &project)
     if err != nil {
+        tx.Rollback()
         return err
     }
+    return tx.Commit().Error
-    return nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *ProjectService) Create(ctx context.Context, name string, logo string, audioRule string, ids []uint) error {
users, err := s.userDAO.FindByUserIDs(ctx, ids)
if err != nil {
return err
}
project := model.Project{
ProjectName: name,
Logo: logo,
AudioRule: audioRule,
Users: users,
}
err = s.userDAO.CreateProject(ctx, &project)
if err != nil {
return err
}
return nil
}
func (s *ProjectService) Create(ctx context.Context, name string, logo string, audioRule string, ids []uint) error {
if name == "" {
return fmt.Errorf("project name cannot be empty")
}
if len(ids) == 0 {
return fmt.Errorf("user IDs cannot be empty")
}
tx := s.userDAO.DB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
users, err := s.userDAO.FindByUserIDs(ctx, ids)
if err != nil {
tx.Rollback()
return err
}
project := model.Project{
ProjectName: name,
Logo: logo,
AudioRule: audioRule,
Users: users,
}
err = s.userDAO.CreateProject(ctx, tx, &project)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}

Comment on lines +43 to 47
type Item struct {
gorm.Model
Status int `gorm:"column:status;not null"` //0:未审核1:通过2:否决
ProjectId uint `gorm:"column:project_id;not null"`
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add enum validation for status field.

The status field in Item model should have proper validation for enum values.

 type Item struct {
     gorm.Model
-    Status    int  `gorm:"column:status;not null"` //0:未审核1:通过2:否决
+    Status    int  `gorm:"column:status;not null;check:status IN (0,1,2)"` //0:未审核1:通过2:否决
     ProjectId uint `gorm:"column:project_id;not null"`
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type Item struct {
gorm.Model
Status int `gorm:"column:status;not null"` //0:未审核1:通过2:否决
ProjectId uint `gorm:"column:project_id;not null"`
}
type Item struct {
gorm.Model
Status int `gorm:"column:status;not null;check:status IN (0,1,2)"` //0:未审核1:通过2:否决
ProjectId uint `gorm:"column:project_id;not null"`
}

Comment on lines +13 to +21
type Project struct {
gorm.Model
ProjectName string `gorm:"column:project_name;not null"`
Logo string `gorm:"column:logo;not null"`
AudioRule string `gorm:"column:audio_rule;not null"`
Users []User `gorm:"many2many:user_projects;"`
Items []Item
Apikey string `gorm:"column:apikey;not null"`
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation and improve database schema.

The Project model could benefit from additional constraints and indexes.

 type Project struct {
     gorm.Model
-    ProjectName string `gorm:"column:project_name;not null"`
+    ProjectName string `gorm:"column:project_name;not null;index"`
     Logo        string `gorm:"column:logo;not null"`
     AudioRule   string `gorm:"column:audio_rule;not null"`
     Users       []User `gorm:"many2many:user_projects;"`
     Items       []Item
-    Apikey      string `gorm:"column:apikey;not null"`
+    Apikey      string `gorm:"column:apikey;not null;uniqueIndex"`
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type Project struct {
gorm.Model
ProjectName string `gorm:"column:project_name;not null"`
Logo string `gorm:"column:logo;not null"`
AudioRule string `gorm:"column:audio_rule;not null"`
Users []User `gorm:"many2many:user_projects;"`
Items []Item
Apikey string `gorm:"column:apikey;not null"`
}
type Project struct {
gorm.Model
ProjectName string `gorm:"column:project_name;not null;index"`
Logo string `gorm:"column:logo;not null"`
AudioRule string `gorm:"column:audio_rule;not null"`
Users []User `gorm:"many2many:user_projects;"`
Items []Item
Apikey string `gorm:"column:apikey;not null;uniqueIndex"`
}

Comment on lines +71 to +95
func (ctrl *ProjectController) Detail(ctx *gin.Context, req request.GetProjectDetail) (response.Response, error) {
_, err := ginx.GetClaims[jwt.UserClaims](ctx)
if err != nil {
return response.Response{
Msg: "",
Code: 40001,
Data: nil,
}, err
}
detail, err := ctrl.service.Detail(ctx, req.ProjectId)
if err != nil {
return response.Response{
Msg: "",
Code: 40001,
Data: nil,
}, err
}

return response.Response{
Code: 200,
Msg: "获取成功",
Data: detail,
}, nil

}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling and utilize claims.

The claims validation is performed but not utilized, and error messages are empty.

Apply this diff:

 func (ctrl *ProjectController) Detail(ctx *gin.Context, req request.GetProjectDetail) (response.Response, error) {
-	_, err := ginx.GetClaims[jwt.UserClaims](ctx)
+	claims, err := ginx.GetClaims[jwt.UserClaims](ctx)
 	if err != nil {
 		return response.Response{
-			Msg:  "",
+			Msg:  "Invalid or expired token",
 			Code: 40001,
 			Data: nil,
 		}, err
 	}
+	
+	// Log access for audit trail
+	log.Printf("User %d accessed project details for project %d", claims.Uid, req.ProjectId)
+	
 	detail, err := ctrl.service.Detail(ctx, req.ProjectId)
 	if err != nil {
 		return response.Response{
-			Msg:  "",
+			Msg:  "Failed to retrieve project details",
 			Code: 40001,
 			Data: nil,
 		}, err
 	}
 	return response.Response{
 		Code: 200,
-		Msg:  "获取成功",
+		Msg:  "Successfully retrieved project details",
 		Data: detail,
 	}, nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (ctrl *ProjectController) Detail(ctx *gin.Context, req request.GetProjectDetail) (response.Response, error) {
_, err := ginx.GetClaims[jwt.UserClaims](ctx)
if err != nil {
return response.Response{
Msg: "",
Code: 40001,
Data: nil,
}, err
}
detail, err := ctrl.service.Detail(ctx, req.ProjectId)
if err != nil {
return response.Response{
Msg: "",
Code: 40001,
Data: nil,
}, err
}
return response.Response{
Code: 200,
Msg: "获取成功",
Data: detail,
}, nil
}
func (ctrl *ProjectController) Detail(ctx *gin.Context, req request.GetProjectDetail) (response.Response, error) {
claims, err := ginx.GetClaims[jwt.UserClaims](ctx)
if err != nil {
return response.Response{
Msg: "Invalid or expired token",
Code: 40001,
Data: nil,
}, err
}
// Log access for audit trail
log.Printf("User %d accessed project details for project %d", claims.Uid, req.ProjectId)
detail, err := ctrl.service.Detail(ctx, req.ProjectId)
if err != nil {
return response.Response{
Msg: "Failed to retrieve project details",
Code: 40001,
Data: nil,
}, err
}
return response.Response{
Code: 200,
Msg: "Successfully retrieved project details",
Data: detail,
}, nil
}

Comment on lines +160 to +191
func (d *UserDAO) GetProjectDetails(ctx context.Context, id uint) (response.GetDetailResp, error) {
var project model.Project
err := d.DB.WithContext(ctx).Preload("Items").Preload("Users").First(&project, id).Error
if err != nil {
return response.GetDetailResp{}, err
}
countMap := map[int]int{
0: 0,
1: 0,
2: 0,
}
for _, item := range project.Items {
countMap[item.Status]++
}
var users []model.UserResponse
for _, user := range project.Users {
users = append(users, model.UserResponse{
Name: user.Name,
UserID: user.ID,
Avatar: user.Avatar,
})
}

re := response.GetDetailResp{
TotleNumber: countMap[0] + countMap[1] + countMap[2],
CurrentNumber: countMap[0],
Apikey: project.Apikey,
AuditRule: project.AudioRule,
Members: users,
}
return re, nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix typo and improve error handling.

The function has the following issues:

  • Typo in field name "TotleNumber".
  • Missing error handling for gorm.ErrRecordNotFound.

Apply this diff:

 func (d *UserDAO) GetProjectDetails(ctx context.Context, id uint) (response.GetDetailResp, error) {
 	var project model.Project
 	err := d.DB.WithContext(ctx).Preload("Items").Preload("Users").First(&project, id).Error
 	if err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			return response.GetDetailResp{}, errors.New("project not found")
+		}
 		return response.GetDetailResp{}, err
 	}
 	countMap := map[int]int{
@@ -183,7 +186,7 @@
 
 	re := response.GetDetailResp{
-		TotleNumber:   countMap[0] + countMap[1] + countMap[2],
+		TotalNumber:   countMap[0] + countMap[1] + countMap[2],
 		CurrentNumber: countMap[0],
 		Apikey:        project.Apikey,
 		AuditRule:     project.AudioRule,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (d *UserDAO) GetProjectDetails(ctx context.Context, id uint) (response.GetDetailResp, error) {
var project model.Project
err := d.DB.WithContext(ctx).Preload("Items").Preload("Users").First(&project, id).Error
if err != nil {
return response.GetDetailResp{}, err
}
countMap := map[int]int{
0: 0,
1: 0,
2: 0,
}
for _, item := range project.Items {
countMap[item.Status]++
}
var users []model.UserResponse
for _, user := range project.Users {
users = append(users, model.UserResponse{
Name: user.Name,
UserID: user.ID,
Avatar: user.Avatar,
})
}
re := response.GetDetailResp{
TotleNumber: countMap[0] + countMap[1] + countMap[2],
CurrentNumber: countMap[0],
Apikey: project.Apikey,
AuditRule: project.AudioRule,
Members: users,
}
return re, nil
}
func (d *UserDAO) GetProjectDetails(ctx context.Context, id uint) (response.GetDetailResp, error) {
var project model.Project
err := d.DB.WithContext(ctx).Preload("Items").Preload("Users").First(&project, id).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return response.GetDetailResp{}, errors.New("project not found")
}
return response.GetDetailResp{}, err
}
countMap := map[int]int{
0: 0,
1: 0,
2: 0,
}
for _, item := range project.Items {
countMap[item.Status]++
}
var users []model.UserResponse
for _, user := range project.Users {
users = append(users, model.UserResponse{
Name: user.Name,
UserID: user.ID,
Avatar: user.Avatar,
})
}
re := response.GetDetailResp{
TotalNumber: countMap[0] + countMap[1] + countMap[2],
CurrentNumber: countMap[0],
Apikey: project.Apikey,
AuditRule: project.AudioRule,
Members: users,
}
return re, nil
}

@cqhasy
Copy link
Collaborator Author

cqhasy commented Feb 8, 2025

关于project的功能实现

Data: userResponse,
}, nil
}
func (uc *UserController) UpdateUsers(ctx *gin.Context, req request.UpdateUserRoleReq) (response.Response, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

有中间件已经解决了这个userClaims的问题

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

直接用ginx.WrapClaimsAndReq泛型函数应该就可以实现的

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

那个uc是直接赋值好了的,可以直接调用。

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

你去看看ginx里面那几个函数的说明应该就能明白

@sunjunnan79
Copy link
Contributor

类似这样的做法:func (h *GradeHandler) RegisterRoutes(s *gin.RouterGroup, authMiddleware gin.HandlerFunc) {
sg := s.Group("/grade")
//这里有三类路由,分别是ginx.WrapClaimsAndReq()有参数且要验证
sg.GET("/getGradeByTerm", authMiddleware, ginx.WrapClaimsAndReq(h.GetGradeByTerm))
sg.GET("/getGradeScore", authMiddleware, ginx.WrapClaims(h.GetGradeScore))

}

// GradeByTerm 查询按学年和学期的成绩
// @summary 查询按学年和学期的成绩
// @description 根据学年号和学期号获取用户的成绩
// @tags 成绩
// @accept json
// @produce json
// @param xnm query int true "学年号(如 2023 表示 2023~2024 学年)"
// @param xqm query int true "学期号(1 表示第一学期,2 表示第二学期)"
// @success 200 {object} web.Response{data=GetGradeByTermResp} "成功返回学年和学期的成绩信息"
// @failure 500 {object} web.Response "系统异常,获取失败"
// @router /grade/getGradeByTerm [get]
func (h *GradeHandler) GetGradeByTerm(ctx *gin.Context, req GetGradeByTermReq, uc ijwt.UserClaims) (web.Response, error) {
grades, err := h.GradeClient.GetGradeByTerm(ctx, &gradev1.GetGradeByTermReq{
StudentId: uc.StudentId,
Xnm: req.Xnm,
Xqm: req.Xqm,
})
if err != nil {
return web.Response{}, errs.GET_GRADE_BY_TERM_ERROR(err)
}

var resp GetGradeByTermResp
for _, grade := range grades.Grades {
	resp.Grades = append(resp.Grades, Grade{
		Kcmc:                grade.Kcmc,                // 课程名
		Xf:                  grade.Xf,                  // 学分
		Jd:                  grade.Jd,                  //绩点
		Cj:                  grade.Cj,                  // 总成绩
		Kcxzmc:              grade.Kcxzmc,              // 课程性质名称 比如专业主干课程/通识必修课
		Kclbmc:              grade.Kclbmc,              // 课程类别名称,比如专业课/公共课
		Kcbj:                grade.Kcbj,                // 课程标记,比如主修/辅修
		RegularGradePercent: grade.RegularGradePercent, // 平时分占比
		RegularGrade:        grade.RegularGrade,        // 平时分分数
		FinalGradePercent:   grade.FinalGradePercent,   // 期末占比
		FinalGrade:          grade.FinalGrade,          // 期末分数
	})
}

//这里做了一个异步的增加用户的feedCount
go func() {
	ct := context.Background()
	_, err := h.CounterClient.AddCounter(ct, &counterv1.AddCounterReq{StudentId: uc.StudentId})
	if err != nil {
		h.l.Error("增加用户feedCount失败:", logger.Error(err))
	}
}()
return web.Response{
	Msg:  fmt.Sprintf("获取%d~%d学年第%d学期成绩成功!", req.Xnm, req.Xnm+1, req.Xqm),
	Data: resp,
}, nil

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants