-
Notifications
You must be signed in to change notification settings - Fork 787
/
create_chat_token.go
201 lines (180 loc) · 5.44 KB
/
create_chat_token.go
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
package cmd
import (
"fmt"
"io"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/chats"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
createChatTokenLong = templates.LongDesc(`
Creates a new User Token for a Chat service
`)
createChatTokenExample = templates.Examples(`
# Add a new User Token for a Chat service
jx create chat token -n jira someUserName
# As above with the password being passed in
jx create git token -n jira -p somePassword someUserName
`)
)
// CreateChatTokenOptions the command line options for the command
type CreateChatTokenOptions struct {
CreateOptions
ServerFlags ServerFlags
Username string
Password string
ApiToken string
Timeout string
}
// NewCmdCreateChatToken creates a command
func NewCmdCreateChatToken(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := &CreateChatTokenOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "token [username]",
Short: "Adds a new token/login for a user on a Chat service server",
Aliases: []string{"login"},
Long: createChatTokenLong,
Example: createChatTokenExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.ServerFlags.addGitServerFlags(cmd)
cmd.Flags().StringVarP(&options.ApiToken, "api-token", "t", "", "The API Token for the user")
cmd.Flags().StringVarP(&options.Timeout, "timeout", "", "", "The timeout if using browser automation to generate the API token (by passing username and password)")
return cmd
}
// Run implements the command
func (o *CreateChatTokenOptions) Run() error {
args := o.Args
if len(args) > 0 {
o.Username = args[0]
}
if len(args) > 1 {
o.ApiToken = args[1]
}
authConfigSvc, err := o.createChatAuthConfigService()
if err != nil {
return err
}
config := authConfigSvc.Config()
server, err := o.findChatServer(config, &o.ServerFlags)
if err != nil {
return err
}
if o.Username == "" {
return fmt.Errorf("No Username specified")
}
userAuth := config.GetOrCreateUserAuth(server.URL, o.Username)
if o.ApiToken != "" {
userAuth.ApiToken = o.ApiToken
}
tokenUrl := chats.ProviderAccessTokenURL(server.Kind, server.URL)
if userAuth.IsInvalid() {
f := func(username string) error {
log.Infof("Please generate an API Token for %s server %s\n", server.Kind, server.Label())
if tokenUrl != "" {
log.Infof("Click this URL %s\n\n", util.ColorInfo(tokenUrl))
}
log.Infof("Then COPY the token and enter in into the form below:\n\n")
return nil
}
err = config.EditUserAuth(server.Label(), userAuth, o.Username, false, o.BatchMode, f, o.In, o.Out, o.Err)
if err != nil {
return err
}
if userAuth.IsInvalid() {
return fmt.Errorf("You did not properly define the user authentication!")
}
}
config.CurrentServer = server.URL
err = authConfigSvc.SaveConfig()
if err != nil {
return err
}
err = o.updateChatCredentialsSecret(server, userAuth)
if err != nil {
log.Warnf("Failed to update chat credentials secret: %v\n", err)
}
log.Infof("Created user %s API Token for chat server %s at %s\n",
util.ColorInfo(o.Username), util.ColorInfo(server.Name), util.ColorInfo(server.URL))
return nil
}
func (o *CreateChatTokenOptions) updateChatCredentialsSecret(server *auth.AuthServer, userAuth *auth.UserAuth) error {
client, curNs, err := o.KubeClientAndNamespace()
if err != nil {
return err
}
ns, _, err := kube.GetDevNamespace(client, curNs)
if err != nil {
return err
}
options := metav1.GetOptions{}
name := kube.ToValidName(kube.SecretJenkinsPipelineChatCredentials + server.Kind + "-" + server.Name)
secrets := client.CoreV1().Secrets(ns)
secret, err := secrets.Get(name, options)
create := false
operation := "update"
labels := map[string]string{
kube.LabelCredentialsType: kube.ValueCredentialTypeUsernamePassword,
kube.LabelCreatedBy: kube.ValueCreatedByJX,
kube.LabelKind: kube.ValueKindIssue,
kube.LabelServiceKind: server.Kind,
}
annotations := map[string]string{
kube.AnnotationCredentialsDescription: fmt.Sprintf("API Token for acccessing %s chat inside pipelines", server.URL),
kube.AnnotationURL: server.URL,
kube.AnnotationName: server.Name,
}
if err != nil {
// lets create a new secret
create = true
operation = "create"
secret = &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Annotations: annotations,
Labels: labels,
},
Data: map[string][]byte{},
}
} else {
secret.Annotations = util.MergeMaps(secret.Annotations, annotations)
secret.Labels = util.MergeMaps(secret.Labels, labels)
}
if userAuth.Username != "" {
secret.Data["username"] = []byte(userAuth.Username)
}
if userAuth.ApiToken != "" {
secret.Data["password"] = []byte(userAuth.ApiToken)
}
if create {
_, err = secrets.Create(secret)
} else {
_, err = secrets.Update(secret)
}
if err != nil {
return fmt.Errorf("Failed to %s secret %s due to %s", operation, secret.Name, err)
}
return nil
}