105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
package services
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
// AuthService 认证服务
|
|
type AuthService struct {
|
|
baseURL string
|
|
client *http.Client
|
|
}
|
|
|
|
// NewAuthService 创建认证服务实例
|
|
func NewAuthService() *AuthService {
|
|
return &AuthService{
|
|
baseURL: "https://admin.xiangbing.vip",
|
|
client: &http.Client{
|
|
Timeout: 30 * time.Second,
|
|
},
|
|
}
|
|
}
|
|
|
|
// LoginRequest 登录请求
|
|
type LoginRequest struct {
|
|
Username string `json:"Username"`
|
|
Password string `json:"Password"`
|
|
Platform string `json:"Platform"`
|
|
PcName string `json:"PcName"`
|
|
PcUserName string `json:"PcUserName"`
|
|
Ips string `json:"Ips"`
|
|
}
|
|
|
|
// LoginResponse 登录响应
|
|
type LoginResponse struct {
|
|
Code int `json:"Code"`
|
|
Msg string `json:"Msg"`
|
|
Data interface{} `json:"Data"`
|
|
}
|
|
|
|
// Login 用户登录
|
|
func (s *AuthService) Login(ctx context.Context, username, password string) (*LoginResponse, error) {
|
|
// 获取机器信息
|
|
pcMachineName, _ := os.Hostname()
|
|
pcUserName := os.Getenv("USERNAME")
|
|
if pcUserName == "" {
|
|
pcUserName = os.Getenv("USER")
|
|
}
|
|
|
|
// 获取 IP 地址
|
|
var ips string
|
|
addrs, err := net.InterfaceAddrs()
|
|
if err == nil {
|
|
for _, addr := range addrs {
|
|
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
|
if ipnet.IP.To4() != nil {
|
|
ips = ipnet.IP.String()
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
reqData := LoginRequest{
|
|
Username: username,
|
|
Password: password,
|
|
Platform: "pc",
|
|
PcName: pcMachineName,
|
|
PcUserName: pcUserName,
|
|
Ips: ips,
|
|
}
|
|
|
|
jsonData, err := json.Marshal(reqData)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("序列化请求数据失败: %v", err)
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", s.baseURL+"/api/base/login", bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("创建请求失败: %v", err)
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := s.client.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("请求失败: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
var loginResp LoginResponse
|
|
if err := json.NewDecoder(resp.Body).Decode(&loginResp); err != nil {
|
|
return nil, fmt.Errorf("解析响应失败: %v", err)
|
|
}
|
|
|
|
return &loginResp, nil
|
|
}
|
|
|