summaryrefslogtreecommitdiff
path: root/user.go
blob: f2d014fb17f1314dead1640e7f6ad60de2e3a45e (plain)
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package main

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"log"
	"random.chars.jp/git/image-board/api"
	"random.chars.jp/git/image-board/store"
	"time"
)

var this api.UserPayload
var userMenu = &fyne.Menu{
	Label: "User",
	Items: nil,
}

func initUser() bool {
	if remote.SingleUser() {
		userMenu.Items = []*fyne.MenuItem{{
			Label: "Single User Mode",
		}}
		defer loading("Loading", "Getting initial user information...")()
		if t, err := remote.User(remote.InitialUser); err != nil {
			go dialog.ShowError(err, window)
			return false
		} else {
			this = t
		}
		mainMenuRefresh()
		return true
	}

	secret := getSecret()
	if secret == "" {
		// Do not invoke loading view.
		setPreLogin()
		return false
	}
	defer loading("Loading", "Getting user information...")()
	if u, ok := remote.Secret(secret); u.ID == "" || !ok {
		setPreLogin()
		return false
	} else {
		if u.ID == "" {
			setPreLogin()
			return false
		}
		setUserInfo(u)
		return true
	}
}

func setPreLogin() {
	userMenu.Items = []*fyne.MenuItem{{
		Label:  "Login",
		Action: login,
	}}
	if remote.Register {
		userMenu.Items = append(userMenu.Items, &fyne.MenuItem{
			Label:  "Register",
			Action: register,
		})
	}
	mainMenuRefresh()
}

func setUserInfo(user api.UserPayload) {
	this = user
	log.Printf("Setting user %s.", userString(user))

	userMenu.Items = []*fyne.MenuItem{
		{
			Label:  user.Username,
			Action: func() { displayUserInfo(user) },
		},
		{
			IsSeparator: true,
		},
		{
			Label:  "Change Password",
			Action: changePassword,
		},
		{
			Label:  "Logout",
			Action: logout,
		},
	}
	if this.Privileged {
		userMenu.Items = append(userMenu.Items,
			&fyne.MenuItem{IsSeparator: true},
			&fyne.MenuItem{
				Label:  "Create User",
				Action: register,
			})
	}
	mainMenuRefresh()
}

func displayUserInfo(user api.UserPayload) {
	w := application.NewWindow(user.Username)
	username := &widget.FormItem{
		Text:   "Username",
		Widget: widget.NewLabel(user.Username),
	}
	id := &widget.FormItem{
		Text:   "ID",
		Widget: newLink(user.ID, func() { window.Clipboard().SetContent(user.ID) }),
	}
	admin := &widget.FormItem{
		Text: "Administrator",
		Widget: widget.NewLabel(func() string {
			if user.Privileged {
				return "Yes"
			} else {
				return "No"
			}
		}()),
	}
	form := widget.NewForm(
		username,
		id,
		admin,
	)
	box := container.NewVBox(form)

	// Username entry
	uEntry := widget.NewEntry()
	uEntry.SetText(user.Username)

	// Privileged entry and new value
	pNew := user.Privileged
	var pEntry *widget.Button
	pEntry = widget.NewButton("", func() {
		if pNew {
			pEntry.SetText("No")
			pNew = false
		} else {
			pEntry.SetText("Yes")
			pNew = true
		}
	})
	p := "Yes"
	if !pNew {
		p = "No"
	}
	pEntry.SetText(p)

	if this.Privileged || this.ID == user.ID {
		log.Printf("User %s writable.", user.ID)
		var edit *widget.Button
		edit = widget.NewButton("Edit", func() {
			const (
				e = "Edit"
				d = "Done"
			)

			edit.Disable()
			defer edit.Enable()
			defer func() {
				log.Printf("Resetting user %s window content.", user.ID)
				form = widget.NewForm(
					username,
					id,
					admin,
				)
				box = container.NewVBox(form, edit)
				w.SetContent(box)
			}()

			if edit.Text == d {
				log.Printf("Reverting form of user %s to display.", user.ID)
				if user.Username != uEntry.Text || user.Privileged != pNew {
					s := time.Now()
					if err := remote.UserUpdate(user.ID, uEntry.Text, pNew); err != nil {
						log.Printf("Error updating user %s username %s privileged %v, %s",
							user.ID, uEntry.Text, pNew, err)
						go dialog.ShowError(err, w)
						return
					}
					user.Username = uEntry.Text
					if this.Privileged {
						user.Privileged = pNew
					}
					log.Printf("Updated user %s username %s privileged %v in %s.",
						user.ID, user.Username, user.Privileged, time.Now().Sub(s))
				}
				username.Widget = widget.NewLabel(user.Username)
				admin.Widget = widget.NewLabel(pEntry.Text)
				edit.SetText(e)
				return
			}

			log.Printf("Setting form of user %s to edit.", user.ID)
			edit.SetText(d)
			username.Widget = uEntry
			if this.Privileged {
				admin.Widget = pEntry
			}
		})
		box = container.NewVBox(form, edit)
	}
	w.SetContent(box)
	w.Resize(fyne.Size{
		Width: 512,
	})
	w.SetFixedSize(true)
	w.Show()
}

