middlewares

package
v1.4.17 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2024 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AnotherExampleMiddleware core.Middleware = func(c *core.Context) {
	fmt.Println("another example middleware!")
	c.Next()
}

Another example middleware

View Source
var AuthCheck core.Middleware = func(c *core.Context) {
	tokenRaw := c.GetHeader("Authorization")
	token := strings.TrimSpace(strings.Replace(tokenRaw, "Bearer", "", 1))
	if token == "" {
		c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
			"message": "unauthorized",
		})).ForceSendResponse()
		return
	}
	payload, err := c.GetJWT().DecodeToken(token)
	if err != nil {
		c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
			"message": "unauthorized",
		})).ForceSendResponse()
		return
	}
	userAgent := c.GetUserAgent()
	hashedCacheKey := utils.CreateAuthTokenHashedCacheKey(uint(c.CastToInt(payload["userID"])), userAgent)

	cachedToken, err := c.GetCache().Get(hashedCacheKey)
	if err != nil {

		c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
			"message": "unauthorized",
		})).ForceSendResponse()
		return
	}
	if cachedToken != token {

		c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
			"message": "unauthorized",
		})).ForceSendResponse()
		return
	}

	var user models.User
	res := c.GetGorm().Where("id = ?", payload["userID"]).First(&user)
	if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {

		c.GetLogger().Error(res.Error.Error())
		c.Response.SetStatusCode(http.StatusInternalServerError).Json(c.MapToJson(map[string]interface{}{
			"message": "internal error",
		})).ForceSendResponse()
		return
	}

	if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {

		c.Response.SetStatusCode(http.StatusUnauthorized).Json(c.MapToJson(map[string]interface{}{
			"message": "unauthorized",
		})).ForceSendResponse()
		return
	}

	c.Next()
}
View Source
var ExampleMiddleware core.Middleware = func(c *core.Context) {
	fmt.Println("example middleware!")
	c.Next()
}

Example middleware

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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