-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
profilehttp.go
102 lines (82 loc) · 2.14 KB
/
profilehttp.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
package home
import (
"encoding/json"
"fmt"
"net/http"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/log"
)
// Theme is an enum of all allowed UI themes.
type Theme string
// Allowed [Theme] values.
//
// Keep in sync with client/src/helpers/constants.js.
const (
ThemeAuto Theme = "auto"
ThemeLight Theme = "light"
ThemeDark Theme = "dark"
)
// UnmarshalText implements [encoding.TextUnmarshaler] interface for *Theme.
func (t *Theme) UnmarshalText(b []byte) (err error) {
switch string(b) {
case "auto":
*t = ThemeAuto
case "dark":
*t = ThemeDark
case "light":
*t = ThemeLight
default:
return fmt.Errorf("invalid theme %q, supported: %q, %q, %q", b, ThemeAuto, ThemeDark, ThemeLight)
}
return nil
}
// profileJSON is an object for /control/profile and /control/profile/update
// endpoints.
type profileJSON struct {
Name string `json:"name"`
Language string `json:"language"`
Theme Theme `json:"theme"`
}
// handleGetProfile is the handler for GET /control/profile endpoint.
func handleGetProfile(w http.ResponseWriter, r *http.Request) {
u := Context.auth.getCurrentUser(r)
var resp profileJSON
func() {
config.RLock()
defer config.RUnlock()
resp = profileJSON{
Name: u.Name,
Language: config.Language,
Theme: config.Theme,
}
}()
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// handlePutProfile is the handler for PUT /control/profile/update endpoint.
func handlePutProfile(w http.ResponseWriter, r *http.Request) {
if aghhttp.WriteTextPlainDeprecated(w, r) {
return
}
profileReq := &profileJSON{}
err := json.NewDecoder(r.Body).Decode(profileReq)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
return
}
lang := profileReq.Language
if !allowedLanguages.Has(lang) {
aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang)
return
}
theme := profileReq.Theme
func() {
config.Lock()
defer config.Unlock()
config.Language = lang
config.Theme = theme
log.Printf("home: language is set to %s", lang)
log.Printf("home: theme is set to %s", theme)
}()
onConfigModified()
aghhttp.OK(w)
}