From 3fca309f2c60045ccb2798f84d1314684783eace Mon Sep 17 00:00:00 2001 From: Norwin Date: Mon, 30 Aug 2021 23:19:45 +0800 Subject: [PATCH] Fix adding login without token on private instances (#392) fixes #365 Co-authored-by: Norwin Reviewed-on: https://gitea.com/gitea/tea/pulls/392 Reviewed-by: 6543 <6543@obermui.de> Reviewed-by: Andrew Thornton Co-authored-by: Norwin Co-committed-by: Norwin --- modules/config/login.go | 12 ++++++------ modules/task/login_create.go | 13 +++++++------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/modules/config/login.go b/modules/config/login.go index 0c70edb..47f944c 100644 --- a/modules/config/login.go +++ b/modules/config/login.go @@ -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) } diff --git a/modules/task/login_create.go b/modules/task/login_create.go index b0901c5..f1d5bec 100644 --- a/modules/task/login_create.go +++ b/modules/task/login_create.go @@ -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")