Files
mtusi2026lab5/internal/s3/config.go
T
2026-11-13 15:52:39 +03:00

100 lines
2.0 KiB
Go

package s3
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"mtusi2026-messenger/internal/config"
)
const (
seaweedUID = 1000
seaweedGID = 1000
)
type Credential struct {
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
}
type Identity struct {
Name string `json:"name"`
Credentials []Credential `json:"credentials"`
Actions []string `json:"actions"`
}
type Config struct {
Identities []Identity `json:"identities"`
}
func WriteConfig(output string, cfg config.S3Config) error {
apiAccessKey, err := cfg.APIAccessKey()
if err != nil {
return err
}
apiSecretKey, err := cfg.APISecretKey()
if err != nil {
return err
}
bootstrapAccessKey, err := cfg.BootstrapAccessKey()
if err != nil {
return err
}
bootstrapSecretKey, err := cfg.BootstrapSecretKey()
if err != nil {
return err
}
config := Config{
Identities: []Identity{
{
Name: "bootstrap",
Credentials: []Credential{
{AccessKey: bootstrapAccessKey, SecretKey: bootstrapSecretKey},
},
Actions: []string{"Admin", "Read", "Write", "List", "Tagging"},
},
{
Name: "api",
Credentials: []Credential{
{AccessKey: apiAccessKey, SecretKey: apiSecretKey},
},
Actions: []string{"Read", "Write", "List", "Tagging"},
},
},
}
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return fmt.Errorf("marshal s3 config: %w", err)
}
if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil {
return fmt.Errorf("create config directory: %w", err)
}
tmp := output + ".tmp"
if err := os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil {
return fmt.Errorf("write config: %w", err)
}
if err := os.Chown(tmp, seaweedUID, seaweedGID); err != nil {
return fmt.Errorf("chown config: %w", err)
}
if err := os.Chmod(tmp, 0o400); err != nil {
return fmt.Errorf("chmod config: %w", err)
}
if err := os.Rename(tmp, output); err != nil {
return fmt.Errorf("replace config: %w", err)
}
return nil
}