feat: sync project
This commit is contained in:
64
mengyastore-backend/internal/auth/sproutgate.go
Normal file
64
mengyastore-backend/internal/auth/sproutgate.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultAuthAPIURL = "https://auth.api.shumengya.top"
|
||||
|
||||
type SproutGateClient struct {
|
||||
apiURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type VerifyResult struct {
|
||||
Valid bool `json:"valid"`
|
||||
User *SproutGateUser `json:"user"`
|
||||
}
|
||||
|
||||
type SproutGateUser struct {
|
||||
Account string `json:"account"`
|
||||
Username string `json:"username"`
|
||||
AvatarURL string `json:"avatarUrl"`
|
||||
}
|
||||
|
||||
func NewSproutGateClient(apiURL string) *SproutGateClient {
|
||||
if apiURL == "" {
|
||||
apiURL = defaultAuthAPIURL
|
||||
}
|
||||
return &SproutGateClient{
|
||||
apiURL: apiURL,
|
||||
httpClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SproutGateClient) VerifyToken(token string) (*VerifyResult, error) {
|
||||
body, _ := json.Marshal(map[string]string{"token": token})
|
||||
resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] verify request failed: %v", err)
|
||||
return nil, fmt.Errorf("verify request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
rawBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("[SproutGate] read response body failed: %v", err)
|
||||
return nil, fmt.Errorf("read verify response: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody))
|
||||
|
||||
var result VerifyResult
|
||||
if err := json.Unmarshal(rawBody, &result); err != nil {
|
||||
log.Printf("[SproutGate] decode response failed: %v", err)
|
||||
return nil, fmt.Errorf("decode verify response: %w", err)
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user