ai_scheduler/internal/pkg/lsxd/login.go

121 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package lsxd
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/data/constants"
"ai_scheduler/internal/pkg/l_request"
"ai_scheduler/utils"
"context"
"encoding/json"
"github.com/go-kratos/kratos/v2/log"
"github.com/redis/go-redis/v9"
)
type Login struct {
config *config.Config
redisCli *redis.Client
}
func NewLogin(config *config.Config, rdb *utils.Rdb) *Login {
return &Login{
config: config,
redisCli: rdb.Rdb,
}
}
func (l *Login) GetToken() string {
ctx := context.Background()
// 1.取缓存
token, err := l.redisCli.Get(ctx, constants.CACHE_KEY_LSXD_TOKEN).Result()
if err != nil {
log.Errorf("lsxd get token from redis failed, err: %v", err)
}
// 2.缓存存在
if token != "" {
// 3.缓存有效直接输出
if l.checkTokenValid(token) {
return token
}
}
// 4.缓存不存在或缓存无效调用登录接口获取token
token, err = l.login()
if err != nil {
log.Errorf("lsxd login failed, err: %v", err)
return ""
}
// 5.缓存token
l.redisCli.Set(ctx, constants.CACHE_KEY_LSXD_TOKEN, token, constants.EXPIRE_LSXD_TOKEN)
return token
}
// 校验token是否有效
func (l *Login) checkTokenValid(token string) bool {
// 欢迎页校验token有效
checkTokenURL := l.config.LSXD.CheckTokenURL
// 调用欢迎页校验token有效
r := l_request.Request{
Url: checkTokenURL,
Headers: map[string]string{
"Content-Type": "application/json",
"Authorization": token,
},
Method: "GET",
}
res, err := r.Send()
if err != nil {
log.Errorf("lsxd check token valid failed, err: %v", err)
return false
}
if res.StatusCode != 200 {
log.Errorf("lsxd check token valid failed, status code: %d", res.StatusCode)
return false
}
log.Info("lsxd check token valid success")
return true
}
// 调用登录接口获取token
func (l *Login) login() (string, error) {
// 1.获取配置
loginURL := l.config.LSXD.LoginURL
phone := l.config.LSXD.Phone
password := l.config.LSXD.Password
// 2.调用登录接口获取token
r := l_request.Request{
Url: loginURL,
Headers: map[string]string{
"Content-Type": "application/json",
},
Method: "POST",
Json: map[string]any{
"phone": phone,
"password": password,
"code": "123456",
},
}
res, err := r.Send()
if err != nil {
return "", err
}
// 3.解析token
var resp struct {
Token string `json:"accessToken"`
}
err = json.Unmarshal(res.Content, &resp)
if err != nil {
return "", err
}
token := resp.Token
// 4.返回token
return token, nil
}