File: login_create.go

package info (click to toggle)
tea-cli 0.11.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,648 kB
  • sloc: makefile: 116; sh: 17
file content (201 lines) | stat: -rw-r--r-- 5,684 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package task

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"time"

	"code.gitea.io/tea/modules/config"
	"code.gitea.io/tea/modules/utils"

	"code.gitea.io/sdk/gitea"
)

// SetupHelper add tea helper to config global
func SetupHelper(login config.Login) (ok bool, err error) {
	// Check that the URL is not blank
	if login.URL == "" {
		return false, fmt.Errorf("Invalid gitea url")
	}

	// get all helper to URL in git config
	var currentHelpers []byte
	if currentHelpers, err = exec.Command("git", "config", "--global", "--get-all", fmt.Sprintf("credential.%s.helper", login.URL)).Output(); err != nil {
		currentHelpers = []byte{}
	}

	// Check if ared added tea helper
	for _, line := range strings.Split(strings.ReplaceAll(string(currentHelpers), "\r", ""), "\n") {
		if strings.HasSuffix(strings.TrimSpace(line), "login helper") {
			return false, nil
		}
	}

	// Add tea helper
	if _, err = exec.Command("git", "config", "--global", fmt.Sprintf("credential.%s.helper", login.URL), "").Output(); err != nil {
		return false, fmt.Errorf("git config --global %s, error: %s", fmt.Sprintf("credential.%s.helper", login.URL), err)
	} else if _, err = exec.Command("git", "config", "--global", "--add", fmt.Sprintf("credential.%s.helper", login.URL), "!tea login helper").Output(); err != nil {
		return false, fmt.Errorf("git config --global --add %s %s, error: %s", fmt.Sprintf("credential.%s.helper", login.URL), "!tea login helper", err)
	}

	return true, nil
}

// CreateLogin create a login to be stored in config
func CreateLogin(name, token, user, passwd, otp, scopes, sshKey, giteaURL, sshCertPrincipal, sshKeyFingerprint string, insecure, sshAgent, versionCheck, addHelper bool) error {
	// checks ...
	// ... if we have a url
	if len(giteaURL) == 0 {
		return fmt.Errorf("You have to input Gitea server URL")
	}

	// ... if there already exist a login with same name
	if login := config.GetLoginByName(name); login != nil {
		return fmt.Errorf("login name '%s' has already been used", login.Name)
	}
	// ... if we already use this token
	if login := config.GetLoginByToken(token); login != nil {
		return fmt.Errorf("token already been used, delete login '%s' first", login.Name)
	}

	serverURL, err := utils.ValidateAuthenticationMethod(
		giteaURL,
		token,
		user,
		passwd,
		sshAgent,
		sshKey,
		sshCertPrincipal,
	)
	if err != nil {
		return err
	}

	// check if it's a certificate the principal doesn't matter as the user
	// has explicitly selected this private key
	if _, err := os.Stat(sshKey + "-cert.pub"); err == nil {
		sshCertPrincipal = "yes"
	}

	login := config.Login{
		Name:              name,
		URL:               serverURL.String(),
		Token:             token,
		Insecure:          insecure,
		SSHKey:            sshKey,
		SSHCertPrincipal:  sshCertPrincipal,
		SSHKeyFingerprint: sshKeyFingerprint,
		SSHAgent:          sshAgent,
		Created:           time.Now().Unix(),
		VersionCheck:      versionCheck,
	}

	if len(token) == 0 && sshCertPrincipal == "" && !sshAgent && sshKey == "" {
		if login.Token, err = generateToken(login, user, passwd, otp, scopes); err != nil {
			return err
		}
	}

	client := login.Client()

	// Verify if authentication works and get user info
	u, _, err := client.GetMyUserInfo()
	if err != nil {
		return err
	}
	login.User = u.UserName

	if len(login.Name) == 0 {
		if login.Name, err = GenerateLoginName(giteaURL, login.User); err != nil {
			return err
		}
	}

	// we do not have a method to get SSH config from api,
	// so we just use the host
	login.SSHHost = serverURL.Host

	if len(sshKey) == 0 {
		login.SSHKey, err = findSSHKey(client)
		if err != nil {
			fmt.Printf("Warning: problem while finding a SSH key: %s\n", err)
		}
	}

	if err = config.AddLogin(&login); err != nil {
		return err
	}

	fmt.Printf("Login as %s on %s successful. Added this login as %s\n", login.User, login.URL, login.Name)
	if addHelper {
		if _, err := SetupHelper(login); err != nil {
			return err
		}
	}

	return nil
}

// generateToken creates a new token when given BasicAuth credentials
func generateToken(login config.Login, user, pass, otp, scopes string) (string, error) {
	opts := []gitea.ClientOption{gitea.SetBasicAuth(user, pass)}
	if otp != "" {
		opts = append(opts, gitea.SetOTP(otp))
	}
	client := login.Client(opts...)

	tl, _, err := client.ListAccessTokens(gitea.ListAccessTokensOptions{
		ListOptions: gitea.ListOptions{Page: -1},
	})
	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")
			break
		}
	}

	var tokenScopes []gitea.AccessTokenScope
	if len(scopes) == 0 {
		tokenScopes = []gitea.AccessTokenScope{gitea.AccessTokenScopeAll}
	} else {
		for _, scope := range strings.Split(scopes, ",") {
			tokenScopes = append(tokenScopes, gitea.AccessTokenScope(strings.TrimSpace(scope)))
		}
	}

	t, _, err := client.CreateAccessToken(gitea.CreateAccessTokenOption{
		Name:   tokenName,
		Scopes: tokenScopes,
	})
	return t.Token, err
}

// GenerateLoginName generates a name string based on instance URL & adds username if the result is not unique
func GenerateLoginName(url, user string) (string, error) {
	parsedURL, err := utils.NormalizeURL(url)
	if err != nil {
		return "", err
	}
	name := parsedURL.Host

	// append user name if login name already exists
	if len(user) != 0 {
		if login := config.GetLoginByName(name); login != nil {
			return name + "_" + user, nil
		}
	}

	return name, nil
}