middlewares

package
v0.0.0-...-6e93265 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2021 License: MIT Imports: 11 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
)
View Source
var Auth gin.HandlerFunc = func(c *gin.Context) {

	token, err := JWT.ExtractToken(c)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
			"message": "unauthorized",
		})
		return
	}

	_, err = JWT.ValidateToken(token)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
			"message": "unauthorized",
		})
		return
	}

	payload, err := JWT.DecodeToken(token)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
			"message": "unauthorized",
		})
		return
	}

	tokenRedisKey := fmt.Sprintf("%s-token", payload["userId"])
	res, err := Cache.Get(tokenRedisKey)

	if err != nil {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
			"message": "unauthorized",
		})
		return
	}

	userId, _ := strconv.ParseInt(fmt.Sprintf("%s", res), 10, 64)
	// check db for user with given id
	var user models.User
	result := DB.Find(&user, userId)
	if result.Error != nil && errors.Is(result.Error, gorm.ErrRecordNotFound) {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
			"message": "unauthorized",
		})
		return
	}

	c.Next()
}

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

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

Functions

func InitiateMiddlewaresDependencies

func InitiateMiddlewaresDependencies()

InitiateMiddlewaresDependencies 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