-
Notifications
You must be signed in to change notification settings - Fork 33
/
view.go
407 lines (351 loc) · 13 KB
/
view.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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// Source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package aah
import (
"fmt"
"html/template"
"path"
"path/filepath"
"strings"
"aahframe.work/ahttp"
"aahframe.work/internal/settings"
"aahframe.work/internal/util"
"aahframe.work/security"
"aahframe.work/view"
)
const (
defaultViewEngineName = "go"
defaultViewFileExt = ".html"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// app Unexported methods
//______________________________________________________________________________
func (a *Application) initView() error {
viewsDir := path.Join(a.VirtualBaseDir(), "views")
if !a.VFS().IsExists(viewsDir) {
// view directory not exists, scenario could be API, WebSocket application
a.SecurityManager().AntiCSRF.Enabled = false
return nil
}
engineName := a.Config().StringDefault("view.engine", defaultViewEngineName)
viewEngine, found := view.GetEngine(engineName)
if !found {
return fmt.Errorf("view: named engine not found: %s", engineName)
}
viewMgr := &viewManager{
a: a,
engineName: engineName,
fileExt: a.Config().StringDefault("view.ext", defaultViewFileExt),
defaultTmplLayout: "master" + a.Config().StringDefault("view.ext", defaultViewFileExt),
filenameCaseSensitive: a.Config().BoolDefault("view.case_sensitive", false),
defaultLayoutEnabled: a.Config().BoolDefault("view.default_layout", true),
notFoundTmpl: template.Must(template.New("not_found").Parse(`
<strong>{{ .ViewNotFound }}</strong>
`)),
}
// Add Framework template methods
a.AddTemplateFunc(template.FuncMap{
"config": viewMgr.tmplConfig,
"i18n": viewMgr.tmplI18n,
"rurl": viewMgr.tmplURL,
"rurlm": viewMgr.tmplURLm,
"pparam": viewMgr.tmplPathParam,
"fparam": viewMgr.tmplFormParam,
"qparam": viewMgr.tmplQueryParam,
"session": viewMgr.tmplSessionValue,
"flash": viewMgr.tmplFlashValue,
"isauthenticated": viewMgr.tmplIsAuthenticated,
"hasrole": viewMgr.tmplHasRole,
"hasallroles": viewMgr.tmplHasAllRoles,
"hasanyrole": viewMgr.tmplHasAnyRole,
"ispermitted": viewMgr.tmplIsPermitted,
"ispermittedall": viewMgr.tmplIsPermittedAll,
"anticsrftoken": viewMgr.tmplAntiCSRFToken,
})
if err := viewEngine.Init(a.VFS(), a.Config(), viewsDir); err != nil {
return err
}
viewMgr.engine = viewEngine
if a.viewMgr != nil && a.viewMgr.minifier != nil {
viewMgr.minifier = a.viewMgr.minifier
}
a.viewMgr = viewMgr
a.SecurityManager().AntiCSRF.Enabled = true
a.viewMgr.setHotReload(a.IsEnvProfile(settings.DefaultEnvProfile) && !a.IsPackaged())
return nil
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// View Manager
//______________________________________________________________________________
type viewManager struct {
a *Application
engineName string
engine view.Enginer
fileExt string
defaultTmplLayout string
filenameCaseSensitive bool
defaultLayoutEnabled bool
notFoundTmpl *template.Template
minifier MinifierFunc
}
// resolve method resolves the view template based available facts, such as
// controller name, action and user provided inputs.
func (vm *viewManager) resolve(ctx *Context) {
// Resolving view by convention and configuration
reply := ctx.Reply()
if reply.Rdr == nil {
reply.Rdr = &htmlRender{}
}
htmlRdr, ok := reply.Rdr.(*htmlRender)
if !ok || htmlRdr.Template != nil {
// 1. If its not type `htmlRender`, possibly custom render implementation
// 2. Template already populated in it
// So no need to go forward
return
}
if len(htmlRdr.Layout) == 0 && vm.defaultLayoutEnabled {
htmlRdr.Layout = vm.defaultTmplLayout
}
if htmlRdr.ViewArgs == nil {
htmlRdr.ViewArgs = make(map[string]interface{})
}
for k, v := range ctx.ViewArgs() {
if _, found := htmlRdr.ViewArgs[k]; found {
continue
}
htmlRdr.ViewArgs[k] = v
}
// Add ViewArgs values from framework
vm.addFrameworkValuesIntoViewArgs(ctx)
var tmplPath, tmplName string
// If user not provided the template info, auto resolve by convention
if len(htmlRdr.Filename) == 0 {
tmplName = ctx.action.Name + vm.fileExt
tmplPath = filepath.Join(ctx.controller.Namespace, ctx.controller.NoSuffixName)
} else {
// User provided view info like layout, filename.
// Taking full-control of view rendering.
// Scenario's:
// 1. filename with relative path
// 2. filename with root page path
tmplName = filepath.Base(htmlRdr.Filename)
tmplPath = filepath.Dir(htmlRdr.Filename)
if strings.HasPrefix(htmlRdr.Filename, "/") {
tmplPath = strings.TrimLeft(tmplPath, "/")
} else {
tmplPath = filepath.Join(ctx.controller.Namespace, ctx.controller.NoSuffixName, tmplPath)
}
}
tmplPath = filepath.Join("pages", tmplPath)
ctx.Log().Tracef("view(layout:%s path:%s name:%s)", htmlRdr.Layout, tmplPath, tmplName)
var err error
if htmlRdr.Template, err = vm.engine.Get(htmlRdr.Layout, tmplPath, tmplName); err != nil {
if err == view.ErrTemplateNotFound {
tmplFile := filepath.Join("views", tmplPath, tmplName)
if !vm.filenameCaseSensitive {
tmplFile = strings.ToLower(tmplFile)
}
ctx.Log().Errorf("template not found: %s", tmplFile)
if vm.a.IsEnvProfile("prod") {
htmlRdr.ViewArgs["ViewNotFound"] = "View Not Found"
} else {
htmlRdr.ViewArgs["ViewNotFound"] = "View Not Found: " + tmplFile
}
htmlRdr.Layout = ""
htmlRdr.Template = vm.notFoundTmpl
} else {
ctx.Log().Error(err)
}
}
}
func (vm *viewManager) addFrameworkValuesIntoViewArgs(ctx *Context) {
html := ctx.Reply().Rdr.(*htmlRender)
html.ViewArgs["Scheme"] = ctx.Req.Scheme
html.ViewArgs["Host"] = ctx.Req.Host
html.ViewArgs["HTTPMethod"] = ctx.Req.Method
html.ViewArgs["RequestPath"] = ctx.Req.Path
html.ViewArgs["Locale"] = ctx.Req.Locale()
html.ViewArgs["ClientIP"] = ctx.Req.ClientIP()
html.ViewArgs["IsJSONP"] = ctx.Req.IsJSONP()
html.ViewArgs["IsAJAX"] = ctx.Req.IsAJAX()
html.ViewArgs["HTTPReferer"] = ctx.Req.Referer()
html.ViewArgs["AahVersion"] = Version
html.ViewArgs[KeyViewArgRequest] = ctx.Req
if ctx.subject != nil {
html.ViewArgs[KeyViewArgSubject] = ctx.Subject()
}
html.ViewArgs["EnvProfile"] = vm.a.EnvProfile()
html.ViewArgs["AppBuildInfo"] = vm.a.BuildInfo()
}
func (vm *viewManager) setHotReload(v bool) {
if hr, ok := vm.engine.(interface {
SetHotReload(r bool)
}); ok {
hr.SetHotReload(v)
}
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// View Template methods
//______________________________________________________________________________
//
// Request Parameters
//
// tmplPathParam method returns Request Path Param value for the given key.
func (vm *viewManager) tmplPathParam(viewArgs map[string]interface{}, key string) interface{} {
return vm.tmplRequestParameters(viewArgs, "P", key)
}
// tmplFormParam method returns Request Form value for the given key.
func (vm *viewManager) tmplFormParam(viewArgs map[string]interface{}, key string) interface{} {
return vm.tmplRequestParameters(viewArgs, "F", key)
}
// tmplQueryParam method returns Request Query String value for the given key.
func (vm *viewManager) tmplQueryParam(viewArgs map[string]interface{}, key string) interface{} {
return vm.tmplRequestParameters(viewArgs, "Q", key)
}
func (vm *viewManager) tmplRequestParameters(viewArgs map[string]interface{}, fn, key string) interface{} {
req := viewArgs[KeyViewArgRequest].(*ahttp.Request)
switch fn {
case "Q":
return util.SanitizeValue(req.QueryValue(key))
case "F":
return util.SanitizeValue(req.FormValue(key))
case "P":
return util.SanitizeValue(req.PathValue(key))
}
return ""
}
//
// Configuration view functions
//
// tmplConfig method provides access to application config on templates.
func (vm *viewManager) tmplConfig(key string) interface{} {
if value, found := vm.a.Config().Get(key); found {
return util.SanitizeValue(value)
}
vm.a.Log().Warnf("Configuration key not found: '%s'", key)
return ""
}
//
// i18n view functions
//
// tmplI18n method is mapped to Go template func for resolving i18n values.
func (vm *viewManager) tmplI18n(viewArgs map[string]interface{}, key string, args ...interface{}) string {
if locale, ok := viewArgs[keyLocale].(*ahttp.Locale); ok {
if len(args) == 0 {
return vm.a.I18n().Lookup(locale, key)
}
sanatizeArgs := make([]interface{}, 0)
for _, value := range args {
sanatizeArgs = append(sanatizeArgs, util.SanitizeValue(value))
}
return vm.a.I18n().Lookup(locale, key, sanatizeArgs...)
}
return ""
}
//
// Route view functions
//
// tmplURL method returns reverse URL by given route name and args.
// Mapped to Go template func.
func (vm *viewManager) tmplURL(viewArgs map[string]interface{}, args ...interface{}) template.URL {
if len(args) == 0 {
vm.a.Log().Errorf("router: template 'rurl' - route name is empty: %v", args)
return template.URL("#")
}
/* #nosec */
return template.URL(vm.a.Router().CreateRouteURL(viewArgs["Host"].(string), args[0].(string), nil, args[1:]...))
}
// tmplURLm method returns reverse URL by given route name and
// map[string]interface{}. Mapped to Go template func.
func (vm *viewManager) tmplURLm(viewArgs map[string]interface{}, routeName string, args map[string]interface{}) template.URL {
/* #nosec */
return template.URL(vm.a.Router().CreateRouteURL(viewArgs["Host"].(string), routeName, args))
}
//
// Session and Flash view functions
//
// tmplSessionValue method returns session value for the given key. If session
// object unavailable this method returns nil.
func (vm *viewManager) tmplSessionValue(viewArgs map[string]interface{}, key string) interface{} {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
if sub.Session != nil {
value := sub.Session.Get(key)
return util.SanitizeValue(value)
}
}
return nil
}
// tmplFlashValue method returns session value for the given key. If session
// object unavailable this method returns nil.
func (vm *viewManager) tmplFlashValue(viewArgs map[string]interface{}, key string) interface{} {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
if sub.Session != nil {
return util.SanitizeValue(sub.Session.GetFlash(key))
}
}
return nil
}
//
// Security view functions
//
// tmplIsAuthenticated method returns the value of `Session.IsAuthenticated`.
func (vm *viewManager) tmplIsAuthenticated(viewArgs map[string]interface{}) bool {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
if sub.Session != nil {
return sub.Session.IsAuthenticated
}
}
return false
}
// tmplHasRole method returns the value of `Subject.HasRole`.
func (vm *viewManager) tmplHasRole(viewArgs map[string]interface{}, role string) bool {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
return sub.HasRole(role)
}
return false
}
// tmplHasAllRoles method returns the value of `Subject.HasAllRoles`.
func (vm *viewManager) tmplHasAllRoles(viewArgs map[string]interface{}, roles ...string) bool {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
return sub.HasAllRoles(roles...)
}
return false
}
// tmplHasAnyRole method returns the value of `Subject.HasAnyRole`.
func (vm *viewManager) tmplHasAnyRole(viewArgs map[string]interface{}, roles ...string) bool {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
return sub.HasAnyRole(roles...)
}
return false
}
// tmplIsPermitted method returns the value of `Subject.IsPermitted`.
func (vm *viewManager) tmplIsPermitted(viewArgs map[string]interface{}, permission string) bool {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
return sub.IsPermitted(permission)
}
return false
}
// tmplIsPermittedAll method returns the value of `Subject.IsPermittedAll`.
func (vm *viewManager) tmplIsPermittedAll(viewArgs map[string]interface{}, permissions ...string) bool {
if sub := vm.getSubjectFromViewArgs(viewArgs); sub != nil {
return sub.IsPermittedAll(permissions...)
}
return false
}
// tmplAntiCSRFToken method returns the salted Anti-CSRF secret for the view,
// if enabled otherwise empty string.
func (vm *viewManager) tmplAntiCSRFToken(viewArgs map[string]interface{}) string {
if vm.a.SecurityManager().AntiCSRF.Enabled {
if cs, found := viewArgs[keyAntiCSRF]; found {
return vm.a.SecurityManager().AntiCSRF.SaltCipherSecret(cs.([]byte))
}
}
return ""
}
func (vm *viewManager) getSubjectFromViewArgs(viewArgs map[string]interface{}) *security.Subject {
if sv, found := viewArgs[KeyViewArgSubject]; found {
return sv.(*security.Subject)
}
return nil
}