2026-03-13 20:43:44 +08:00
|
|
|
package auth
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
2026-06-09 23:08:03 +08:00
|
|
|
"log/slog"
|
2026-03-13 20:43:44 +08:00
|
|
|
"net/http"
|
|
|
|
|
"regexp"
|
|
|
|
|
"strings"
|
|
|
|
|
|
2026-03-16 13:40:53 +08:00
|
|
|
"schedule_converter/client"
|
|
|
|
|
"schedule_converter/config"
|
2026-03-13 20:43:44 +08:00
|
|
|
)
|
|
|
|
|
|
2026-06-09 23:08:03 +08:00
|
|
|
var nameRegexp = regexp.MustCompile(`(\w+)同学`)
|
2026-03-13 20:43:44 +08:00
|
|
|
|
|
|
|
|
// LoginWithClient 使用指定的 HTTP 客户端和凭据登录
|
|
|
|
|
func LoginWithClient(httpClient *http.Client, captchaCode, username, password string) (bool, error) {
|
2026-06-09 23:08:03 +08:00
|
|
|
log := slog.With("username", username)
|
|
|
|
|
log.Debug("执行登录")
|
2026-03-13 20:43:44 +08:00
|
|
|
|
|
|
|
|
data := fmt.Sprintf("usercode=%s&password=%s&code=%s", username, password, captchaCode)
|
2026-06-09 23:08:03 +08:00
|
|
|
req, err := http.NewRequest("POST", config.Get().BaseURL+"/login", strings.NewReader(data))
|
2026-03-13 20:43:44 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return false, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.Header = client.GetHeadersWithContentType("application/x-www-form-urlencoded")
|
|
|
|
|
|
|
|
|
|
resp, err := httpClient.Do(req)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return false, err
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return false, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 23:08:03 +08:00
|
|
|
bodyStr := string(body)
|
|
|
|
|
if client.CheckLoginSuccess(bodyStr) {
|
|
|
|
|
if match := nameRegexp.FindStringSubmatch(bodyStr); len(match) > 1 {
|
|
|
|
|
log.Info("登录成功", "name", match[1])
|
2026-03-13 20:43:44 +08:00
|
|
|
} else {
|
2026-06-09 23:08:03 +08:00
|
|
|
log.Info("登录成功")
|
2026-03-13 20:43:44 +08:00
|
|
|
}
|
|
|
|
|
return true, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 23:08:03 +08:00
|
|
|
if client.IsCaptchaError(bodyStr) {
|
|
|
|
|
log.Warn("登录失败:验证码错误")
|
|
|
|
|
} else {
|
|
|
|
|
log.Warn("登录失败")
|
2026-03-13 20:43:44 +08:00
|
|
|
}
|
|
|
|
|
return false, nil
|
2026-06-09 23:08:03 +08:00
|
|
|
}
|