enbas/internal/client/register.go

58 lines
1.3 KiB
Go
Raw Normal View History

package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"codeflow.dananglin.me.uk/apollo/enbas/internal"
2024-02-22 03:22:03 +00:00
"codeflow.dananglin.me.uk/apollo/enbas/internal/model"
)
type RegisterRequest struct {
ClientName string `json:"client_name"`
RedirectUris string `json:"redirect_uris"`
Scopes string `json:"scopes"`
Website string `json:"website"`
}
func (g *Client) Register() error {
params := RegisterRequest{
ClientName: internal.ApplicationName,
RedirectUris: internal.RedirectUri,
Scopes: "read write",
Website: internal.ApplicationWebsite,
}
data, err := json.Marshal(params)
if err != nil {
return fmt.Errorf("unable to marshal the request body; %w", err)
}
requestBody := bytes.NewBuffer(data)
path := "/api/v1/apps"
url := g.Authentication.Instance + path
ctx, cancel := context.WithTimeout(context.Background(), g.Timeout)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, requestBody)
if err != nil {
return fmt.Errorf("unable to create the HTTP request; %w", err)
}
2024-02-22 03:22:03 +00:00
var app model.Application
2024-02-22 03:22:03 +00:00
if err := g.sendRequest(request, &app); err != nil {
return fmt.Errorf("received an error after sending the registration request; %w", err)
}
2024-02-22 03:22:03 +00:00
g.Authentication.ClientID = app.ClientID
g.Authentication.ClientSecret = app.ClientSecret
return nil
}