2024-01-04 20:48:05 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2024-01-06 13:10:24 +00:00
|
|
|
"resource-manager/security"
|
2024-01-04 20:48:05 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Auth() gin.HandlerFunc {
|
|
|
|
basicAuth, hasBasicAuth := os.LookupEnv("BASIC_AUTH_CREDENTIALS")
|
|
|
|
var apiAuths []string
|
|
|
|
if list, hasApiAuth := os.LookupEnv("API_CREDENTIALS"); hasApiAuth {
|
|
|
|
apiAuths = strings.Split(list, ",")
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(c *gin.Context) {
|
2024-01-06 13:10:24 +00:00
|
|
|
if rawToken := c.Query("token"); rawToken != "" {
|
|
|
|
token, err := security.ParseToken(rawToken)
|
|
|
|
if err != nil {
|
|
|
|
abort(c, nil, http.StatusUnauthorized, "invalid token")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.Set("secure", "token")
|
|
|
|
c.Set("path", token.Path)
|
|
|
|
return
|
|
|
|
}
|
2024-01-04 20:48:05 +00:00
|
|
|
authHeader := c.GetHeader("Authorization")
|
|
|
|
if strings.HasPrefix(authHeader, "Basic ") && hasBasicAuth {
|
|
|
|
if strings.TrimPrefix(authHeader, "Basic ") == basicAuth {
|
2024-01-06 13:17:22 +00:00
|
|
|
c.Set("secure", security.TypeBasic)
|
2024-01-04 20:48:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if strings.HasPrefix(authHeader, "Api ") && hasBasicAuth {
|
|
|
|
key := strings.TrimPrefix(authHeader, "Api ")
|
|
|
|
if hasValidApiKey(apiAuths, key) {
|
2024-01-06 13:17:22 +00:00
|
|
|
c.Set("secure", security.TypeApi)
|
2024-01-04 20:48:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
abort(c, nil, http.StatusUnauthorized, "missing auth")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-06 13:17:22 +00:00
|
|
|
func Secure(types ...security.Type) gin.HandlerFunc {
|
2024-01-04 20:48:05 +00:00
|
|
|
return func(c *gin.Context) {
|
|
|
|
value, exists := c.Get("secure")
|
|
|
|
if !exists {
|
|
|
|
abort(c, nil, http.StatusUnauthorized, "missing auth")
|
|
|
|
} else {
|
2024-01-07 19:23:15 +00:00
|
|
|
securityType := value.(security.Type)
|
2024-01-04 20:48:05 +00:00
|
|
|
for _, t := range types {
|
|
|
|
if t == securityType {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
abort(c, nil, http.StatusUnauthorized, fmt.Sprintf("bad security: received %s type", securityType))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func hasValidApiKey(auths []string, key string) bool {
|
|
|
|
for _, a := range auths {
|
|
|
|
if a == key {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func abort(c *gin.Context, err error, statusCode int, message string) {
|
2024-01-06 13:10:24 +00:00
|
|
|
log.Printf("Aborted with error: %v", err)
|
2024-01-04 20:48:05 +00:00
|
|
|
c.AbortWithStatusJSON(statusCode, gin.H{"status": statusCode, "created": time.Now(), "message": message})
|
|
|
|
}
|