golang gin framework auth middleware jwt and CORS

Golang Auth Middleware example code for gin framework:

package middlewares

import (
	"time"
	"github.com/gin-gonic/gin"
	"github.com/appleboy/gin-jwt"
	"myproject/db"
	"fmt"
	"github.com/appleboy/gin-jwt-server/model"

)


func GinJwtMiddlewareHandler() *jwt.GinJWTMiddleware {
	return &jwt.GinJWTMiddleware{
		Realm:      "test zone",
		Key:        []byte("very secrete key"),
		Timeout:    time.Hour * 100,
		MaxRefresh: time.Hour,
		Authenticator: func(userId string, password string, c *gin.Context) (string, bool) {
			var getDB = db.GetDB()
			var user model.User
			if err := getDB.Where("username=? AND password=?", userId, password).Find(&user).Limit(1).Error; err != nil {
				c.AbortWithStatus(404)
				fmt.Println(err)
			} else {
				fmt.Println(user)
				//c.JSON(200, user)
				return userId, true
			}

			return userId, false
		},
		Authorizator: func(userId string, c *gin.Context) bool {
			//if userId == "sohag" {
			//	return true
			//}
			//return false

			return true
		},
		Unauthorized: func(c *gin.Context, code int, message string) {
			c.JSON(code, gin.H{
				"code":    code,
				"message": message,
			})
		},
		TokenLookup: "header:Authorization",
		TokenHeadName: "Bearer",
		TimeFunc: time.Now,
	}
}

func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Content-Type", "application/json")
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Max-Age", "86400")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *