go-cook-portal/client/auth.go

84 lines
1.7 KiB
Go

package client
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"git.jamestombleson.com/jtom38/go-cook/api/domain"
)
type Auth interface {
Register(username, password string) error
Login(username, password string) (LoginResponse, 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
}
type LoginResponse struct {
Success bool `json:"success"`
Token string `json:"token"`
Type string `json:"type"`
RefreshToken string `json:"refreshToken"`
}
func (a AuthClient) Login(username, password string) (LoginResponse, error) {
endpoint := fmt.Sprintf("%s/api/v1/auth/login", a.serverAddress)
param := url.Values{}
param.Set("username", username)
param.Set("password", password)
var bind = LoginResponse{}
err := PostUrlForm(a.client, endpoint, param, &bind)
if err != nil {
return LoginResponse{}, err
}
return bind, nil
}