This repository has been archived by the owner on Nov 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
login.go
146 lines (124 loc) · 4.01 KB
/
login.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
///////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
///////////////////////////////////////////////////////////////////////
package cmd
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/toqueteos/webbrowser"
"github.com/vmware/dispatch/pkg/dispatchcli/i18n"
)
var (
loginLong = i18n.T(`Login to VMware Dispatch.`)
// TODO: Add examples
loginExample = i18n.T(``)
loginDebug = false
)
// NewCmdLogin creates a command to login to VMware Dispatch.
func NewCmdLogin(in io.Reader, out, errOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Short: i18n.T("Login to VMware Dispatch."),
Long: loginLong,
Example: loginExample,
Run: func(cmd *cobra.Command, args []string) {
err := login(in, out, errOut, cmd, args)
CheckErr(err)
},
}
cmd.Flags().BoolVar(&loginDebug, "debug", false, "Extra debug output")
return cmd
}
const (
localServerPath = "/catcher"
remoteServerPath = "/v1/iam/redirect"
oauth2Path = "/v1/iam/oauth2/start"
)
var cookieChan = make(chan string, 1)
func startLocalServer() string {
server := &http.Server{}
http.HandleFunc(localServerPath, func(w http.ResponseWriter, req *http.Request) {
values := req.URL.Query()
cookie := values.Get("cookie")
if cookie == "" {
io.WriteString(w, "Invalid/Error Authorization Cookie.\n")
cookieChan <- ""
} else {
io.WriteString(w, "Cookie received. Please close this page.\n")
cookieChan <- cookie
}
})
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
fmt.Printf("LocalServer: Listen() error: %s\n", err)
}
go func() {
err = server.Serve(listener)
if err != nil && err != http.ErrServerClosed {
fmt.Printf("LocalServer: ListenAndServe() error: %s\n", err)
}
}()
return listener.Addr().String()
}
func login(in io.Reader, out, errOut io.Writer, cmd *cobra.Command, args []string) error {
if dispatchConfig.Token != "" ||
(dispatchConfig.ServiceAccount != "" && dispatchConfig.JWTPrivateKey != "") {
return serviceAccountLogin(in, out, errOut, cmd, args)
}
return oidcLogin(in, out, errOut, cmd, args)
}
// login Dispatch by OIDC
func oidcLogin(in io.Reader, out, errOut io.Writer, cmd *cobra.Command, args []string) error {
localServerHost := startLocalServer()
localServerURI := fmt.Sprintf("http://%s%s", localServerHost, localServerPath)
// note: two redirects involve here.
// first, user get authenticated at OAuth2 endpoint e.g. /oauth2/start
// and if authenticated, will be redirect to identity manager (iam) redirect endpoint
// second, the redirect endpoint retrieves the cookie
// redirect the request to the local server, with cookie as a http parameter
vals := url.Values{
"rd": {
fmt.Sprintf("%s?%s", remoteServerPath, url.Values{
"redirect": {localServerURI},
}.Encode()),
},
}
requestURL := fmt.Sprintf("https://%s%s?%s", dispatchConfig.Host, oauth2Path, vals.Encode())
if dispatchConfig.Port != 443 {
requestURL = fmt.Sprintf("https://%s:%d%s?%s", dispatchConfig.Host, dispatchConfig.Port, oauth2Path, vals.Encode())
}
if loginDebug {
fmt.Fprintf(out, "Logging into: %s\n", requestURL)
}
err := webbrowser.Open(requestURL)
if err != nil {
return errors.Wrap(err, "error opening web browser")
}
cookie := <-cookieChan
if cookie == "" {
fmt.Printf("Failed to login, please try again.")
return nil
}
dispatchConfig.Cookie = cookie
writeConfigFile()
fmt.Printf("You have successfully logged in, cookie saved to %s\n", viper.ConfigFileUsed())
return nil
}
// Login Dispatch by service account
func serviceAccountLogin(in io.Reader, out, errOut io.Writer, cmd *cobra.Command, args []string) (err error) {
_, err = identityManagerClient().Home(context.TODO(), getOrgFromConfig())
if err != nil {
return errors.Wrap(err, "error logging in")
}
writeConfigFile()
fmt.Fprintln(out, "You have successfully logged in")
return nil
}