go-cook-portal/client/auth.go

84 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"
"net/url"
2024-04-09 07:29:45 -07:00
"git.jamestombleson.com/jtom38/go-cook/api/domain"
)
type Auth interface {
Register(username, password string) error
Login(username, password string) (LoginResponse, error)
2024-04-09 07:29:45 -07:00
}
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()
2024-04-09 07:29:45 -07:00
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"`
}
2024-04-09 07:29:45 -07:00
func (a AuthClient) Login(username, password string) (LoginResponse, error) {
endpoint := fmt.Sprintf("%s/api/v1/auth/login", a.serverAddress)
2024-04-09 07:29:45 -07:00
param := url.Values{}
param.Set("username", username)
param.Set("password", password)
2024-04-09 07:29:45 -07:00
var bind = LoginResponse{}
err := PostUrlForm(a.client, endpoint, param, &bind)
2024-04-09 07:29:45 -07:00
if err != nil {
return LoginResponse{}, err
2024-04-09 07:29:45 -07:00
}
return bind, nil
}