Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
Service.go 1.61 KiB
package app

import (
	"context"
	"fmt"

	"code.fbi.h-da.de/danet/gosdn/controller/store"
	"github.com/google/uuid"
)

// ManagementService is the app service.
type ManagementService interface {
	Register(string, string) (*App, error)
	Deregister(string) error
}

// Service manages apps and their access to the event system.
type Service struct {
	store ManagementStore
}

// NewAppService creates a new app service.
func NewAppService(store ManagementStore) ManagementService {
	return &Service{
		store: store,
	}
}

// Register checks if the app already exists and if not creates a new one.
func (a *Service) Register(appName, token string) (*App, error) {
	ctx := context.Background()
	if token != "SecurePresharedToken" {
		return nil, fmt.Errorf("token not valid")
	}

	exisitingApp, err := a.store.Get(ctx, store.Query{ID: uuid.Nil, Name: appName})
	if err != nil {
		if exisitingApp.ID == uuid.Nil {
			return a.createNewApp(appName)
		}

		return nil, err
	}

	return &exisitingApp, nil
}

// Deregister deregisters an app.
func (a *Service) Deregister(appName string) error {
	ctx := context.Background()
	app, err := a.store.Get(ctx, store.Query{Name: appName})
	if err != nil {
		return err
	}

	err = a.store.Delete(ctx, app)
	if err != nil {
		return err
	}

	return nil
}

func (a *Service) createNewApp(appName string) (*App, error) {
	ctx := context.Background()
	app := App{
		ID:                     uuid.New(),
		Name:                   appName,
		EventSystemCredentials: "amqp://guest:guest@127.0.0.1:5672",
	}

	// generate app credentials
	err := a.store.Add(ctx, app)
	if err != nil {
		return nil, err
	}

	return &app, nil
}