mirror of
https://github.com/documize/community.git
synced 2025-07-24 07:39:43 +02:00
major code repair from old to new API -- WIP
This commit is contained in:
parent
25b576f861
commit
792c3e2ce8
46 changed files with 3403 additions and 171 deletions
210
server/middleware.go
Normal file
210
server/middleware.go
Normal file
|
@ -0,0 +1,210 @@
|
|||
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
|
||||
//
|
||||
// This software (Documize Community Edition) is licensed under
|
||||
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
//
|
||||
// You can operate outside the AGPL restrictions by purchasing
|
||||
// Documize Enterprise Edition and obtaining a commercial license
|
||||
// by contacting <sales@documize.com>.
|
||||
//
|
||||
// https://documize.com
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/documize/community/core/env"
|
||||
"github.com/documize/community/core/response"
|
||||
"github.com/documize/community/domain"
|
||||
"github.com/documize/community/domain/auth"
|
||||
"github.com/documize/community/domain/organization"
|
||||
"github.com/documize/community/domain/user"
|
||||
)
|
||||
|
||||
type middleware struct {
|
||||
Runtime env.Runtime
|
||||
}
|
||||
|
||||
func (m *middleware) cors(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS, PATCH")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "host, content-type, accept, authorization, origin, referer, user-agent, cache-control, x-requested-with")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "x-documize-version, x-documize-status")
|
||||
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Add("X-Documize-Version", m.Runtime.Product.Version)
|
||||
w.Header().Add("Cache-Control", "no-cache")
|
||||
|
||||
w.Write([]byte(""))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
|
||||
func (m *middleware) metrics(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
w.Header().Add("X-Documize-Version", m.Runtime.Product.Version)
|
||||
w.Header().Add("Cache-Control", "no-cache")
|
||||
|
||||
// Prevent page from being displayed in an iframe
|
||||
w.Header().Add("X-Frame-Options", "DENY")
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
|
||||
// Authorize secure API calls by inspecting authentication token.
|
||||
// request.Context provides caller user information.
|
||||
// Site meta sent back as HTTP custom headers.
|
||||
func (m *middleware) Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
method := "Authorize"
|
||||
|
||||
s := domain.StoreContext{Runtime: m.Runtime, Context: domain.RequestContext{}}
|
||||
|
||||
// Let certain requests pass straight through
|
||||
authenticated := preAuthorizeStaticAssets(m.Runtime, r)
|
||||
|
||||
if !authenticated {
|
||||
token := auth.FindJWT(r)
|
||||
rc, _, tokenErr := auth.DecodeJWT(m.Runtime, token)
|
||||
|
||||
var org = organization.Organization{}
|
||||
var err = errors.New("")
|
||||
|
||||
if len(rc.OrgID) == 0 {
|
||||
org, err = organization.GetOrganizationByDomain(s, organization.GetRequestSubdomain(s, r))
|
||||
} else {
|
||||
org, err = organization.GetOrganization(s, rc.OrgID)
|
||||
}
|
||||
|
||||
// Inability to find org record spells the end of this request.
|
||||
if err != nil {
|
||||
response.WriteForbiddenError(w)
|
||||
return
|
||||
}
|
||||
|
||||
// If we have bad auth token and the domain does not allow anon access
|
||||
if !org.AllowAnonymousAccess && tokenErr != nil {
|
||||
response.WriteUnauthorizedError(w)
|
||||
return
|
||||
}
|
||||
|
||||
rc.Subdomain = org.Domain
|
||||
dom := organization.GetSubdomainFromHost(s, r)
|
||||
dom2 := organization.GetRequestSubdomain(s, r)
|
||||
|
||||
if org.Domain != dom && org.Domain != dom2 {
|
||||
m.Runtime.Log.Info(fmt.Sprintf("domain mismatch %s vs. %s vs. %s", dom, dom2, org.Domain))
|
||||
|
||||
response.WriteUnauthorizedError(w)
|
||||
return
|
||||
}
|
||||
|
||||
// If we have bad auth token and the domain allows anon access
|
||||
// then we generate guest context.
|
||||
if org.AllowAnonymousAccess {
|
||||
// So you have a bad token
|
||||
if len(token) > 1 {
|
||||
if tokenErr != nil {
|
||||
response.WriteUnauthorizedError(w)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Just grant anon user guest access
|
||||
rc.UserID = "0"
|
||||
rc.OrgID = org.RefID
|
||||
rc.Authenticated = false
|
||||
rc.Guest = true
|
||||
}
|
||||
}
|
||||
|
||||
rc.AllowAnonymousAccess = org.AllowAnonymousAccess
|
||||
rc.OrgName = org.Title
|
||||
rc.Administrator = false
|
||||
rc.Editor = false
|
||||
rc.Global = false
|
||||
rc.AppURL = r.Host
|
||||
rc.Subdomain = organization.GetSubdomainFromHost(s, r)
|
||||
rc.SSL = r.TLS != nil
|
||||
|
||||
// get user IP from request
|
||||
i := strings.LastIndex(r.RemoteAddr, ":")
|
||||
if i == -1 {
|
||||
rc.ClientIP = r.RemoteAddr
|
||||
} else {
|
||||
rc.ClientIP = r.RemoteAddr[:i]
|
||||
}
|
||||
|
||||
fip := r.Header.Get("X-Forwarded-For")
|
||||
if len(fip) > 0 {
|
||||
rc.ClientIP = fip
|
||||
}
|
||||
|
||||
// Fetch user permissions for this org
|
||||
if rc.Authenticated {
|
||||
u, err := user.GetSecuredUser(s, org.RefID, rc.UserID)
|
||||
|
||||
if err != nil {
|
||||
response.WriteServerError(w, method, err)
|
||||
return
|
||||
}
|
||||
|
||||
rc.Administrator = u.Admin
|
||||
rc.Editor = u.Editor
|
||||
rc.Global = u.Global
|
||||
rc.Fullname = u.Fullname()
|
||||
|
||||
// We send back with every HTTP request/response cycle the latest
|
||||
// user state. This helps client-side applications to detect changes in
|
||||
// user state/privileges.
|
||||
var state struct {
|
||||
Active bool `json:"active"`
|
||||
Admin bool `json:"admin"`
|
||||
Editor bool `json:"editor"`
|
||||
}
|
||||
|
||||
state.Active = u.Active
|
||||
state.Admin = u.Admin
|
||||
state.Editor = u.Editor
|
||||
sb, err := json.Marshal(state)
|
||||
|
||||
w.Header().Add("X-Documize-Status", string(sb))
|
||||
}
|
||||
|
||||
// m.Runtime.Log.Info(fmt.Sprintf("%v", rc))
|
||||
ctx := context.WithValue(r.Context(), domain.DocumizeContextKey, rc)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
// Middleware moves on if we say 'yes' -- authenticated or allow anon access.
|
||||
authenticated = rc.Authenticated || org.AllowAnonymousAccess
|
||||
}
|
||||
|
||||
if authenticated {
|
||||
next(w, r)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// Certain assets/URL do not require authentication.
|
||||
// Just stops the log files being clogged up with failed auth errors.
|
||||
func preAuthorizeStaticAssets(rt env.Runtime, r *http.Request) bool {
|
||||
if strings.ToLower(r.URL.Path) == "/" ||
|
||||
strings.ToLower(r.URL.Path) == "/validate" ||
|
||||
strings.ToLower(r.URL.Path) == "/favicon.ico" ||
|
||||
strings.ToLower(r.URL.Path) == "/robots.txt" ||
|
||||
strings.ToLower(r.URL.Path) == "/version" ||
|
||||
strings.HasPrefix(strings.ToLower(r.URL.Path), "/api/public/") ||
|
||||
((rt.Flags.SiteMode == env.SiteModeSetup) && (strings.ToLower(r.URL.Path) == "/api/setup")) {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
|
@ -28,6 +28,8 @@ const (
|
|||
RoutePrefixPrivate = "/api/"
|
||||
// RoutePrefixRoot used for unsecured endpoints at root (e.g. robots.txt)
|
||||
RoutePrefixRoot = "/"
|
||||
// RoutePrefixTesting used for isolated testing of routes with custom middleware
|
||||
RoutePrefixTesting = "/testing/"
|
||||
)
|
||||
|
||||
type routeDef struct {
|
||||
|
|
|
@ -18,7 +18,6 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/codegangsta/negroni"
|
||||
"github.com/documize/community/core/api"
|
||||
"github.com/documize/community/core/api/endpoint"
|
||||
"github.com/documize/community/core/api/plugins"
|
||||
"github.com/documize/community/core/database"
|
||||
|
@ -39,21 +38,24 @@ func Start(rt env.Runtime, ready chan struct{}) {
|
|||
os.Exit(1)
|
||||
}
|
||||
|
||||
rt.Log.Info(fmt.Sprintf("Starting %s version %s", api.Runtime.Product.Title, api.Runtime.Product.Version))
|
||||
rt.Log.Info(fmt.Sprintf("Starting %s version %s", rt.Product.Title, rt.Product.Version))
|
||||
|
||||
// decide which mode to serve up
|
||||
switch api.Runtime.Flags.SiteMode {
|
||||
case web.SiteModeOffline:
|
||||
switch rt.Flags.SiteMode {
|
||||
case env.SiteModeOffline:
|
||||
rt.Log.Info("Serving OFFLINE web server")
|
||||
case web.SiteModeSetup:
|
||||
case env.SiteModeSetup:
|
||||
routing.Add(rt, routing.RoutePrefixPrivate, "setup", []string{"POST", "OPTIONS"}, nil, database.Create)
|
||||
rt.Log.Info("Serving SETUP web server")
|
||||
case web.SiteModeBadDB:
|
||||
case env.SiteModeBadDB:
|
||||
rt.Log.Info("Serving BAD DATABASE web server")
|
||||
default:
|
||||
rt.Log.Info("Starting web server")
|
||||
}
|
||||
|
||||
// define middleware
|
||||
cm := middleware{Runtime: rt}
|
||||
|
||||
// define API endpoints
|
||||
routing.RegisterEndpoints(rt)
|
||||
|
||||
|
@ -62,7 +64,7 @@ func Start(rt env.Runtime, ready chan struct{}) {
|
|||
|
||||
// "/api/public/..."
|
||||
router.PathPrefix(routing.RoutePrefixPublic).Handler(negroni.New(
|
||||
negroni.HandlerFunc(cors),
|
||||
negroni.HandlerFunc(cm.cors),
|
||||
negroni.Wrap(routing.BuildRoutes(rt, routing.RoutePrefixPublic)),
|
||||
))
|
||||
|
||||
|
@ -74,74 +76,46 @@ func Start(rt env.Runtime, ready chan struct{}) {
|
|||
|
||||
// "/..."
|
||||
router.PathPrefix(routing.RoutePrefixRoot).Handler(negroni.New(
|
||||
negroni.HandlerFunc(cors),
|
||||
negroni.HandlerFunc(cm.cors),
|
||||
negroni.Wrap(routing.BuildRoutes(rt, routing.RoutePrefixRoot)),
|
||||
))
|
||||
|
||||
n := negroni.New()
|
||||
n.Use(negroni.NewStatic(web.StaticAssetsFileSystem()))
|
||||
n.Use(negroni.HandlerFunc(cors))
|
||||
n.Use(negroni.HandlerFunc(metrics))
|
||||
n.Use(negroni.HandlerFunc(cm.cors))
|
||||
n.Use(negroni.HandlerFunc(cm.metrics))
|
||||
n.UseHandler(router)
|
||||
|
||||
// start server
|
||||
if !api.Runtime.Flags.SSLEnabled() {
|
||||
rt.Log.Info("Starting non-SSL server on " + api.Runtime.Flags.HTTPPort)
|
||||
n.Run(testHost + ":" + api.Runtime.Flags.HTTPPort)
|
||||
if !rt.Flags.SSLEnabled() {
|
||||
rt.Log.Info("Starting non-SSL server on " + rt.Flags.HTTPPort)
|
||||
n.Run(testHost + ":" + rt.Flags.HTTPPort)
|
||||
} else {
|
||||
if api.Runtime.Flags.ForceHTTPPort2SSL != "" {
|
||||
rt.Log.Info("Starting non-SSL server on " + api.Runtime.Flags.ForceHTTPPort2SSL + " and redirecting to SSL server on " + api.Runtime.Flags.HTTPPort)
|
||||
if rt.Flags.ForceHTTPPort2SSL != "" {
|
||||
rt.Log.Info("Starting non-SSL server on " + rt.Flags.ForceHTTPPort2SSL + " and redirecting to SSL server on " + rt.Flags.HTTPPort)
|
||||
|
||||
go func() {
|
||||
err := http.ListenAndServe(":"+api.Runtime.Flags.ForceHTTPPort2SSL, http.HandlerFunc(
|
||||
err := http.ListenAndServe(":"+rt.Flags.ForceHTTPPort2SSL, http.HandlerFunc(
|
||||
func(w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("Connection", "close")
|
||||
var host = strings.Replace(req.Host, api.Runtime.Flags.ForceHTTPPort2SSL, api.Runtime.Flags.HTTPPort, 1) + req.RequestURI
|
||||
var host = strings.Replace(req.Host, rt.Flags.ForceHTTPPort2SSL, rt.Flags.HTTPPort, 1) + req.RequestURI
|
||||
http.Redirect(w, req, "https://"+host, http.StatusMovedPermanently)
|
||||
}))
|
||||
if err != nil {
|
||||
rt.Log.Error("ListenAndServe on "+api.Runtime.Flags.ForceHTTPPort2SSL, err)
|
||||
rt.Log.Error("ListenAndServe on "+rt.Flags.ForceHTTPPort2SSL, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
rt.Log.Info("Starting SSL server on " + api.Runtime.Flags.HTTPPort + " with " + api.Runtime.Flags.SSLCertFile + " " + api.Runtime.Flags.SSLKeyFile)
|
||||
rt.Log.Info("Starting SSL server on " + rt.Flags.HTTPPort + " with " + rt.Flags.SSLCertFile + " " + rt.Flags.SSLKeyFile)
|
||||
|
||||
// TODO: https://blog.gopheracademy.com/advent-2016/exposing-go-on-the-internet/
|
||||
|
||||
server := &http.Server{Addr: ":" + api.Runtime.Flags.HTTPPort, Handler: n /*, TLSConfig: myTLSConfig*/}
|
||||
server := &http.Server{Addr: ":" + rt.Flags.HTTPPort, Handler: n /*, TLSConfig: myTLSConfig*/}
|
||||
server.SetKeepAlivesEnabled(true)
|
||||
|
||||
if err := server.ListenAndServeTLS(api.Runtime.Flags.SSLCertFile, api.Runtime.Flags.SSLKeyFile); err != nil {
|
||||
rt.Log.Error("ListenAndServeTLS on "+api.Runtime.Flags.HTTPPort, err)
|
||||
if err := server.ListenAndServeTLS(rt.Flags.SSLCertFile, rt.Flags.SSLKeyFile); err != nil {
|
||||
rt.Log.Error("ListenAndServeTLS on "+rt.Flags.HTTPPort, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cors(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS, PATCH")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "host, content-type, accept, authorization, origin, referer, user-agent, cache-control, x-requested-with")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "x-documize-version, x-documize-status")
|
||||
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Add("X-Documize-Version", api.Runtime.Product.Version)
|
||||
w.Header().Add("Cache-Control", "no-cache")
|
||||
|
||||
w.Write([]byte(""))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
|
||||
func metrics(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
w.Header().Add("X-Documize-Version", api.Runtime.Product.Version)
|
||||
w.Header().Add("Cache-Control", "no-cache")
|
||||
|
||||
// Prevent page from being displayed in an iframe
|
||||
w.Header().Add("X-Frame-Options", "DENY")
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
|
|
|
@ -17,20 +17,10 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/documize/community/core/api"
|
||||
"github.com/documize/community/core/env"
|
||||
"github.com/documize/community/core/secrets"
|
||||
)
|
||||
|
||||
const (
|
||||
// SiteModeNormal serves app
|
||||
SiteModeNormal = ""
|
||||
// SiteModeOffline serves offline.html
|
||||
SiteModeOffline = "1"
|
||||
// SiteModeSetup tells Ember to serve setup route
|
||||
SiteModeSetup = "2"
|
||||
// SiteModeBadDB redirects to db-error.html page
|
||||
SiteModeBadDB = "3"
|
||||
)
|
||||
|
||||
// SiteInfo describes set-up information about the site
|
||||
var SiteInfo struct {
|
||||
DBname, DBhash, Issue string
|
||||
|
@ -44,11 +34,11 @@ func init() {
|
|||
func EmberHandler(w http.ResponseWriter, r *http.Request) {
|
||||
filename := "index.html"
|
||||
switch api.Runtime.Flags.SiteMode {
|
||||
case SiteModeOffline:
|
||||
case env.SiteModeOffline:
|
||||
filename = "offline.html"
|
||||
case SiteModeSetup:
|
||||
case env.SiteModeSetup:
|
||||
// NoOp
|
||||
case SiteModeBadDB:
|
||||
case env.SiteModeBadDB:
|
||||
filename = "db-error.html"
|
||||
default:
|
||||
SiteInfo.DBhash = ""
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue