62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package apis
|
|
|
|
import (
|
|
"clortho/lib/db"
|
|
"clortho/lib/users"
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
)
|
|
|
|
func AuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// Get the token from the Authorization header
|
|
authCookie, err := c.Cookie("CLORTHO_AUTH")
|
|
if err != nil {
|
|
//c.JSON(http.StatusUnauthorized, gin.H{"error": "authorization token required"})
|
|
return
|
|
}
|
|
|
|
session, err := users.GetSessionFromCookie(authCookie)
|
|
if err != nil {
|
|
//c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.Set("session", session)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func LoggedInMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
_, hasSession := c.Get("session")
|
|
if !hasSession {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AdminMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// First ensure user is logged in
|
|
sessionInterface, hasSession := c.Get("session")
|
|
if !hasSession {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// Check if user is admin
|
|
session, ok := sessionInterface.(*db.UserSession)
|
|
if !ok || session.User == nil || !session.User.Admin {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|