Im developing web app where users can create skill-sharing session and leave feedbacks…
- User
Im developing web app where users can create skill-sharing session and leave feedbacks to sessions they participated in. Upgrade my implementation to production level and explain how to test it. I already wrote repository files, model files, handlers etc. The problematic parts of my server is presented below:
routes.go: // Moderator routes moderator := api.Group("/moderator") moderator.Use(middleware.RoleAuthMiddleware("moderator")) { moderator.DELETE("/sessions/:id", sessionController.Delete) //moderator.DELETE("/feedback/:id", feedbackController.Delete) }
// Session routes sessions := api.Group("/sessions") { sessions.GET("", sessionController.GetAll) sessions.GET("/:id", sessionController.GetByID) sessions.POST("", sessionController.Create) sessions.PUT("/:id", sessionController.Update) sessions.DELETE("/:id", sessionController.Delete) sessions.GET("/:id/participants", sessionController.GetParticipants) // Endpoints для Join/Leave сессии sessions.POST("/:id/join", sessionController.JoinSession) sessions.POST("/:id/leave", sessionController.LeaveSession) // Endpoints для отзывов/рейтингов feedback := sessions.Group("/:id/feedback") { feedback.POST("", feedbackController.CreateFeedback) feedback.GET("", feedbackController.GetFeedback) } } } return r }jwt_middleware.go: // JWTAuthMiddleware проверяет валидность JWT токена func JWTAuthMiddleware() gin.HandlerFunc { jwtCfg := config.GetJWTConfig()
return func(c *gin.Context) { // Получаем токен из заголовка Authorization authHeader := c.GetHeader("Authorization") if authHeader == "" { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"}) return } // Проверяем формат "Bearer <token>" parts := strings.Split(authHeader, " ") if len(parts) != 2 || parts[0] != "Bearer" { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer <token>"}) return } tokenString := parts[1] // Парсим и верифицируем токен token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { // Проверяем, что используется правильный алгоритм if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(jwtCfg.SecretKey), nil }) if err != nil { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token: " + err.Error()}) return } // Проверяем валидность токена if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { // Проверяем срок действия токена if float64(time.Now().Unix()) > claims["exp"].(float64) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"}) return } // Получаем ID пользователя из токена userIDStr, ok := claims["user_id"].(string) if !ok { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims"}) return } userID, err := uuid.Parse(userIDStr) if err != nil { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid user ID in token"}) return } // Сохраняем данные пользователя в контексте Gin c.Set("userID", userID) c.Set("email", claims["email"].(string)) c.Set("role", claims["role"].(string)) c.Next() } else { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) return } }}
session_controller.go: // Create handles POST /sessions func (c *SessionController) Create(ctx *gin.Context) { // ИСПРАВИТЬ МЕТОД var req models.SessionRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return }
// For demo purposes - in a real app, get the user ID from auth context creatorID, err := uuid.Parse(ctx.Query("creator_id")) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid creator ID"}) return } session, err := c.repo.Create(creatorID, req) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } ctx.JSON(http.StatusCreated, session)}
feedback_controller.go: // CreateFeedback обрабатывает POST /sessions/:id/feedback func (c *FeedbackController) CreateFeedback(ctx *gin.Context) { sessionIDStr := ctx.Param("id") sessionID, err := uuid.Parse(sessionIDStr) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session ID"}) return }
// Предположим, что middleware JWT кладёт в контекст идентификатор пользователя под ключом "user_id" userIDStr, exists := ctx.Get("user_id") // ЗАМЕНИТЬ НА userID? if !exists { ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) return } userID, err := uuid.Parse(userIDStr.(string)) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"}) return } var req models.FeedbackRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } feedback, err := c.repo.CreateFeedback(req, sessionID, userID) if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } ctx.JSON(http.StatusCreated, feedback)}
Assistant
Okay, let's upgrade your Go web application components for production readiness and discuss testing strategies.
Production-Level Improvements
Here's a breakdown of improvements focusing on security, robustness, maintainability, and consistency:
1. Constants for Context Keys and Roles
Avoid using "magic strings" for context keys and roles. Define constants.
// pkg/middleware/constants.go (or a relevant shared package) package middleware const ( ContextUserIDKey = "userID" ContextEmailKey = "email" ContextRoleKey = "role" ) const ( RoleUser = "user" // Example basic role RoleModerator = "moderator" RoleAdmin = "admin" )2. Enhanced
jwt_middleware.go- Use Constants: Replace string literals with the defined constants.
- Configuration Loading: Load JWT config once when creating the middleware, not on every request (assuming
GetJWTConfigisn't already heavily cached). - Logging: Add server-side logging for token validation errors. This is crucial for debugging in production.
- Type Safety: Ensure
userIDis consistently stored and retrieved asuuid.UUID.
// pkg/middleware/jwt_middleware.go package middleware import ( "fmt" "log" // Or your preferred logging library "net/http" "strings" "time" "your_project/pkg/config" // Adjust import path "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" // Use v5 or latest stable "github.com/google/uuid" ) // JWTAuthMiddleware creates a Gin middleware for JWT authentication and authorization. func JWTAuthMiddleware(jwtCfg config.JWTConfig) gin.HandlerFunc { jwtSecret := []byte(jwtCfg.SecretKey) // Cache the secret key return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader == "" { log.Printf("JWTAuthMiddleware: Missing Authorization header from %s", c.ClientIP()) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"}) return } parts := strings.Split(authHeader, " ") if len(parts) != 2 || parts[0] != "Bearer" { log.Printf("JWTAuthMiddleware: Invalid Authorization header format from %s", c.ClientIP()) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer <token>"}) return } tokenString := parts[1] token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return jwtSecret, nil }) if err != nil { // Log the specific parsing error log.Printf("JWTAuthMiddleware: Token parsing error from %s: %v", c.ClientIP(), err) // Check for specific JWT error types for potentially different client messages if errors.Is(err, jwt.ErrTokenMalformed) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Malformed token"}) } else if errors.Is(err, jwt.ErrTokenSignatureInvalid) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token signature"}) } else if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired or not valid yet"}) } else { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) } return } if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { // Check expiration explicitly (though token.Valid should cover it) // jwt/v5 handles 'exp' check automatically if present during Parse // if exp, ok := claims["exp"].(float64); ok { // if float64(time.Now().Unix()) > exp { // log.Printf("JWTAuthMiddleware: Token expired for claims %v from %s", claims, c.ClientIP()) // c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"}) // return // } // } else { // log.Printf("JWTAuthMiddleware: Missing 'exp' claim for claims %v from %s", claims, c.ClientIP()) // c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims (missing exp)"}) // return // } // --- Get User ID --- userIDStr, ok := claims[ContextUserIDKey].(string) // Expect user_id to be a string in the token if !ok { log.Printf("JWTAuthMiddleware: Missing or invalid type for '%s' claim from %s", ContextUserIDKey, c.ClientIP()) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims (user_id)"}) return } userID, err := uuid.Parse(userIDStr) if err != nil { log.Printf("JWTAuthMiddleware: Cannot parse '%s' claim '%s' as UUID from %s: %v", ContextUserIDKey, userIDStr, c.ClientIP(), err) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid user ID format in token"}) return } // --- Get Email (Optional but good practice) --- email, ok := claims[ContextEmailKey].(string) if !ok { // Decide if email is mandatory in the token log.Printf("JWTAuthMiddleware: Warning - Missing or invalid type for '%s' claim from %s", ContextEmailKey, c.ClientIP()) // Don't necessarily abort if email is optional } // --- Get Role --- role, ok := claims[ContextRoleKey].(string) if !ok { log.Printf("JWTAuthMiddleware: Missing or invalid type for '%s' claim from %s", ContextRoleKey, c.ClientIP()) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims (role)"}) return } // Store strongly-typed values in context c.Set(ContextUserIDKey, userID) // Store as uuid.UUID c.Set(ContextEmailKey, email) // Store as string c.Set(ContextRoleKey, role) // Store as string log.Printf("JWTAuthMiddleware: User %s (%s) authenticated with role %s", userID, email, role) // Example log c.Next() } else { log.Printf("JWTAuthMiddleware: Token deemed invalid (claims type: %T, token.Valid: %t) from %s", token.Claims, token.Valid, c.ClientIP()) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) return } } } // RoleAuthMiddleware checks if the user has the required role. // Assumes JWTAuthMiddleware runs first and sets the role in the context. func RoleAuthMiddleware(requiredRole string) gin.HandlerFunc { return func(c *gin.Context) { roleValue, exists := c.Get(ContextRoleKey) if !exists { log.Printf("RoleAuthMiddleware: Role key '%s' not found in context for client %s", ContextRoleKey, c.ClientIP()) c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Access forbidden: Role information missing"}) return } role, ok := roleValue.(string) if !ok { log.Printf("RoleAuthMiddleware: Role key '%s' in context is not a string for client %s", ContextRoleKey, c.ClientIP()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal server error: Invalid role data"}) // Should not happen if JWT middleware is correct return } // Basic role check - could be expanded for hierarchical roles if role != requiredRole { log.Printf("RoleAuthMiddleware: Access denied for user %s. Required role: '%s', User role: '%s'", c.GetString(ContextEmailKey), requiredRole, role) // Log email or ID c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": fmt.Sprintf("Access forbidden: Requires '%s' role", requiredRole)}) return } log.Printf("RoleAuthMiddleware: Role '%s' authorized for user %s", requiredRole, c.GetString(ContextEmailKey)) c.Next() } }3. Refined
routes.go- Apply JWT Middleware: Apply the JWT middleware to groups that require authentication.
- Authorization Strategy:
- The moderator delete (
/moderator/sessions/:id) is correctly protected by role. - The general delete (
/sessions/:id) needs careful consideration. Who can delete?- Option A (Creator Only): The
sessionController.Deletehandler should check if theuserIDfrom the context matches the session'screator_id. - Option B (Creator or Moderator): The handler checks if the user is the creator OR if their role (from context) is
moderator. - Option C (Remove General Delete): Only allow deletion via the moderator endpoint. This is simplest but might be too restrictive.
- Option A (Creator Only): The
- Let's assume Option A for the general route, and the moderator route provides the override.
- The moderator delete (
- Consistency: Ensure middleware is applied correctly.
// cmd/server/routes.go (or equivalent) package main // Or your router package import ( "your_project/pkg/config" // Adjust import paths "your_project/pkg/controllers" "your_project/pkg/middleware" "your_project/pkg/repositories" // Assuming you have these "github.com/gin-gonic/gin" // "gorm.io/gorm" // Example DB handle if needed here ) func SetupRouter(/* db *gorm.DB */) *gin.Engine { // Pass dependencies if needed r := gin.Default() // Or gin.New() with custom logging/recovery middleware // --- Dependencies (Example - use proper Dependency Injection) --- // repo := repositories.NewSessionRepository(db) // sessionController := controllers.NewSessionController(repo) // feedbackRepo := repositories.NewFeedbackRepository(db) // feedbackController := controllers.NewFeedbackController(feedbackRepo) // Assume controllers are initialized here // Load JWT Config jwtCfg := config.GetJWTConfig() // Load config once // --- Middleware --- jwtAuth := middleware.JWTAuthMiddleware(jwtCfg) moderatorAuth := middleware.RoleAuthMiddleware(middleware.RoleModerator) // API Group api := r.Group("/api/v1") // Use API versioning { // Public routes (if any) - e.g., maybe GET all sessions is public? // api.GET("/sessions", sessionController.GetAll) // Authenticated routes authenticated := api.Group("") authenticated.Use(jwtAuth) // Apply JWT Auth to all routes below { // Moderator routes moderator := authenticated.Group("/moderator") moderator.Use(moderatorAuth) // Apply Moderator Role Check { // Use distinct path or rely purely on role check moderator.DELETE("/sessions/:id", sessionController.DeleteAsModerator) // Use a specific handler? Or check role inside Delete? // moderator.DELETE("/feedback/:id", feedbackController.DeleteAsModerator) } // Session routes (require authentication) sessions := authenticated.Group("/sessions") { // Public GETs can be moved outside 'authenticated' group if needed sessions.GET("", sessionController.GetAll) // Requires auth now sessions.GET("/:id", sessionController.GetByID) // Requires auth now sessions.POST("", sessionController.Create) // Requires auth (creator ID from token) sessions.PUT("/:id", sessionController.Update) // Requires auth (handler should check ownership) sessions.DELETE("/:id", sessionController.Delete) // Requires auth (handler MUST check ownership) sessions.GET("/:id/participants", sessionController.GetParticipants) // Requires auth sessions.POST("/:id/join", sessionController.JoinSession) // Requires auth sessions.POST("/:id/leave", sessionController.LeaveSession) // Requires auth // Feedback routes (require authentication) feedback := sessions.Group("/:id/feedback") { feedback.POST("", feedbackController.CreateFeedback) // Requires auth (user ID from token) feedback.GET("", feedbackController.GetFeedback) // Requires auth // Add PUT/DELETE for feedback if needed, checking ownership } } // User profile routes, etc. // authenticated.GET("/profile", userController.GetProfile) } } return r }4. Updated
session_controller.go(Create)- Get Creator ID from Context: Remove the insecure query parameter logic. Retrieve the authenticated user's ID from the Gin context.
// pkg/controllers/session_controller.go package controllers import ( "log" "net/http" "your_project/pkg/middleware" // Adjust import path "your_project/pkg/models" // Adjust import path "your_project/pkg/repositories" // Adjust import path "github.com/gin-gonic/gin" "github.com/google/uuid" ) type SessionController struct { repo repositories.SessionRepository // Use an interface } // NewSessionController constructor func NewSessionController(r repositories.SessionRepository) *SessionController { return &SessionController{repo: r} } // Create handles POST /sessions // Assumes JWTAuthMiddleware has run and set the user ID in the context. func (c *SessionController) Create(ctx *gin.Context) { var req models.SessionRequest if err := ctx.ShouldBindJSON(&req); err != nil { // Consider more specific validation error messages if needed ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body", "details": err.Error()}) return } // --- Get Creator ID from JWT Context --- creatorIDValue, exists := ctx.Get(middleware.ContextUserIDKey) if !exists { // This should technically not happen if JWTAuthMiddleware is applied correctly log.Printf("ERROR: UserID missing from context in SessionController.Create") ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: User identification failed"}) return } creatorID, ok := creatorIDValue.(uuid.UUID) // Assert type to uuid.UUID if !ok { // This indicates a programming error (middleware setting wrong type) log.Printf("ERROR: UserID in context is not of type uuid.UUID in SessionController.Create") ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error: User identification processing failed"}) return } // --- End Get Creator ID --- // Optional: Add more business logic validation here (e.g., date checks) session, err := c.repo.Create(ctx.Request.Context(), creatorID, req) // Pass context for potential cancellation/timeouts if err != nil { // Check for specific repository errors (e.g., validation error vs db error) log.Printf("ERROR: Failed to create session for user %s: %v", creatorID, err) // Consider mapping specific repo errors to different HTTP statuses ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create session"}) return } ctx.JSON(http.StatusCreated, session) } // Delete handles DELETE /sessions/:id // Assumes JWTAuthMiddleware has run. This handler checks for ownership. func (c *SessionController) Delete(ctx *gin.Context) { sessionIDStr := ctx.Param("id") sessionID, err := uuid.Parse(sessionIDStr) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session ID format"}) return } // --- Get Requesting User ID from JWT Context --- requestingUserIDValue, exists := ctx.Get(middleware.ContextUserIDKey) if !exists { log.Printf("ERROR: UserID missing from context in SessionController.Delete") ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: User identification failed"}) return } requestingUserID, ok := requestingUserIDValue.(uuid.UUID) if !ok { log.Printf("ERROR: UserID in context is not of type uuid.UUID in SessionController.Delete") ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error: User identification processing failed"}) return } // --- End Get Requesting User ID --- // --- Authorization Check: User must be the creator --- // Fetch the session to check its creator_id session, err := c.repo.GetByID(ctx.Request.Context(), sessionID) // Assuming GetByID exists if err != nil { // Handle not found vs other errors // if errors.Is(err, gorm.ErrRecordNotFound) { // Example with GORM // ctx.JSON(http.StatusNotFound, gin.H{"error": "Session not found"}) // return // } log.Printf("ERROR: Failed to fetch session %s for deletion check: %v", sessionID, err) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve session details"}) return } if session.CreatorID != requestingUserID { log.Printf("WARN: User %s attempted to delete session %s owned by %s", requestingUserID, sessionID, session.CreatorID) ctx.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: You can only delete sessions you created"}) return } // --- End Authorization Check --- // Proceed with deletion err = c.repo.Delete(ctx.Request.Context(), sessionID) // Assuming Delete exists if err != nil { log.Printf("ERROR: Failed to delete session %s by user %s: %v", sessionID, requestingUserID, err) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete session"}) return } ctx.JSON(http.StatusNoContent, nil) // Or http.StatusOK with a success message } // DeleteAsModerator handles DELETE /moderator/sessions/:id // Assumes JWTAuthMiddleware and RoleAuthMiddleware('moderator') have run. func (c *SessionController) DeleteAsModerator(ctx *gin.Context) { sessionIDStr := ctx.Param("id") sessionID, err := uuid.Parse(sessionIDStr) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session ID format"}) return } // No need to check ownership here, role middleware already did the work. // Get moderator ID for logging purposes moderatorIDValue, _ := ctx.Get(middleware.ContextUserIDKey) moderatorID, _ := moderatorIDValue.(uuid.UUID) err = c.repo.Delete(ctx.Request.Context(), sessionID) if err != nil { log.Printf("ERROR: Moderator %s failed to delete session %s: %v", moderatorID, sessionID, err) // Handle specific errors like "not found" if needed ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete session"}) return } log.Printf("INFO: Moderator %s deleted session %s", moderatorID, sessionID) ctx.JSON(http.StatusNoContent, nil) } // Implement other methods (GetAll, GetByID, Update, JoinSession, LeaveSession, GetParticipants) // Ensure Update also checks ownership similar to Delete. // Ensure Join/Leave check participation rules (e.g., session capacity, is user already joined/not joined).5. Updated
feedback_controller.go(CreateFeedback)- Get User ID from Context: Correctly retrieve the
uuid.UUIDfrom the context. - Business Logic: Add checks (ideally in a service layer or repository) to ensure the user participated in the session before allowing feedback.
// pkg/controllers/feedback_controller.go package controllers import ( "log" "net/http" "your_project/pkg/middleware" // Adjust import path "your_project/pkg/models" // Adjust import path "your_project/pkg/repositories" // Adjust import path "github.com/gin-gonic/gin" "github.com/google/uuid" ) type FeedbackController struct { repo repositories.FeedbackRepository // Use an interface // sessionRepo repositories.SessionRepository // Potentially needed to check participation } // NewFeedbackController constructor func NewFeedbackController(r repositories.FeedbackRepository /* , sr repositories.SessionRepository */) *FeedbackController { return &FeedbackController{repo: r /* , sessionRepo: sr */} } // CreateFeedback handles POST /sessions/:id/feedback // Assumes JWTAuthMiddleware has run. func (c *FeedbackController) CreateFeedback(ctx *gin.Context) { sessionIDStr := ctx.Param("id") sessionID, err := uuid.Parse(sessionIDStr) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session ID format"}) return } // --- Get User ID from JWT Context --- userIDValue, exists := ctx.Get(middleware.ContextUserIDKey) // Use constant if !exists { log.Printf("ERROR: UserID missing from context in FeedbackController.CreateFeedback") ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: User identification failed"}) return } userID, ok := userIDValue.(uuid.UUID) // Assert type to uuid.UUID if !ok { log.Printf("ERROR: UserID in context is not of type uuid.UUID in FeedbackController.CreateFeedback") ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error: User identification processing failed"}) return } // --- End Get User ID --- var req models.FeedbackRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body", "details": err.Error()}) return } // --- Business Logic Check (Example) --- // This logic might be better placed within the repository or a service layer // hasParticipated, err := c.sessionRepo.HasUserParticipated(ctx.Request.Context(), sessionID, userID) // if err != nil { // log.Printf("ERROR: Failed to check participation for user %s in session %s: %v", userID, sessionID, err) // ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to verify participation status"}) // return // } // if !hasParticipated { // ctx.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: You can only leave feedback for sessions you participated in"}) // return // } // You might also want to check if the user has already left feedback for this session. // --- End Business Logic Check --- feedback, err := c.repo.CreateFeedback(ctx.Request.Context(), req, sessionID, userID) // Pass context if err != nil { // Check for specific errors, e.g., duplicate feedback error log.Printf("ERROR: Failed to create feedback for user %s on session %s: %v", userID, sessionID, err) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to submit feedback"}) return } ctx.JSON(http.StatusCreated, feedback) } // Implement other methods (GetFeedback)Testing Strategy
Testing is crucial for production readiness. You need both Unit and Integration tests.
1. Unit Testing
- Goal: Test individual functions/methods in isolation.
- Tools: Go's built-in
testingpackage,testify/assert,testify/mock,net/http/httptest. - What to Test:
- Middleware (
jwt_middleware_test.go,role_middleware_test.go):- Test cases with valid tokens (correct signature, not expired). Check if context values (
userID,role,email) are set correctly andc.Next()is called. - Test cases with invalid tokens (missing header, wrong format, bad signature, expired, missing claims). Check if
c.AbortWithStatusJSONis called with the correct status code and error message. - Test
RoleAuthMiddlewarefor cases where the role is correct, incorrect, or missing from the context. - Use
httptest.NewRecorder()andgin.CreateTestContext()to create mock contexts. You might need to manually set headers or context values.
- Test cases with valid tokens (correct signature, not expired). Check if context values (
- Controllers (
session_controller_test.go,feedback_controller_test.go):- Mock Dependencies: Mock your repository interfaces (e.g.,
SessionRepository,FeedbackRepository) usingtestify/mock. - Setup: Create test contexts using
gin.CreateTestContext(httptest.NewRecorder()). Set up request bodies (bytes.NewBufferString), path parameters (c.Params), and context values (c.Set) as needed for each test case. - Test Cases:
- Success Case: Valid input, repository mock returns successfully. Assert the HTTP status code (e.g.,
201 Created,200 OK) and the response body structure/content. Verify that the correct repository methods were called with the expected arguments (mockRepo.AssertCalled). - Bad Request: Invalid JSON body, invalid UUID in path. Assert
400 Bad Request. - Authorization Errors (where applicable): Simulate missing user ID in context (assert
401/500), or simulate ownership check failure inDelete/Update(assert403 Forbidden). - Repository Errors: Configure repository mocks to return errors. Assert
500 Internal Server Erroror other relevant status codes based on error type. - Not Found: For
GetByID,Update,Delete, test cases where the resource doesn't exist (mock repo returnsErrNotFound). Assert404 Not Found.
- Success Case: Valid input, repository mock returns successfully. Assert the HTTP status code (e.g.,
- Mock Dependencies: Mock your repository interfaces (e.g.,
- Repositories/Services (
session_repository_test.go, etc.):- Test the actual database logic or business rules within these layers.
- If using a real database for these tests, use a dedicated test database and ensure proper setup/teardown (e.g., using transactions or cleaning tables). Tools like
testcontainers-gocan be helpful. - If mocking the database driver/ORM, test that the correct queries/calls are made.
- Middleware (
Example Unit Test Snippet (Controller):
// pkg/controllers/session_controller_test.go package controllers_test import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "time" "your_project/pkg/controllers" // Adjust imports "your_project/pkg/middleware" "your_project/pkg/models" "your_project/pkg/repositories/mocks" // Assuming testify mocks generated here "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) func TestSessionController_Create(t *testing.T) { gin.SetMode(gin.TestMode) mockRepo := mocks.NewSessionRepository(t) // Create mock repository controller := controllers.NewSessionController(mockRepo) userID := uuid.New() sessionReq := models.SessionRequest{ Title: "Test Session", Description: "A session for testing", StartTime: time.Now().Add(24 * time.Hour), EndTime: time.Now().Add(25 * time.Hour), Capacity: 10, } expectedSession := models.Session{ // What the repo should return ID: uuid.New(), CreatorID: userID, Title: sessionReq.Title, Description: sessionReq.Description, StartTime: sessionReq.StartTime, EndTime: sessionReq.EndTime, Capacity: sessionReq.Capacity, CreatedAt: time.Now(), UpdatedAt: time.Now(), } // --- Test Case: Success --- t.Run("Success", func(t *testing.T) { // Setup mock expectation // Use mock.AnythingOfType for context.Context if you don't need specific checks on it mockRepo.On("Create", mock.AnythingOfType("*context.valueCtx"), userID, sessionReq).Return(expectedSession, nil).Once() // Setup request context w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Set(middleware.ContextUserIDKey, userID) // Simulate middleware setting the user ID // Prepare request body reqBodyBytes, _ := json.Marshal(sessionReq) req, _ := http.NewRequest(http.MethodPost, "/api/v1/sessions", bytes.NewBuffer(reqBodyBytes)) req.Header.Set("Content-Type", "application/json") c.Request = req // Call the handler controller.Create(c) // Assertions assert.Equal(t, http.StatusCreated, w.Code) var responseSession models.Session err := json.Unmarshal(w.Body.Bytes(), &responseSession) assert.NoError(t, err) assert.Equal(t, expectedSession.ID, responseSession.ID) assert.Equal(t, expectedSession.Title, responseSession.Title) mockRepo.AssertExpectations(t) // Verify mock was called }) // --- Test Case: Bad Request (Invalid JSON) --- t.Run("Bad Request - Invalid JSON", func(t *testing.T){ // No mock expectations needed as it should fail before repo call w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Set(middleware.ContextUserIDKey, userID) req, _ := http.NewRequest(http.MethodPost, "/api/v1/sessions", bytes.NewBufferString("{invalid json")) // Malformed body req.Header.Set("Content-Type", "application/json") c.Request = req controller.Create(c) assert.Equal(t, http.StatusBadRequest, w.Code) mockRepo.AssertNotCalled(t, "Create", mock.Anything, mock.Anything, mock.Anything) }) // --- Test Case: Missing User ID in Context (Simulates Middleware Failure) --- t.Run("Unauthorized - Missing UserID", func(t *testing.T) { // No mock expectations needed w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) // DO NOT set the user ID in context reqBodyBytes, _ := json.Marshal(sessionReq) req, _ := http.NewRequest(http.MethodPost, "/api/v1/sessions", bytes.NewBuffer(reqBodyBytes)) req.Header.Set("Content-Type", "application/json") c.Request = req controller.Create(c) assert.Equal(t, http.StatusUnauthorized, w.Code) // Or 500 depending on how you handle it mockRepo.AssertNotCalled(t, "Create", mock.Anything, mock.Anything, mock.Anything) }) // --- Test Case: Repository Error --- t.Run("Internal Server Error - Repo Failure", func(t *testing.T){ mockRepo.On("Create", mock.AnythingOfType("*context.valueCtx"), userID, sessionReq).Return(models.Session{}, assert.AnError).Once() // Simulate repo error w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Set(middleware.ContextUserIDKey, userID) reqBodyBytes, _ := json.Marshal(sessionReq) req, _ := http.NewRequest(http.MethodPost, "/api/v1/sessions", bytes.NewBuffer(reqBodyBytes)) req.Header.Set("Content-Type", "application/json") c.Request = req controller.Create(c) assert.Equal(t, http.StatusInternalServerError, w.Code) mockRepo.AssertExpectations(t) }) }2. Integration Testing
- Goal: Test the interaction between different components (router, middleware, controllers, potentially hitting a real test database).
- Tools:
net/http/httptest, Go'stestingpackage, a test database (optional but recommended). - What to Test:
- Full HTTP request/response cycles for your API endpoints.
- Authentication/Authorization:
- Send requests without an
Authorizationheader to protected routes (expect 401). - Send requests with an invalid/expired JWT (expect 401).
- Send requests with a valid JWT but insufficient role for role-protected routes (expect 403).
- Send requests with a valid JWT and correct role (expect success or other business logic errors).
- Send requests without an
- CRUD Operations: Test creating, reading, updating, and deleting resources through the API. Verify data persistence if using a test database.
- Business Logic Flows: Test sequences like creating a session, joining it, leaving feedback. Test edge cases like trying to join a full session, deleting a non-existent session, leaving feedback without participating.
- Input Validation: Send requests with invalid bodies, path parameters, or query parameters.
Example Integration Test Snippet:
// cmd/server/main_test.go (or a dedicated integration test package) package main_test import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "os" "testing" "time" "your_project/cmd/server" // Adjust imports "your_project/pkg/models" // "your_project/pkg/database" // For test DB setup/teardown "your_project/pkg/auth" // Assuming a helper to generate test tokens "github.com/stretchr/testify/assert" "github.com/google/uuid" ) var testRouter http.Handler // Keep router instance func TestMain(m *testing.M) { // Setup: Initialize router, connect to test DB, seed data if needed // db := database.ConnectTestDB() // Example // defer database.CloseTestDB(db) // database.MigrateTestDB(db) // Run migrations testRouter = server.SetupRouter(/* pass test db if needed */) // Run tests exitCode := m.Run() // Teardown: Clean up test DB if needed // database.CleanTestDB(db) os.Exit(exitCode) } func TestSessionAPI_Integration(t *testing.T) { // --- Generate Test Tokens --- userID := uuid.New() moderatorID := uuid.New() userToken, _ := auth.GenerateTestJWT(userID, "user") // Helper to create valid JWT moderatorToken, _ := auth.GenerateTestJWT(moderatorID, "moderator") invalidToken := "Bearer this.is.invalid" // --- Test POST /sessions --- t.Run("Create Session - Success", func(t *testing.T) { sessionReq := models.SessionRequest{ Title: "Integration Test Session", Description: "Testing creation via API", StartTime: time.Now().Add(48 * time.Hour), EndTime: time.Now().Add(49 * time.Hour), Capacity: 5, } reqBody, _ := json.Marshal(sessionReq) req, _ := http.NewRequest(http.MethodPost, "/api/v1/sessions", bytes.NewBuffer(reqBody)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+userToken) // Use valid user token rr := httptest.NewRecorder() testRouter.ServeHTTP(rr, req) assert.Equal(t, http.StatusCreated, rr.Code) var createdSession models.Session err := json.Unmarshal(rr.Body.Bytes(), &createdSession) assert.NoError(t, err) assert.Equal(t, sessionReq.Title, createdSession.Title) assert.Equal(t, userID, createdSession.CreatorID) // Verify creator ID is set correctly // Store createdSession.ID for subsequent tests }) t.Run("Create Session - Unauthorized", func(t *testing.T) { sessionReq := models.SessionRequest{ Title: "No Auth Session" /* ... */ } reqBody, _ := json.Marshal(sessionReq) req, _ := http.NewRequest(http.MethodPost, "/api/v1/sessions", bytes.NewBuffer(reqBody)) req.Header.Set("Content-Type", "application/json") // No Authorization header rr := httptest.NewRecorder() testRouter.ServeHTTP(rr, req) assert.Equal(t, http.StatusUnauthorized, rr.Code) }) // --- Test DELETE /sessions/:id (Ownership Check) --- // Assume a session with sessionID created by userID exists from previous test var sessionID uuid.UUID // Get this from the successful creation test t.Run("Delete Session - Forbidden (Wrong User)", func(t *testing.T){ otherUserID := uuid.New() otherUserToken, _ := auth.GenerateTestJWT(otherUserID, "user") req, _ := http.NewRequest(http.MethodDelete, "/api/v1/sessions/"+sessionID.String(), nil) req.Header.Set("Authorization", "Bearer "+otherUserToken) rr := httptest.NewRecorder() testRouter.ServeHTTP(rr, req) assert.Equal(t, http.StatusForbidden, rr.Code) }) t.Run("Delete Session - Success (Owner)", func(t *testing.T){ req, _ := http.NewRequest(http.MethodDelete, "/api/v1/sessions/"+sessionID.String(), nil) req.Header.Set("Authorization", "Bearer "+userToken) // Original creator token rr := httptest.NewRecorder() testRouter.ServeHTTP(rr, req) assert.Equal(t, http.StatusNoContent, rr.Code) // Or 200 OK }) // --- Test DELETE /moderator/sessions/:id --- // Create another session first... var sessionToDeleteByModID uuid.UUID t.Run("Delete Session - Success (Moderator)", func(t *testing.T){ req, _ := http.NewRequest(http.MethodDelete, "/api/v1/moderator/sessions/"+sessionToDeleteByModID.String(), nil) req.Header.Set("Authorization", "Bearer "+moderatorToken) // Moderator token rr := httptest.NewRecorder() testRouter.ServeHTTP(rr, req) assert.Equal(t, http.StatusNoContent, rr.Code) }) t.Run("Delete Session - Forbidden (User on Moderator Route)", func(t *testing.T){ req, _ := http.NewRequest(http.MethodDelete, "/api/v1/moderator/sessions/"+uuid.NewString(), nil) // Use a dummy ID req.Header.Set("Authorization", "Bearer "+userToken) // Regular user token rr := httptest.NewRecorder() testRouter.ServeHTTP(rr, req) assert.Equal(t, http.StatusForbidden, rr.Code) }) // --- Add tests for Feedback API (POST, GET) --- // Test creating feedback requires participation (might need DB interaction to check) // Test getting feedback requires auth }By implementing these code improvements and comprehensive testing strategies, you significantly enhance the robustness, security, and maintainability of your skill-sharing web application, making it ready for production deployment. Remember to adapt repository calls, error handling, and specific business logic checks to your exact implementation details.