func login() {
	username := widget.NewEntry()
	username.PlaceHolder = "Username"
	username.MultiLine = false
	password := widget.NewEntry()
	password.PlaceHolder = "Password"
	password.Password = true
	password.MultiLine = false

	diag := dialog.NewForm("Login", "Login", "Cancel", []*widget.FormItem{
		widget.NewFormItem("Username", username),
		widget.NewFormItem("Password", password),
	}, func(submit bool) {
		if !submit {
			return
		}

		if username.Text == "" || password.Text == "" {
			return
		}

		go func() {
			defer loading("Authenticating", "Waiting for server...")()
			s := time.Now()
			if secret, err := remote.Auth(username.Text, password.Text); err != nil {
				go dialog.ShowError(err, window)
			} else {
				log.Printf("Retrieved secret for %s in %s.", username.Text, time.Now().Sub(s))
				s = time.Now()
				if user, ok := remote.Secret(secret); !ok || user.ID == "" {
					log.Printf("Authentication failed in %s.", time.Now().Sub(s))
					// this does look pretty stupid
					// however required because apparently hiding the loading view also destroys the info dialog.
					finalize := make(chan bool)
					info := dialog.NewInformation("Authentication failure",
						"Wasn't able to authenticate, maybe check your password?", window)
					info.SetOnClosed(func() {
						finalize <- true
					})
					info.Show()
					<-finalize
					return
				} else {
					log.Printf("Authenticated with secret %s in %s.", secret, time.Now().Sub(s))
					setSecret(secret)
					setUserInfo(user)
					if remote.Private() {
						setPage(currentPage)
					}
				}
			}
		}()
	}, window)
	diag.Resize(fyne.Size{
		Width: 512,
	})
	diag.Show()
}

func logout() {
	remote.Secret("")
	setSecret("")
	setPreLogin()
	us := userString(this)
	this = api.UserPayload{}
	log.Printf("Logged out of user %s.", us)
}

func register() {
	var (
		username = widget.NewEntry()
		password = widget.NewEntry()
	)
	password.Password = true

	diag := dialog.NewForm("Register", "Register", "Cancel", []*widget.FormItem{
		widget.NewFormItem("Username", username),
		widget.NewFormItem("Password", password),
	}, func(submit bool) {
		if !submit {
			return
		}

		if !store.MatchName(username.Text) || password.Text == "" {
			go dialog.ShowInformation("Invalid input", "Input is invalid.", window)
			return
		}

		go func() {
			defer loading("Creating", "Waiting for server...")()
			s := time.Now()
			if user, err := remote.UserAdd(username.Text, password.Text, false); err != nil {
				log.Printf("Error adding user %s, %s", username.Text, err)
				dialog.ShowError(err, window)
				return
			} else {
				if user.Snowflake == "" {
					log.Printf("Wasn't able to add user %s.", username.Text)
					dialog.ShowInformation("Registration failure",
						"Wasn't able to register. if this problem persists, contact the system administrator.",
						window)
					return
				}
				log.Printf("Created user %s in %s.", user.Username, time.Now().Sub(s))
				dialog.ShowConfirm("Success", "Registration completed successfully, proceed to login?",
					func(submit bool) {
						if !submit {
							return
						}
						go login()
					}, window)
			}
		}()
	}, window)
	diag.Resize(fyne.Size{
		Width: 512,
	})
	diag.Show()
}

func changePassword() {
	newPass := widget.NewEntry()
	newPass.PlaceHolder = "Password"
	newPass.Password = true
	newPass.MultiLine = false
	newPassConf := widget.NewEntry()
	newPassConf.PlaceHolder = "Password (Again)"
	newPassConf.Password = true
	newPassConf.MultiLine = false

	diag := dialog.NewForm("Update password", "Submit", "Cancel", []*widget.FormItem{
		widget.NewFormItem("Password", newPass),
		widget.NewFormItem("Password", newPassConf),
	}, func(submit bool) {
		if !submit {
			return
		}

		if newPass.Text == "" || newPass.Text != newPassConf.Text {
			go dialog.ShowInformation("Invalid input", "Empty passwords are not allowed.", window)
			return
		}

		go func() {
			s := time.Now()
			if secret, err := remote.UserPassword(this.ID, newPass.Text); err != nil {
				log.Printf("Error updating password for %s, %s", this.ID, err)
				dialog.ShowError(err, window)
			} else {
				log.Printf("Password updated for %s in %s.", this.ID, time.Now().Sub(s))
				s = time.Now()
				if user, ok := remote.Secret(secret); !ok {
					log.Printf("Got secret after password update for user %s but wasn't able to authenticate.",
						this.ID)
					dialog.ShowInformation("Authentication error",
						"Got a secret but was unable to authenticate with it.", window)
				} else {
					log.Printf("Fetched user %s after password update in %s.", userString(user), time.Now().Sub(s))
					setSecret(secret)
					setUserInfo(user)
				}
			}
		}()
	}, window)
	diag.Resize(fyne.Size{
		Width: 512,
	})
	diag.Show()
}

func userString(user api.UserPayload) string {
	return fmt.Sprintf("%s (%s) privileged %v", user.Username, user.ID, user.Privileged)
}