help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
go-rest-api
/
internal
/
middleware
RSK World
go-rest-api
Go REST API - Enterprise-grade REST API with JWT Authentication + PostgreSQL + Redis Caching + Docker + Comprehensive Testing + Educational Design
middleware
  • auth_middleware.go1.6 KB
  • auth_middleware_test.go2.7 KB
  • cors.go819 B
  • logger.go736 B
  • ratelimit.go1.3 KB
  • role_middleware.go1.1 KB
auth_middleware_test.go
internal/middleware/auth_middleware_test.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package middleware

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/rskworld/go-rest-api/internal/config"
	"github.com/stretchr/testify/assert"
)

func TestAuthMiddleware(t *testing.T) {
	gin.SetMode(gin.TestMode)

	cfg := &config.Config{
		JWTSecret: "testsecret",
	}

	r := gin.New()
	r.Use(AuthMiddleware(cfg))

	// Protected route
	r.GET("/protected", func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			c.JSON(500, gin.H{"error": "user_id not set"})
			return
		}
		c.JSON(200, gin.H{"user_id": userID})
	})

	tests := []struct {
		name           string
		authHeader     string
		expectedStatus int
	}{
		{
			name:           "No authorization header",
			authHeader:     "",
			expectedStatus: http.StatusUnauthorized,
		},
		{
			name:           "Invalid authorization format",
			authHeader:     "InvalidFormat",
			expectedStatus: http.StatusUnauthorized,
		},
		{
			name:           "Invalid token",
			authHeader:     "Bearer invalidtoken",
			expectedStatus: http.StatusUnauthorized,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req, _ := http.NewRequest("GET", "/protected", nil)
			if tt.authHeader != "" {
				req.Header.Set("Authorization", tt.authHeader)
			}

			w := httptest.NewRecorder()
			r.ServeHTTP(w, req)

			assert.Equal(t, tt.expectedStatus, w.Code)
		})
	}
}

func TestRoleMiddleware(t *testing.T) {
	gin.SetMode(gin.TestMode)

	r := gin.New()

	// Middleware chain
	r.Use(func(c *gin.Context) {
		// Mock user role setting
		c.Set("user_role", "user")
		c.Next()
	})
	r.Use(RequireRole("admin"))

	r.GET("/admin-only", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "success"})
	})

	req, _ := http.NewRequest("GET", "/admin-only", nil)
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)

	// Should be forbidden because user role is "user" but requires "admin"
	assert.Equal(t, http.StatusForbidden, w.Code)
}

func TestRequireAdmin(t *testing.T) {
	gin.SetMode(gin.TestMode)

	r := gin.New()

	// Middleware chain
	r.Use(func(c *gin.Context) {
		// Mock user role setting
		c.Set("user_role", "admin")
		c.Next()
	})
	r.Use(RequireAdmin())

	r.GET("/admin-only", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "success"})
	})

	req, _ := http.NewRequest("GET", "/admin-only", nil)
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)

	// Should succeed because user role is "admin"
	assert.Equal(t, http.StatusOK, w.Code)
}
126 lines•2.7 KB
go

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer