SimpleTutorialHosting/internal/config/config.go

121 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-10-27 11:12:56 +00:00
package config
import (
"SimpleTutorialHosting/internal/models"
"SimpleTutorialHosting/internal/secrets"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
)
type Config struct {
Port int
BucketName string
Auth AuthConfig
}
type AuthConfig struct {
Mode string
Dev *models.DevAuthConfig
SAML *models.SAMLConfig
}
func Load(ctx context.Context) (*Config, error) {
bucketName := os.Getenv("S3_BUCKET_NAME")
if bucketName == "" {
return nil, fmt.Errorf("S3_BUCKET_NAME is not set")
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
authMode := os.Getenv("AUTH_MODE")
if authMode == "" {
authMode = "dev"
}
var authConfig AuthConfig
authConfig.Mode = authMode
switch authMode {
case "dev":
if err := loadDevAuth(&authConfig); err != nil {
return nil, err
}
case "saml":
if err := loadSAMLAuth(ctx, &authConfig); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("invalid AUTH_MODE: %s", authMode)
}
return &Config{
Port: 8080,
BucketName: bucketName,
Auth: authConfig,
}, nil
}
func loadDevAuth(config *AuthConfig) error {
devUserJSON := os.Getenv("DEV_USERS")
if devUserJSON == "" {
config.Dev = &models.DevAuthConfig{
Users: []models.User{
{
ID: "admin",
Username: "admin",
Role: models.RoleAdmin,
},
{
ID: "viewer",
Username: "viewer",
Role: models.RoleViewer,
},
},
}
}
return nil
}
func loadSAMLAuth(ctx context.Context, config *AuthConfig) error { //todo
secretID := os.Getenv("SAML_SECRET_ID")
if secretID == "" {
return fmt.Errorf("SAML_SECRET_ID is not set")
}
secretManager, err := secrets.NewSecretManager(ctx)
if err != nil {
return fmt.Errorf("failed to create secret manager: %w", err)
}
samlSecrets, err := secretManager.GetSAMLConfig(ctx, secretID)
if err != nil {
return fmt.Errorf("failed to get SAML secrets: %w", err)
}
cert, err := tls.X509KeyPair([]byte(samlSecrets.Certificate), []byte(samlSecrets.PrivateKey))
if err != nil {
return fmt.Errorf("failed to load X509 key pair: %w", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return fmt.Errorf("failed to parse certificate: %w", err)
}
config.SAML = &models.SAMLConfig{
RootURL: samlSecrets.RootURL,
KeyPair: cert,
IDPMetadata: []byte(samlSecrets.IDPMetadata),
AdminGroup: samlSecrets.AdminGroup,
ViewerGroup: samlSecrets.ViewerGroup,
}
return nil
}