auth/server/userclient.go
2023-10-21 10:26:15 +02:00

56 lines
996 B
Go

package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type UserClient struct {
BaseURL string
}
const defaultTimeout time.Duration = 5 * time.Second
func NewUserClient(baseurl string) *UserClient {
return &UserClient{BaseURL: baseurl}
}
func (c *UserClient) VerifyUserPassword(username, password string) error {
ctx, cancel := context.WithTimeout(context.Background(), 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
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authentication failed")
}
return nil
}