Allow adding users to rooms

This commit is contained in:
2025-01-04 23:12:56 +01:00
parent c78a84e075
commit 2eadad9135
6 changed files with 189 additions and 14 deletions

View File

@@ -4,6 +4,7 @@ import(
"os"
"fmt"
"time"
"strconv"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
@@ -16,6 +17,32 @@ type AuthValidator struct {
DB *gorm.DB
}
func (av *AuthValidator) RequireRoomAdmin(c *gin.Context) {
user, exists := c.Get("user")
if !exists {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
roomId, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{ "message": fmt.Sprintf("Room with Id '%s' does not exist", c.Param("id"))})
return
}
var rooms []models.Room
av.DB.Model(&user).Association("OwnedRooms").Find(&rooms)
for _, room := range rooms {
if room.ID == uint(roomId) {
c.Next()
return
}
}
c.AbortWithStatus(http.StatusUnauthorized)
}
func (av *AuthValidator) RequireAuth(c *gin.Context) {
// Get Cookie
tokenString, err := c.Cookie("Authorization")
@@ -68,3 +95,43 @@ func (av *AuthValidator) RequireAuth(c *gin.Context) {
c.AbortWithStatus(http.StatusUnauthorized)
}
func (av *AuthValidator) OptionalAuth(c *gin.Context) {
defer c.Next()
// Get Cookie
tokenString, err := c.Cookie("Authorization")
if err != nil {
return
}
//Validate
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("SECRET")), nil
})
if err != nil {
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if float64(time.Now().Unix()) > claims["exp"].(float64) {
return
}
//Find user
var user models.User
result := av.DB.First(&user, claims["sub"])
if result.Error != nil {
return
}
//Attach to req
c.Set("user", user)
}
}