Skip to content

Commit b02ed37

Browse files
committed
add authentication middleware to protect product endpoints
1 parent 1517966 commit b02ed37

File tree

4 files changed

+52
-5
lines changed

4 files changed

+52
-5
lines changed

cmd/main.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"api-go/controller"
55
"api-go/db"
6+
"api-go/middleware"
67
"api-go/repository"
78
"api-go/usecase"
89

@@ -30,11 +31,15 @@ func main() {
3031
})
3132
})
3233

33-
server.GET("/products", ProductController.GetProducts)
34-
server.POST("/product", ProductController.CreateProduct)
35-
server.GET("/product/:productId", ProductController.GetProductsById)
36-
server.PUT("/product", ProductController.UpdateProduct)
37-
server.DELETE("/product/:productId", ProductController.DeleteProduct)
34+
protected := server.Group("/")
35+
protected.Use(middleware.AuthMiddleware())
36+
{
37+
protected.GET("/products", ProductController.GetProducts)
38+
protected.POST("/product", ProductController.CreateProduct)
39+
protected.GET("/product/:productId", ProductController.GetProductsById)
40+
protected.PUT("/product", ProductController.UpdateProduct)
41+
protected.DELETE("/product/:productId", ProductController.DeleteProduct)
42+
}
3843

3944
server.Run(":8000")
4045

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ require (
1212
github.com/bytedance/sonic/loader v0.1.1 // indirect
1313
github.com/cloudwego/base64x v0.1.4 // indirect
1414
github.com/cloudwego/iasm v0.2.0 // indirect
15+
github.com/dgrijalva/jwt-go v3.2.0+incompatible // direct
1516
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
1617
github.com/gin-contrib/sse v0.1.0 // indirect
1718
github.com/go-playground/locales v0.14.1 // indirect

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQ
99
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
1010
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
1111
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
12+
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
13+
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
1214
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
1315
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
1416
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=

middleware/auth.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package middleware
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"strings"
7+
8+
"github.com/dgrijalva/jwt-go"
9+
"github.com/gin-gonic/gin"
10+
)
11+
12+
var jwtSecret = []byte("your_secret_key")
13+
14+
func AuthMiddleware() gin.HandlerFunc {
15+
return func(c *gin.Context) {
16+
authHeader := c.GetHeader("Authorization")
17+
if authHeader == "" {
18+
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
19+
c.Abort()
20+
return
21+
}
22+
23+
tokenString := strings.Split(authHeader, "Bearer ")[1]
24+
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
25+
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
26+
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
27+
}
28+
return jwtSecret, nil
29+
})
30+
31+
if err != nil || !token.Valid {
32+
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
33+
c.Abort()
34+
return
35+
}
36+
37+
c.Next()
38+
}
39+
}

0 commit comments

Comments
 (0)