forked from greenpau/caddy-auth-portal
/
ui.go
294 lines (272 loc) · 8.47 KB
/
ui.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
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
// Copyright 2020 Paul Greenberg greenpau@outlook.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ui
import (
"bytes"
"fmt"
"io/ioutil"
"path"
"strings"
"text/template"
cfgutils "github.com/betrybe/caddy-authorize/pkg/utils/cfg"
)
// Themes stores UI themes.
var Themes = map[string]interface{}{
"basic": true,
}
// Factory represents a collection of HTML templates
// and associated methods for the creation of HTML user interfaces.
type Factory struct {
//TemplatePrefix string `json:"template_prefix,omitempty"`
Templates map[string]*Template `json:"templates,omitempty"`
Title string `json:"title,omitempty"`
LogoURL string `json:"logo_url,omitempty"`
LogoDescription string `json:"logo_description,omitempty"`
RegistrationEnabled bool `json:"registration_enabled,omitempty"`
PasswordRecoveryEnabled bool `json:"password_recovery_enabled,omitempty"`
MfaEnabled bool `json:"mfa_enabled,omitempty"`
// The links visible to anonymous user
PublicLinks []Link `json:"public_links,omitempty"`
// The links visible to authenticated user
PrivateLinks []Link `json:"private_links,omitempty"`
// The authentication realms/domains
Realms []UserRealm `json:"realms,omitempty"`
// The pass to authentication endpoint. This is where
// user credentials will be passed to via POST.
ActionEndpoint string `json:"-"`
CustomCSSPath string `json:"custom_css_path,omitempty"`
CustomJsPath string `json:"custom_js_path,omitempty"`
}
// Template represents a user interface instance, e.g. a single
// HTML page.
type Template struct {
Alias string `json:"alias,omitempty"`
// Path could be `inline`, URL path, or file path
Path string `json:"path,omitempty"`
Template *template.Template `json:"-"`
}
// UserRealm represents a single authentication realm/domain.
type UserRealm struct {
Name string `json:"name,omitempty"`
Label string `json:"label,omitempty"`
}
// Args is a collection of page attributes
// that needs to be passed to Render method.
type Args struct {
Title string
LogoURL string
LogoDescription string
ActionEndpoint string
Message string
MessageType string
PublicLinks []Link
PrivateLinks []Link
Realms []UserRealm
Authenticated bool
Data map[string]interface{}
RegistrationEnabled bool
PasswordRecoveryEnabled bool
MfaEnabled bool
CustomCSSEnabled bool
CustomJsEnabled bool
}
// NewFactory return an instance of a user interface factory.
func NewFactory() *Factory {
return &Factory{
LogoURL: "/assets/images/logo.svg",
LogoDescription: "Authentication Portal",
Templates: make(map[string]*Template),
PublicLinks: []Link{},
PrivateLinks: []Link{},
Realms: []UserRealm{},
}
}
// NewTemplate returns a user interface template
func NewTemplate(s, tp string) (*Template, error) {
var templateBody string
if s == "" {
return nil, fmt.Errorf("the user interface alias cannot be empty")
}
if tp == "" {
return nil, fmt.Errorf("the path to user interface template cannot be empty")
}
tmpl := &Template{
Alias: s,
Path: tp,
}
if tp == "inline" {
if _, exists := PageTemplates[s]; !exists {
return nil, fmt.Errorf("built-in template does not exists: %s", s)
}
templateBody = PageTemplates[s]
} else {
if strings.HasPrefix(tp, "http://") || strings.HasPrefix(tp, "https://") {
return nil, fmt.Errorf("the loading of template from remote URL is not supported yet")
}
// Assuming the template is a file system template
content, err := ioutil.ReadFile(tp)
if err != nil {
return nil, fmt.Errorf("failed to load %s template from %s: %s", s, tp, err)
}
templateBody = string(content)
}
t, err := loadTemplateFromString(s, templateBody)
if err != nil {
return nil, fmt.Errorf("Failed to load %s template from %s: %s", s, tp, err)
}
tmpl.Template = t
return tmpl, nil
}
// GetArgs return an instance of Args. Upon the receipt
// of the arguments, they can be manipulated and passed to
// Factory.Render method. The manipulation means
// adding an error message, appending to the title of a page,
// adding arbitrary data etc.
func (f *Factory) GetArgs() *Args {
args := &Args{
Title: f.Title,
LogoURL: f.LogoURL,
LogoDescription: f.LogoDescription,
PublicLinks: f.PublicLinks,
PrivateLinks: f.PrivateLinks,
Realms: f.Realms,
ActionEndpoint: f.ActionEndpoint,
Data: make(map[string]interface{}),
RegistrationEnabled: f.RegistrationEnabled,
PasswordRecoveryEnabled: f.PasswordRecoveryEnabled,
MfaEnabled: f.MfaEnabled,
}
uiOptions := make(map[string]interface{})
if f.CustomCSSPath != "" {
args.CustomCSSEnabled = true
uiOptions["custom_css_required"] = "yes"
} else {
uiOptions["custom_css_required"] = "no"
}
if f.CustomJsPath != "" {
args.CustomJsEnabled = true
uiOptions["custom_js_required"] = "yes"
} else {
uiOptions["custom_js_required"] = "no"
}
args.Data["ui_options"] = uiOptions
return args
}
// BaseURL sets base URL for the authentication portal.
func (args *Args) BaseURL(s string) {
if !strings.HasPrefix(args.LogoURL, "http") {
args.LogoURL = path.Join(s, args.LogoURL)
}
args.ActionEndpoint = s
}
// AddFrontendLinks adds private links.
func (args *Args) AddFrontendLinks(arr []string) {
for _, encodedArgs := range arr {
parts, err := cfgutils.DecodeArgs(encodedArgs)
if err != nil {
continue
}
lnk := Link{
Title: parts[0],
Link: parts[1],
}
argp := 2
var disabledLink bool
for argp < len(parts) {
switch parts[argp] {
case "target_blank":
lnk.Target = "_blank"
lnk.TargetEnabled = true
case "icon":
argp++
if argp < len(parts) {
lnk.IconName = parts[argp]
lnk.IconEnabled = true
}
case "disabled":
disabledLink = true
break
}
argp++
}
if disabledLink {
continue
}
args.PrivateLinks = append(args.PrivateLinks, lnk)
}
}
// AddBuiltinTemplates adds all built-in template to Factory
func (f *Factory) AddBuiltinTemplates() error {
for name := range PageTemplates {
if err := f.AddBuiltinTemplate(name); err != nil {
return fmt.Errorf("Failed to load built-in template %s: %s", name, err)
}
}
return nil
}
// AddBuiltinTemplate adds a built-in template to Factory
func (f *Factory) AddBuiltinTemplate(name string) error {
if _, exists := f.Templates[name]; exists {
return fmt.Errorf("template %s already defined", name)
}
if _, exists := PageTemplates[name]; !exists {
return fmt.Errorf("built-in template %s does not exists", name)
}
tmpl, err := NewTemplate(name, "inline")
if err != nil {
return err
}
f.Templates[name] = tmpl
return nil
}
// AddTemplate adds a template to Factory.
func (f *Factory) AddTemplate(s, tp string) error {
if _, exists := f.Templates[s]; exists {
return fmt.Errorf("Template already defined: %s", s)
}
tmpl, err := NewTemplate(s, tp)
if err != nil {
return err
}
f.Templates[s] = tmpl
return nil
}
// DeleteTemplates removes all templates from Factory.
func (f *Factory) DeleteTemplates() {
f.Templates = make(map[string]*Template)
return
}
func loadTemplateFromString(s, p string) (*template.Template, error) {
funcMap := template.FuncMap{
"pathjoin": path.Join,
}
t := template.New(s).Funcs(funcMap)
t, err := t.Parse(p)
if err != nil {
return nil, err
}
return t, nil
}
// Render returns a pointer to a data buffer.
func (f *Factory) Render(name string, args *Args) (*bytes.Buffer, error) {
if _, exists := f.Templates[name]; !exists {
return nil, fmt.Errorf("template %s does not exist", name)
}
b := bytes.NewBuffer(nil)
err := f.Templates[name].Template.Execute(b, args)
if err != nil {
return nil, err
}
return b, nil
}