auth/server/userclient.go

91 lines
1.7 KiB
Go

package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"git.t-juice.club/microfilm/users"
)
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
}
func (c *UserClient) GetUser(identifier string) (users.User, error) {
var u users.User
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
url := fmt.Sprintf("%s/%s", c.BaseURL, identifier)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil {
return u, err
}
client := http.Client{}
resp, err := 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
}