feat: setup middleware

This commit is contained in:
2026-06-25 11:46:32 +02:00
parent 539c0216f5
commit a07940df20
3 changed files with 61 additions and 149 deletions

View File

@@ -1,18 +1,24 @@
package internal
import (
"fmt"
"git.dynamicdiscord.de/malobeo/portal/openapi"
"github.com/gin-gonic/gin"
)
var apiClient *openapi.APIClient
func GetApiClient(c *gin.Context) *openapi.APIClient {
configuration := openapi.NewConfiguration()
//TODO: read from env
configuration.Host = "localhost:8000"
configuration.Scheme = "http"
func GetApiClient() *openapi.APIClient {
if apiClient == nil {
configuration := openapi.NewConfiguration()
configuration.Host = "localhost:8000"
configuration.Scheme = "http"
apiClient = openapi.NewAPIClient(configuration)
if c != nil {
authToken, err := c.Cookie("Authorization")
if err == nil && len(authToken) > 0 {
configuration.AddDefaultHeader("Authorization", fmt.Sprintf("Bearer %v", authToken))
}
}
return apiClient
return openapi.NewAPIClient(configuration)
}

View File

@@ -1,162 +1,54 @@
package middlewares
import (
// "fmt"
"fmt"
// "os"
// "time"
// //"strconv"
"github.com/gin-gonic/gin"
// "github.com/golang-jwt/jwt/v5"
// "net/http"
"net/http"
"git.dynamicdiscord.de/malobeo/portal/openapi"
"git.dynamicdiscord.de/malobeo/portal/services"
)
type AuthValidator struct {
}
func setUser(c *gin.Context) (openapi.UserResponse, error) {
user, err := services.Users.GetByAuthHeader(c)
if err != nil {
return openapi.UserResponse{}, fmt.Errorf("Error getting user by auth header: %s", err)
}
c.Set("user", user)
return user, nil
}
func (av *AuthValidator) RequireAuth(c *gin.Context) {
// Get Cookie
//tokenString, err := c.Cookie("Authorization")
_, err := setUser(c)
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
//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)
c.Next()
}
func (av *AuthValidator) RequireAdmin(c *gin.Context) {
// Get Cookie
//tokenString, err := c.Cookie("Authorization")
user, err := setUser(c)
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
//if err != nil {
// c.AbortWithStatus(http.StatusUnauthorized)
// return
//}
if !*user.IsAdmin {
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
// }
// if !user.IsAdmin {
// 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)
//}
c.Next()
}

View File

@@ -85,3 +85,17 @@ func (u *UserService) GetByName(c *gin.Context, username string) (openapi.UserRe
return openapi.UserResponse{}, fmt.Errorf("Not found")
}
func (u *UserService) GetByAuthHeader(c *gin.Context) (openapi.UserResponse, error) {
apiClient := internal.GetApiClient(c)
resp, r, err := apiClient.UsersAPI.GetCurrentUserApiV1UsersCurrentGet(context.Background()).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `UserApi.GetById``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
return openapi.UserResponse{}, err
}
// response from `LoginForAccessTokenTokenPost`: Token
fmt.Fprintf(os.Stdout, "Response from `UserApi.GetById`: %v\n", resp)
return *resp, nil
}