lv8girl!
This commit is contained in:
49
internal/middleware/auth.go
Normal file
49
internal/middleware/auth.go
Normal file
@@ -0,0 +1,49 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user