auth/server/userclient.go

102 lines
2.0 KiB
Go
Raw Permalink Normal View History

2023-10-21 08:26:15 +00:00
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
2023-10-22 20:59:16 +00:00
"git.t-juice.club/microfilm/users"
2023-10-23 12:23:19 +00:00
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
2023-10-21 08:26:15 +00:00
)
type UserClient struct {
BaseURL string
2023-10-23 12:23:19 +00:00
client *http.Client
2023-10-21 08:26:15 +00:00
}
const defaultTimeout time.Duration = 5 * time.Second
func NewUserClient(baseurl string) *UserClient {
2023-10-23 12:23:19 +00:00
return &UserClient{
BaseURL: baseurl,
client: &http.Client{
Transport: otelhttp.NewTransport(http.DefaultTransport),
},
}
2023-10-21 08:26:15 +00:00
}
2023-10-23 12:23:19 +00:00
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)
2023-10-21 08:26:15 +00:00
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
}
2023-10-23 12:23:19 +00:00
resp, err := c.client.Do(req)
2023-10-21 08:26:15 +00:00
if err != nil {
return err
}
2023-10-23 12:23:19 +00:00
defer resp.Body.Close()
2023-10-21 08:26:15 +00:00
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authentication failed")
}
return nil
}
2023-10-22 20:59:16 +00:00
2023-10-23 12:23:19 +00:00
func (c *UserClient) GetUser(ctx context.Context, identifier string) (users.User, error) {
2023-10-22 20:59:16 +00:00
var u users.User
2023-10-23 12:23:19 +00:00
ctx, span := otel.GetTracerProvider().Tracer("").Start(ctx, "get-user")
defer span.End()
ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
2023-10-22 20:59:16 +00:00
defer cancel()
url := fmt.Sprintf("%s/%s", c.BaseURL, identifier)
2023-10-22 21:10:36 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
2023-10-22 20:59:16 +00:00
if err != nil {
return u, err
}
2023-10-23 12:23:19 +00:00
resp, err := c.client.Do(req)
2023-10-22 20:59:16 +00:00
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
}