Archived
Template
1
0
This repository has been archived on 2023-12-20. You can view files and clone it, but cannot push or open issues or pull requests.
Files
golang-base-project/middleware/auth.go

23 lines
562 B
Go
Raw Permalink Normal View History

2021-12-12 14:56:13 +01:00
// Package middleware defines all the middlewares for the application
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
// UserIDKey is the key used to set and get the user id in the context of the current request
2021-12-12 14:56:13 +01:00
const UserIDKey = "UserID"
// Auth middleware redirects to /login and aborts the current request if there is no authenticated user
2021-12-12 14:56:13 +01:00
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
_, exists := c.Get(UserIDKey)
if !exists {
c.Redirect(http.StatusTemporaryRedirect, "/login")
c.Abort()
return
}
}
}