mirror of
https://github.com/Dvorinka/Productier.git
synced 2026-06-04 20:43:02 +00:00
67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
package authsession
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type User struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
}
|
|
|
|
type sessionEnvelope struct {
|
|
User *User `json:"user"`
|
|
}
|
|
|
|
type Client struct {
|
|
baseURL string
|
|
httpClient *http.Client
|
|
}
|
|
|
|
func NewClient(baseURL string) *Client {
|
|
return &Client{
|
|
baseURL: strings.TrimRight(baseURL, "/"),
|
|
httpClient: &http.Client{
|
|
Timeout: 5 * time.Second,
|
|
},
|
|
}
|
|
}
|
|
|
|
func (c *Client) GetUser(ctx context.Context, cookieHeader string) (*User, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/auth/get-session", nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create auth session request: %w", err)
|
|
}
|
|
|
|
if cookieHeader != "" {
|
|
req.Header.Set("Cookie", cookieHeader)
|
|
}
|
|
|
|
res, err := c.httpClient.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("request auth session: %w", err)
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("auth session status: %s", res.Status)
|
|
}
|
|
|
|
var payload *sessionEnvelope
|
|
if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
|
|
return nil, fmt.Errorf("decode auth session: %w", err)
|
|
}
|
|
|
|
if payload == nil || payload.User == nil {
|
|
return nil, nil
|
|
}
|
|
|
|
return payload.User, nil
|
|
}
|