middlewares

package
v0.0.0-...-eab9a32 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2022 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DB for database manipulation
	DB *gorm.DB
	// Cache for cache manipulation
	Cache *cache.CacheEngine
	// JWT used for jwt tokens creation and validation
	JWT     *jwt.JWTUtil
	Session *sessions.Sessions
)
View Source
var Auth gin.HandlerFunc = func(c *gin.Context) {
	auth := authpkg.Resolve()
	ok, err := auth.Check(c)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
			"message": "something went wrong while performing auth check",
		})
		return
	}

	if !ok {
		c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
			"message": "forbidden",
		})
		return
	}

	c.Next()
}

Auth checks if the request is authenticated

View Source
var CORSMiddleware gin.HandlerFunc = func(c *gin.Context) {

	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Credentials", "true")
	c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
	c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT, DELETE")

	if c.Request.Method == "OPTIONS" {
		c.AbortWithStatus(204)
		return
	}

	c.Next()
}

CORSMiddleware enable router another domain

View Source
var MiddlewareExample gin.HandlerFunc = func(c *gin.Context) {
	fmt.Println("I'm an example middleware!")

	c.Next()
}

MiddlewareExample is an example of a middleware gets executed before the request handler

View Source
var VerifyJwt gin.HandlerFunc = func(c *gin.Context) {

	if c.Request.Header["Authorization"] != nil {
		hash := jwt.NewHS256([]byte("secret"))
		payload := jwt.Payload{}

		HeaderToken := strings.Split(c.Request.Header["Authorization"][0], " ")[1]
		token := []byte(HeaderToken)
		hd, err := jwt.Verify(token, hash, &payload)

		if err != nil {
			c.JSON(401, gin.H{
				"Data": "Token Invalido",
			})
			c.Abort()
		} else {

			tokenInt, err := strconv.Atoi(hd.KeyID)
			if err != nil {
				fmt.Println(err)
			}
			tokenUint := uint(tokenInt)

			c.Set("id", tokenUint)
			c.Next()
		}
	} else {
		c.JSON(401, gin.H{
			"Data": "Token inexistente",
		})
		c.Abort()
	}
}

VerifyJwt verify jwt is valid

Functions

func GenerateJwt

func GenerateJwt(ID uint) string

GenerateJwt return JWT

func InitiateMiddlewaresDependencies

func InitiateMiddlewaresDependencies()

InitiateHandlersDependencies to initiate the any dependency of the handlers

func RegisterMiddlewares

func RegisterMiddlewares()

RegisterMiddlewares helps you attach middlwares globally

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL