Files
fnx_web/webcontroller/template_data.go

73 lines
1.7 KiB
Go
Raw Normal View History

package webcontroller
import (
2018-06-21 23:41:50 +02:00
"html/template"
"net/http"
2019-02-07 23:09:54 +01:00
"net/url"
2018-06-23 21:17:53 +02:00
"time"
"fornaxian.com/pixeldrain-web/pixelapi"
"fornaxian.com/pixeldrain-web/webcontroller/forms"
2018-06-23 21:17:53 +02:00
"github.com/Fornaxian/log"
)
// TemplateData is a struct that every template expects when being rendered. In
// the field Other you can pass your own template-specific variables.
type TemplateData struct {
Authenticated bool
Username string
UserStyle template.CSS
2018-06-21 23:41:50 +02:00
APIEndpoint template.URL
2018-07-09 21:41:17 +02:00
PixelAPI *pixelapi.PixelAPI
// Only used on file viewer page
Title string
OGData OGData
Other interface{}
URLQuery url.Values
// Only used for pages containing forms
Form forms.Form
}
2018-06-23 21:17:53 +02:00
func (wc *WebController) newTemplateData(w http.ResponseWriter, r *http.Request) *TemplateData {
2018-06-21 23:41:50 +02:00
var t = &TemplateData{
Authenticated: false,
2018-07-08 14:40:20 +02:00
Username: "",
UserStyle: userStyle(r),
2018-06-21 23:41:50 +02:00
APIEndpoint: template.URL(wc.conf.APIURLExternal),
2019-02-07 23:09:54 +01:00
URLQuery: r.URL.Query(),
2018-06-21 23:41:50 +02:00
}
2018-06-23 21:17:53 +02:00
if key, err := wc.getAPIKey(r); err == nil {
2018-07-09 21:41:17 +02:00
t.PixelAPI = pixelapi.New(wc.conf.APIURLInternal, key)
uinf, err := t.PixelAPI.UserInfo()
2018-06-23 21:17:53 +02:00
if err != nil {
// This session key doesn't work, or the backend is down, user
// cannot be authenticated
2018-07-09 21:41:17 +02:00
log.Debug("Session check for key '%s' failed: %s", key, err)
2019-03-28 11:39:13 +01:00
if err.Error() == "authentication_required" || err.Error() == "authentication_failed" {
// This key is invalid, delete it
log.Debug("Deleting invalid API key")
http.SetCookie(w, &http.Cookie{
Name: "pd_auth_key",
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
})
}
2018-06-23 21:17:53 +02:00
return t
}
// Authentication succeeded
t.Authenticated = true
t.Username = uinf.Username
2018-07-09 21:41:17 +02:00
} else {
t.PixelAPI = pixelapi.New(wc.conf.APIURLInternal, "")
2018-06-23 21:17:53 +02:00
}
return t
}