Files
zineshop/middlewares/requireAuth.go

139 lines
2.8 KiB
Go

package middlewares
import(
"os"
"fmt"
"time"
"strconv"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"example.com/gin/test/models"
"example.com/gin/test/repositories"
)
type AuthValidator struct {
}
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
}
rooms, err := repositories.Users.GetOwnedRooms(user.(models.User))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{ "message": "Could not querie owend rooms"})
return
}
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")
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
//Validate
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(os.Getenv("SECRET")), nil
})
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
//Check Expiration
if float64(time.Now().Unix()) > claims["exp"].(float64) {
//expired
c.AbortWithStatus(http.StatusUnauthorized)
return
}
//Find user
user, err := repositories.Users.GetById(claims["sub"])
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
//Attach to req
c.Set("user", user)
// Coninue
c.Next()
return
}
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
user, err := repositories.Users.GetById(claims["sub"])
if err != nil {
return
}
//Attach to req
c.Set("user", user)
}
}