auth/server/userclient.go
2023-10-23 14:23:38 +02:00

102 lines
2.0 KiB
Go

package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"git.t-juice.club/microfilm/users"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
)
type UserClient struct {
BaseURL string
client *http.Client
}
const defaultTimeout time.Duration = 5 * time.Second
func NewUserClient(baseurl string) *UserClient {
return &UserClient{
BaseURL: baseurl,
client: &http.Client{
Transport: otelhttp.NewTransport(http.DefaultTransport),
},
}
}
func (c *UserClient) VerifyUserPassword(ctx context.Context, username, password string) error {
ctx, span := otel.GetTracerProvider().Tracer("").Start(ctx, "verify-user-password")
defer span.End()
ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
defer cancel()
url := fmt.Sprintf("%s/%s/verify", c.BaseURL, username)
body := struct {
Password string `json:"password"`
}{
Password: password,
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(&body); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &buf)
if err != nil {
return err
}
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authentication failed")
}
return nil
}
func (c *UserClient) GetUser(ctx context.Context, identifier string) (users.User, error) {
var u users.User
ctx, span := otel.GetTracerProvider().Tracer("").Start(ctx, "get-user")
defer span.End()
ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
defer cancel()
url := fmt.Sprintf("%s/%s", c.BaseURL, identifier)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return u, err
}
resp, err := c.client.Do(req)
if err != nil {
return u, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return u, fmt.Errorf("authentication failed")
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&u); err != nil {
return u, err
}
return u, nil
}