Skip to content
This repository was archived by the owner on Sep 28, 2021. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
login
  • Loading branch information
axelssonHakan committed Nov 29, 2019
commit 5225dc61fc3e93fb18e9c7c4eae81bad8eaacfeb
26 changes: 24 additions & 2 deletions cmd/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ var clearContextCmd = &cobra.Command{
Args: cobra.ExactArgs(0),
Short: "Set the current context to none",
Long: "Set the current context to none",
Example: "corectl clear",
Example: "corectl context clear",

Run: func(ccmd *cobra.Command, args []string) {
previous := internal.ClearContext()
Expand All @@ -109,6 +109,28 @@ var clearContextCmd = &cobra.Command{
},
}

var loginContextCmd = &cobra.Command{
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved
Use: "login <context-name> <username> <password>",
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved
Args: cobra.RangeArgs(1, 3),
Short: "Login and set cookie for the named context",
Long: "Login and set cookie for the named context",
Example: "corectl context login",
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved

Run: func(ccmd *cobra.Command, args []string) {
var contextName, userName, password string
switch len(args) {
case 3:
contextName, userName, password = args[0], args[1], args[2]
case 2:
contextName, userName, password = args[0], args[1], ""
case 1:
contextName, userName, password = args[0], "", ""
}

internal.LoginContext(tlsClientConfig, contextName, userName, password)
},
}

var contextCmd = &cobra.Command{
Use: "context",
Short: "Create, update and use contexts",
Expand All @@ -134,5 +156,5 @@ Contexts are stored locally in your ~/.corectl/contexts.yml file.`,
}

func init() {
contextCmd.AddCommand(setContextCmd, removeContextCmd, listContextsCmd, useContextCmd, getContextCmd, clearContextCmd)
contextCmd.AddCommand(setContextCmd, removeContextCmd, listContextsCmd, useContextCmd, getContextCmd, clearContextCmd, loginContextCmd)
}
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func skipPreRun(ccmd *cobra.Command) bool {
return true
// For contexts we only want to do a prerun for context set.
case strings.Contains(path, "context"):
if strings.Contains(path, "context set") {
if strings.Contains(path, "context set") || strings.Contains(path, "context login") {
return false
}
return true
Expand Down
107 changes: 107 additions & 0 deletions internal/context.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
package internal

import (
"bufio"
"crypto/rand"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"reflect"
"regexp"
"strings"
"syscall"

"github.com/qlik-oss/corectl/internal/log"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh/terminal"
"gopkg.in/yaml.v2"
)

Expand Down Expand Up @@ -106,6 +114,21 @@ func ClearContext() string {
return previous
}

// LoginContext login to a Qlik Sense Enterprise and sets the X-Qlik-Session as a cookie
func LoginContext(tlsClientConfig *tls.Config, contextName string, userName string, password string) {
handler := NewContextHandler()
context := handler.Get(contextName)
qlikSession := getSessionCookie(tlsClientConfig, context.Engine, userName, password)

// cookie := context.Headers["cookie"]
re := regexp.MustCompile(`X-Qlik-Session=[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`)
context.Headers["cookie"] = re.ReplaceAllString(context.Headers["cookie"], qlikSession)

// m := context.ToMap()
// context.Update(&m)
handler.Save()
}

// NewContextHandler helps with handeling contexts
func NewContextHandler() *ContextHandler {
handler := &ContextHandler{}
Expand Down Expand Up @@ -284,3 +307,87 @@ func createContextFileIfNotExist() {
log.Verboseln("Created ~/.corectl/contexts.yml for storage of corectl contexts")
}
}

func getSessionCookie(tlsClientConfig *tls.Config, engineURL string, userName string, password string) string {
// Verify Qlik Sense URL
u, err := url.Parse(engineURL)

if err != nil {
log.Fatalln("The engineURL doesn't seem to be correct")
}

if u.Scheme != "https" {
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved
log.Fatalln("We only support login through secure connections (HTTPS)")
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved
}

// Get username
if len(userName) == 0 {
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Username (domain\\user): ")
userName, _ = reader.ReadString('\n')
}

if !strings.Contains(userName, "\\") {
log.Fatalln("username MUST be in format 'domain\\user'")
}

// Get password
if len(password) == 0 {
fmt.Print("Enter Password: ")
bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
password = string(bytePassword)
}

// Enable selfsigned certs
http.DefaultTransport.(*http.Transport).TLSClientConfig = tlsClientConfig

// Get post URL via redirects
resp, err := http.Get(engineURL)

if err != nil {
log.Fatalln(err)
}

// Generate xrfkey
xrfkey := generateXrfkey()

//
loginURL := resp.Request.URL
q, _ := url.ParseQuery(loginURL.RawQuery)
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved
q.Add("xrfkey", xrfkey)
loginURL.RawQuery = q.Encode()

urlData := url.Values{}
urlData.Set("username", userName)
urlData.Set("pwd", password)

hc := http.Client{}
req, err := http.NewRequest("POST", loginURL.String(), strings.NewReader(urlData.Encode()))
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved

req.PostForm = urlData
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("x-qlik-xrfkey", xrfkey)

postResp, postErr := hc.Do(req)
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved

if postErr != nil {
log.Fatalln(postErr)
}

setCookie := postResp.Header.Get("Set-Cookie")

return strings.TrimRight(strings.Fields(setCookie)[0], ";")
}

func generateXrfkey() (xrfkey string) {
Comment thread
axelssonHakan marked this conversation as resolved.
Resolved

b := make([]byte, 8)
_, err := rand.Read(b)

if err != nil {
log.Fatalln("Error: ", err)
}

xrfkey = fmt.Sprintf("%X", b)
return
}
⌂ 换网址