go-cook-portal/client/auth.go

88 lines
1.7 KiB
Go
Raw Normal View History

2024-04-09 07:29:45 -07:00
package client
import (
"encoding/json"
"fmt"
"io"
"net/http"
"git.jamestombleson.com/jtom38/go-cook/api/domain"
)
type Auth interface {
Register(username, password string) error
Login(username, password string) error
}
type AuthClient struct {
serverAddress string
client http.Client
}
func newAuthClient(serverAddress string) AuthClient {
return AuthClient{
serverAddress: serverAddress,
client: http.Client{},
}
}
func (a AuthClient) Register(username, password string) error {
endpoint := fmt.Sprintf("%s/api/v1/auth/register", a.serverAddress)
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return err
}
req.Header.Set(HeaderContentType, MIMEApplicationForm)
req.Form.Add("username", username)
req.Form.Add("password", password)
resp, err := a.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
var bind = domain.ErrorResponse{}
err = json.Unmarshal(content, &bind)
if err != nil {
return err
}
return nil
}
func (a AuthClient) Login(username, password string) error {
endpoint := fmt.Sprintf("%s/api/v1/auth/register", a.serverAddress)
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return err
}
req.Header.Set(HeaderContentType, MIMEApplicationForm)
req.Form.Add("username", username)
req.Form.Add("password", password)
resp, err := a.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
content, err := io.ReadAll(req.Body)
if err != nil {
return err
}
var bind = domain.ErrorResponse{}
err = json.Unmarshal(content, &bind)
if err != nil {
return err
}
return nil
}