Fix adding login without token on private instances #392

Merged
zeripath merged 1 commits from noerw/tea:fix-365 into master 2021-08-30 15:19:46 +00:00
2 changed files with 13 additions and 12 deletions

View File

@ -142,8 +142,9 @@ func AddLogin(login *Login) error {
return saveConfig()
}
// Client returns a client to operate Gitea API
func (l *Login) Client() *gitea.Client {
// Client returns a client to operate Gitea API. You may provide additional modifiers
// for the client like gitea.SetBasicAuth() for customization
func (l *Login) Client(options ...func(*gitea.Client)) *gitea.Client {
httpClient := &http.Client{}
if l.Insecure {
cookieJar, _ := cookiejar.New(nil)
@ -155,10 +156,9 @@ func (l *Login) Client() *gitea.Client {
}}
}
client, err := gitea.NewClient(l.URL,
gitea.SetToken(l.Token),
gitea.SetHTTPClient(httpClient),
)
options = append(options, gitea.SetToken(l.Token), gitea.SetHTTPClient(httpClient))
client, err := gitea.NewClient(l.URL, options...)
if err != nil {
log.Fatal(err)
}

View File

@ -56,14 +56,14 @@ func CreateLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bo
Created: time.Now().Unix(),
}
client := login.Client()
if len(token) == 0 {
if login.Token, err = generateToken(client, user, passwd); err != nil {
if login.Token, err = generateToken(login, user, passwd); err != nil {
return err
}
}
client := login.Client()
// Verify if authentication works and get user info
u, _, err := client.GetMyUserInfo()
if err != nil {
@ -98,16 +98,17 @@ func CreateLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bo
}
// generateToken creates a new token when given BasicAuth credentials
func generateToken(client *gitea.Client, user, pass string) (string, error) {
gitea.SetBasicAuth(user, pass)(client)
func generateToken(login config.Login, user, pass string) (string, error) {
client := login.Client(gitea.SetBasicAuth(user, pass))
host, _ := os.Hostname()
tl, _, err := client.ListAccessTokens(gitea.ListAccessTokensOptions{})
if err != nil {
return "", err
}
host, _ := os.Hostname()
tokenName := host + "-tea"
// append timestamp, if a token with this hostname already exists
for i := range tl {
if tl[i].Name == tokenName {
tokenName += time.Now().Format("2006-01-02_15-04-05")