50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AuthRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
userID := session.Get("user_id")
|
|
if userID == nil {
|
|
c.Redirect(http.StatusFound, "/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("user_id", userID)
|
|
c.Set("username", session.Get("username"))
|
|
c.Set("user_role", session.Get("user_role"))
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AdminRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
userRole := session.Get("user_role")
|
|
if userRole != "admin" {
|
|
c.Redirect(http.StatusFound, "/")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("user_id", session.Get("user_id"))
|
|
c.Set("username", session.Get("username"))
|
|
c.Set("user_role", userRole)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func GetCurrentUser(c *gin.Context) (uint, string, string, bool) {
|
|
session := sessions.Default(c)
|
|
userID := session.Get("user_id")
|
|
if userID == nil {
|
|
return 0, "", "", false
|
|
}
|
|
return userID.(uint), session.Get("username").(string), session.Get("user_role").(string), true
|
|
}
|