change how config is loaded

This commit is contained in:
2019-12-30 13:00:00 +01:00
parent 7b5723705c
commit efd9f716eb
9 changed files with 71 additions and 49 deletions

View File

@@ -1,20 +0,0 @@
package conf
type PixelWebConfig struct {
APIURLExternal string `toml:"api_url_external"`
APIURLInternal string `toml:"api_url_internal"`
SessionCookieDomain string `toml:"session_cookie_domain"`
ResourceDir string `toml:"resource_dir"`
DebugMode bool `toml:"debug_mode"`
MaintenanceMode bool `toml:"maintenance_mode"`
}
const DefaultConfig = `# Pixeldrain Web UI server configuration
api_url_external = "/api" # Used in the web browser
api_url_internal = "http://127.0.0.1:8080" # Used for internal API requests to the pixeldrain server, not visible to users
session_cookie_domain = ".pixeldrain.com"
resource_dir = "res"
debug_mode = false
maintenance_mode = false
`

View File

@@ -3,20 +3,40 @@ package init
import ( import (
"os" "os"
"fornaxian.com/pixeldrain-web/init/conf"
"fornaxian.com/pixeldrain-web/webcontroller" "fornaxian.com/pixeldrain-web/webcontroller"
"github.com/Fornaxian/config" "github.com/Fornaxian/config"
"github.com/Fornaxian/log" "github.com/Fornaxian/log"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
) )
// PixelWebConfig contains the Pixeldrain Web UI configuration
type PixelWebConfig struct {
APIURLExternal string `toml:"api_url_external"`
APIURLInternal string `toml:"api_url_internal"`
SessionCookieDomain string `toml:"session_cookie_domain"`
ResourceDir string `toml:"resource_dir"`
DebugMode bool `toml:"debug_mode"`
MaintenanceMode bool `toml:"maintenance_mode"`
}
// DefaultConfig is the default configuration for Pixeldrain Web
const DefaultConfig = `# Pixeldrain Web UI server configuration
api_url_external = "/api" # Used in the web browser
api_url_internal = "http://127.0.0.1:8080" # Used for internal API requests to the pixeldrain server, not visible to users
session_cookie_domain = ".pixeldrain.com"
resource_dir = "res"
debug_mode = false
maintenance_mode = false
`
// Init initializes the Pixeldrain Web UI controllers // Init initializes the Pixeldrain Web UI controllers
func Init(r *httprouter.Router, prefix string, setLogLevel bool) { func Init(r *httprouter.Router, prefix string, setLogLevel bool) {
log.Info("Starting web UI server (PID %v)", os.Getpid()) log.Info("Starting web UI server (PID %v)", os.Getpid())
var webconf = &conf.PixelWebConfig{} var webconf = &PixelWebConfig{}
var _, err = config.New( var _, err = config.New(
conf.DefaultConfig, DefaultConfig,
"", "",
"pdwebconf.toml", "pdwebconf.toml",
webconf, webconf,
@@ -31,5 +51,14 @@ func Init(r *httprouter.Router, prefix string, setLogLevel bool) {
log.SetLogLevel(log.LevelInfo) log.SetLogLevel(log.LevelInfo)
} }
webcontroller.New(r, prefix, webconf) webcontroller.New(
r,
prefix,
webconf.ResourceDir,
webconf.APIURLInternal,
webconf.APIURLExternal,
webconf.SessionCookieDomain,
webconf.MaintenanceMode,
webconf.DebugMode,
)
} }

View File

@@ -28,7 +28,7 @@ func (wc *WebController) serveFilePreview(w http.ResponseWriter, r *http.Request
return return
} }
apikey, _ := wc.getAPIKey(r) apikey, _ := wc.getAPIKey(r)
var api = pixelapi.New(wc.conf.APIURLInternal, apikey) var api = pixelapi.New(wc.apiURLInternal, apikey)
api.RealIP = util.RemoteAddress(r) api.RealIP = util.RemoteAddress(r)
inf, err := api.GetFileInfo(p.ByName("id"), "?should_a_view_be_added=yes_gimme") // TODO: Error handling inf, err := api.GetFileInfo(p.ByName("id"), "?should_a_view_be_added=yes_gimme") // TODO: Error handling
if err != nil { if err != nil {
@@ -37,7 +37,7 @@ func (wc *WebController) serveFilePreview(w http.ResponseWriter, r *http.Request
} }
var fp = filePreview{ var fp = filePreview{
APIURL: wc.conf.APIURLExternal, APIURL: wc.apiURLExternal,
PixelAPI: api, PixelAPI: api,
} }
io.WriteString(w, fp.run(inf)) io.WriteString(w, fp.run(inf))

View File

@@ -32,7 +32,7 @@ func (wc *WebController) serveFileViewer(w http.ResponseWriter, r *http.Request,
ids = append(ids, p.ByName("id")) ids = append(ids, p.ByName("id"))
} }
var api = pixelapi.New(wc.conf.APIURLInternal, "") var api = pixelapi.New(wc.apiURLInternal, "")
var finfo []*pixelapi.FileInfo var finfo []*pixelapi.FileInfo
for _, id := range ids { for _, id := range ids {
inf, err := api.GetFileInfo(id, "") inf, err := api.GetFileInfo(id, "")

View File

@@ -13,7 +13,7 @@ import (
// ServeListViewer controller for GET /l/:id // ServeListViewer controller for GET /l/:id
func (wc *WebController) serveListViewer(w http.ResponseWriter, r *http.Request, p httprouter.Params) { func (wc *WebController) serveListViewer(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var api = pixelapi.New(wc.conf.APIURLInternal, "") var api = pixelapi.New(wc.apiURLInternal, "")
var list, err = api.GetList(p.ByName("id")) var list, err = api.GetList(p.ByName("id"))
var templateData = wc.newTemplateData(w, r) var templateData = wc.newTemplateData(w, r)
if err != nil { if err != nil {

View File

@@ -49,12 +49,12 @@ func (wc *WebController) newTemplateData(w http.ResponseWriter, r *http.Request)
UserAgent: r.UserAgent(), UserAgent: r.UserAgent(),
Style: userStyle(r), Style: userStyle(r),
UserStyle: template.CSS(userStyle(r).String()), UserStyle: template.CSS(userStyle(r).String()),
APIEndpoint: template.URL(wc.conf.APIURLExternal), APIEndpoint: template.URL(wc.apiURLExternal),
URLQuery: r.URL.Query(), URLQuery: r.URL.Query(),
} }
if key, err := wc.getAPIKey(r); err == nil { if key, err := wc.getAPIKey(r); err == nil {
t.PixelAPI = pixelapi.New(wc.conf.APIURLInternal, key) t.PixelAPI = pixelapi.New(wc.apiURLInternal, key)
uinf, err := t.PixelAPI.UserInfo() uinf, err := t.PixelAPI.UserInfo()
if err != nil { if err != nil {
// This session key doesn't work, or the backend is down, user // This session key doesn't work, or the backend is down, user
@@ -69,7 +69,7 @@ func (wc *WebController) newTemplateData(w http.ResponseWriter, r *http.Request)
Value: "", Value: "",
Path: "/", Path: "/",
Expires: time.Unix(0, 0), Expires: time.Unix(0, 0),
Domain: wc.conf.SessionCookieDomain, Domain: wc.sessionCookieDomain,
}) })
} }
return t return t
@@ -80,7 +80,7 @@ func (wc *WebController) newTemplateData(w http.ResponseWriter, r *http.Request)
t.Username = uinf.Username t.Username = uinf.Username
t.Email = uinf.Email t.Email = uinf.Email
} else { } else {
t.PixelAPI = pixelapi.New(wc.conf.APIURLInternal, "") t.PixelAPI = pixelapi.New(wc.apiURLInternal, "")
} }
return t return t

View File

@@ -16,7 +16,7 @@ func (wc *WebController) serveLogout(
p httprouter.Params, p httprouter.Params,
) { ) {
if key, err := wc.getAPIKey(r); err == nil { if key, err := wc.getAPIKey(r); err == nil {
var api = pixelapi.New(wc.conf.APIURLInternal, key) var api = pixelapi.New(wc.apiURLInternal, key)
if err = api.UserSessionDestroy(key); err != nil { if err = api.UserSessionDestroy(key); err != nil {
log.Warn("logout failed for session '%s': %s", key, err) log.Warn("logout failed for session '%s': %s", key, err)
} }
@@ -177,7 +177,7 @@ func (wc *WebController) loginForm(td *TemplateData, r *http.Request) (f Form) {
Value: loginResp.APIKey, Value: loginResp.APIKey,
Path: "/", Path: "/",
Expires: time.Now().AddDate(50, 0, 0), Expires: time.Now().AddDate(50, 0, 0),
Domain: wc.conf.SessionCookieDomain, Domain: wc.sessionCookieDomain,
} }
f.Extra.RedirectTo = "/user" f.Extra.RedirectTo = "/user"
} }

View File

@@ -133,7 +133,7 @@ func (wc *WebController) serveEmailConfirm(
) { ) {
var status string var status string
if key, err := wc.getAPIKey(r); err == nil { if key, err := wc.getAPIKey(r); err == nil {
err = pixelapi.New(wc.conf.APIURLInternal, key).UserEmailResetConfirm(r.FormValue("key")) err = pixelapi.New(wc.apiURLInternal, key).UserEmailResetConfirm(r.FormValue("key"))
if err != nil && err.Error() == "not_found" { if err != nil && err.Error() == "not_found" {
status = "not_found" status = "not_found"
} else if err != nil { } else if err != nil {

View File

@@ -7,7 +7,6 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"fornaxian.com/pixeldrain-web/init/conf"
"fornaxian.com/pixeldrain-web/pixelapi" "fornaxian.com/pixeldrain-web/pixelapi"
"github.com/Fornaxian/log" "github.com/Fornaxian/log"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
@@ -16,30 +15,44 @@ import (
// WebController controls how requests are handled and makes sure they have // WebController controls how requests are handled and makes sure they have
// proper context when running // proper context when running
type WebController struct { type WebController struct {
conf *conf.PixelWebConfig
templates *TemplateManager templates *TemplateManager
resourceDir string
apiURLInternal string
apiURLExternal string
sessionCookieDomain string
// page-specific variables // page-specific variables
captchaSiteKey string captchaSiteKey string
} }
// New initializes a new WebController by registering all the request handlers // New initializes a new WebController by registering all the request handlers
// and parsing all templates in the resource directory // and parsing all templates in the resource directory
func New(r *httprouter.Router, prefix string, conf *conf.PixelWebConfig) *WebController { func New(
var wc = &WebController{ r *httprouter.Router,
conf: conf, prefix string,
resourceDir string,
apiURLInternal string,
apiURLExternal string,
sessionCookieDomain string,
maintenanceMode bool,
debugMode bool,
) (wc *WebController) {
wc = &WebController{
resourceDir: resourceDir,
apiURLInternal: apiURLInternal,
apiURLExternal: apiURLExternal,
sessionCookieDomain: sessionCookieDomain,
} }
wc.templates = NewTemplateManager( wc.templates = NewTemplateManager(resourceDir, apiURLExternal, debugMode)
conf.ResourceDir,
conf.APIURLExternal,
conf.DebugMode,
)
wc.templates.ParseTemplates(false) wc.templates.ParseTemplates(false)
var p = prefix var p = prefix
// Serve static files // Serve static files
var fs = http.FileServer(http.Dir(wc.conf.ResourceDir + "/static")) var fs = http.FileServer(http.Dir(resourceDir + "/static"))
r.GET(p+"/res/*filepath", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { r.GET(p+"/res/*filepath", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Cache-Control", "public, max-age=86400") // Cache for one day w.Header().Set("Cache-Control", "public, max-age=86400") // Cache for one day
r.URL.Path = p.ByName("filepath") r.URL.Path = p.ByName("filepath")
@@ -50,7 +63,7 @@ func New(r *httprouter.Router, prefix string, conf *conf.PixelWebConfig) *WebCon
r.GET(p+"/favicon.ico" /* */, wc.serveFile("/favicon.ico")) r.GET(p+"/favicon.ico" /* */, wc.serveFile("/favicon.ico"))
r.GET(p+"/robots.txt" /* */, wc.serveFile("/robots.txt")) r.GET(p+"/robots.txt" /* */, wc.serveFile("/robots.txt"))
if conf.MaintenanceMode { if maintenanceMode {
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable) w.WriteHeader(http.StatusServiceUnavailable)
wc.templates.Get().ExecuteTemplate(w, "maintenance", wc.newTemplateData(w, r)) wc.templates.Get().ExecuteTemplate(w, "maintenance", wc.newTemplateData(w, r))
@@ -129,7 +142,7 @@ func (wc *WebController) serveFile(path string) httprouter.Handle {
r *http.Request, r *http.Request,
p httprouter.Params, p httprouter.Params,
) { ) {
http.ServeFile(w, r, wc.conf.ResourceDir+"/static"+path) http.ServeFile(w, r, wc.resourceDir+"/static"+path)
} }
} }
@@ -211,7 +224,7 @@ func (wc *WebController) getAPIKey(r *http.Request) (key string, err error) {
func (wc *WebController) captchaKey() string { func (wc *WebController) captchaKey() string {
// This only runs on the first request // This only runs on the first request
if wc.captchaSiteKey == "" { if wc.captchaSiteKey == "" {
var api = pixelapi.New(wc.conf.APIURLInternal, "") var api = pixelapi.New(wc.apiURLInternal, "")
capt, err := api.GetRecaptcha() capt, err := api.GetRecaptcha()
if err != nil { if err != nil {
log.Error("Error getting recaptcha key: %s", err) log.Error("Error getting recaptcha key: %s", err)