userform.go 2.07 KB
Newer Older
Loïck Bonniot's avatar
Loïck Bonniot committed
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
package userform

import (
	"io/ioutil"
	"os"
	osuser "os/user"
	"path/filepath"

	"dfss/dfssc/user"
	"github.com/visualfc/goqt/ui"
)

type Widget struct {
	W *ui.QWidget
}

func NewWidget() *Widget {
	file := ui.NewFileWithName(":/userform/userform.ui")
	loader := ui.NewUiLoader()
	form := loader.Load(file)

	emailField := ui.NewLineEditFromDriver(form.FindChild("emailField"))
	hostField := ui.NewLineEditFromDriver(form.FindChild("hostField"))
	passwordField := ui.NewLineEditFromDriver(form.FindChild("passwordField"))
	passwordField.SetEchoMode(ui.QLineEdit_Password)

	feedbackLabel := ui.NewLabelFromDriver(form.FindChild("feedbackLabel"))
	registerButton := ui.NewPushButtonFromDriver(form.FindChild("registerButton"))

	home := getHomeDir()
	fileDialog := ui.NewFileDialogWithParentCaptionDirectoryFilter(nil, "Select the CA file for the platform", home, "Root Certificates (*.pem);;Any (*.*)")

	// Events

	registerButton.OnClicked(func() {
		form.SetDisabled(true)
		feedbackLabel.SetText("Registration in progress...")
		fileDialog.Open()
	})

	fileDialog.OnFileSelected(func(ca string) {
		fileDialog.Hide()
		caDest := home + "ca.pem"
		_ = copyCA(ca, caDest)

		err := user.Register(
			home+"ca.pem",
			home+"cert.pem",
			home+"key.pem",
			hostField.Text(),
			passwordField.Text(),
			"", "", "", emailField.Text(), 2048,
		)
		if err != nil {
			feedbackLabel.SetText(err.Error())
		} else {
			feedbackLabel.SetText("Registration done! Please check your mails.")
		}
		form.SetDisabled(false)
	})

	fileDialog.OnRejected(func() {
		form.SetDisabled(false)
		feedbackLabel.SetText("Registration aborted.")
	})

	return &Widget{W: form}
}

func getHomeDir() string {
	u, err := osuser.Current()
	if err != nil {
		return ""
	}

	dfssPath := filepath.Join(u.HomeDir, ".dfss")
	if err := os.MkdirAll(dfssPath, os.ModeDir|0700); err != nil {
		return ""
	}

	return dfssPath + string(filepath.Separator)
}

func copyCA(from string, to string) error {
	if from == to {
		return nil
	}

	file, err := ioutil.ReadFile(from)
	if err != nil {
		return err
	}

	return ioutil.WriteFile(to, file, 0600)
}