polycule-connect/polyculeconnect/cmd/backend/add.go

102 lines
2.9 KiB
Go
Raw Normal View History

package cmd
import (
"context"
"fmt"
"strings"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/model"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/logger"
"github.com/google/uuid"
"github.com/spf13/cobra"
)
var (
backendID string
backendName string
backendIssuer string
backendClientID string
backendClientSecret string
backendScopes []string
)
var backendAddCmd = &cobra.Command{
Use: "add",
Short: "Add a new backend to the storage",
Long: `Add a new backend to the storage.
Parameters to provide:
- id: Unique ID to represent the backend in the storage
- name: Human readable name to represent the backend. It will be used by
the user in the authentication page to select a backend during
authentication
- issuer: Full hostname of the OIDC provider, e.g. 'https://github.com'
- client-id: OIDC Client ID for the backend
- client-secret OIDC Client secret for the backend`,
Run: func(cmd *cobra.Command, args []string) {
addNewBackend()
},
}
func scopesValid(scopes []string) bool {
for _, s := range scopes {
if s == "openid" {
return true
}
}
return false
}
func addNewBackend() {
c := utils.InitConfig("")
logger.Init(c.LogLevel)
s, err := db.New(*c)
if err != nil {
utils.Failf("failed to init storage: %s", err.Error())
}
if backendClientID == "" {
utils.Fail("Empty client ID")
}
if backendClientSecret == "" {
utils.Fail("Empty client secret")
}
if !scopesValid(backendScopes) {
utils.Failf("Invalid list of scopes %s", strings.Join(backendScopes, ", "))
}
backendIDUUID := uuid.New()
backendConf := model.Backend{
ID: backendIDUUID,
Name: backendName,
Config: model.BackendOIDCConfig{
ClientID: backendClientID,
ClientSecret: backendClientSecret,
Issuer: backendIssuer,
RedirectURI: c.RedirectURI(),
Scopes: backendScopes,
},
}
if err := s.BackendStorage().AddBackend(context.Background(), &backendConf); err != nil {
utils.Failf("Failed to add new backend to storage: %s", err.Error())
}
fmt.Printf("New backend %s added.\n", backendName)
}
func init() {
backendCmd.AddCommand(backendAddCmd)
backendAddCmd.Flags().StringVarP(&backendID, "id", "i", "", "ID to identify the backend in the storage")
backendAddCmd.Flags().StringVarP(&backendName, "name", "n", "", "Name to represent the backend")
backendAddCmd.Flags().StringVarP(&backendIssuer, "issuer", "d", "", "Full hostname of the backend")
backendAddCmd.Flags().StringVarP(&backendClientID, "client-id", "", "", "OIDC Client ID for the backend")
backendAddCmd.Flags().StringVarP(&backendClientSecret, "client-secret", "", "", "OIDC Client secret for the backend")
backendAddCmd.Flags().StringArrayVarP(&backendScopes, "scopes", "s", []string{"openid", "profile", "email"}, "OIDC Scopes asked to the backend")
}