70 lines
1.4 KiB
Go
70 lines
1.4 KiB
Go
package common
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"k8s.io/apimachinery/pkg/util/json"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
USER = "admin"
|
|
PASSWORD = "Nudt@123"
|
|
DOMAIN = "Default"
|
|
TokenUrl = "http://10.105.20.9:5000/v3/auth/tokens?nocatalog"
|
|
Status_created = 201
|
|
ProjectName = "Default"
|
|
TokenHeader = "X-Subject-Token"
|
|
AuthMethod = "password"
|
|
)
|
|
|
|
var (
|
|
token, expiredAt = GenerateToken()
|
|
)
|
|
|
|
func GenerateToken() (string, time.Time) {
|
|
a := Auth{}
|
|
a.Auth.Scope.Project.Name = USER
|
|
a.Auth.Scope.Project.Domain.Name = ProjectName
|
|
a.Auth.Identity.Methods = append(a.Auth.Identity.Methods, AuthMethod)
|
|
a.Auth.Identity.Password.User.Name = USER
|
|
a.Auth.Identity.Password.User.Password = PASSWORD
|
|
a.Auth.Identity.Password.User.Domain.Name = DOMAIN
|
|
|
|
jsonStr, _ := json.Marshal(a)
|
|
req_url, err := http.NewRequest("POST", TokenUrl, bytes.NewBuffer(jsonStr))
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
c := http.Client{Timeout: time.Duration(3) * time.Second}
|
|
|
|
respUrl, err := c.Do(req_url)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
if respUrl.StatusCode != Status_created {
|
|
panic("获取token失败")
|
|
}
|
|
|
|
defer respUrl.Body.Close()
|
|
|
|
var t Token
|
|
|
|
result, _ := io.ReadAll(respUrl.Body)
|
|
json.Unmarshal(result, &t)
|
|
|
|
return respUrl.Header.Get(TokenHeader), t.Token.ExpiresAt
|
|
}
|
|
|
|
func GetToken() string {
|
|
if time.Now().After(expiredAt) {
|
|
token, expiredAt = GenerateToken()
|
|
}
|
|
return token
|
|
}
|