mirror of
https://github.com/thomiceli/opengist.git
synced 2025-07-11 10:21:50 +02:00
Refactor server code (#407)
This commit is contained in:
40
internal/web/server/handler.go
Normal file
40
internal/web/server/handler.go
Normal file
@ -0,0 +1,40 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
)
|
||||
|
||||
type Handler func(ctx *context.Context) error
|
||||
type Middleware func(next Handler) Handler
|
||||
|
||||
func (h Handler) toEcho() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
return h(c.(*context.Context))
|
||||
}
|
||||
}
|
||||
|
||||
func (m Middleware) toEcho() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return m(func(c *context.Context) error {
|
||||
return next(c)
|
||||
}).toEcho()
|
||||
}
|
||||
}
|
||||
|
||||
func (h Handler) toEchoHandler() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if ogc, ok := c.(*context.Context); ok {
|
||||
return h(ogc)
|
||||
}
|
||||
// Could also add error handling for incorrect context type
|
||||
return h(c.(*context.Context))
|
||||
}
|
||||
}
|
||||
|
||||
func chain(h Handler, middleware ...Middleware) Handler {
|
||||
for i := len(middleware) - 1; i >= 0; i-- {
|
||||
h = middleware[i](h)
|
||||
}
|
||||
return h
|
||||
}
|
393
internal/web/server/middlewares.go
Normal file
393
internal/web/server/middlewares.go
Normal file
@ -0,0 +1,393 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/auth"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/i18n"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers"
|
||||
"golang.org/x/text/cases"
|
||||
"golang.org/x/text/language"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Server) useCustomContext() {
|
||||
s.echo.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
cc := context.NewContext(c, s.sessionsPath)
|
||||
return next(cc)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) registerMiddlewares() {
|
||||
s.echo.Use(Middleware(dataInit).toEcho())
|
||||
s.echo.Use(Middleware(locale).toEcho())
|
||||
|
||||
s.echo.Pre(middleware.MethodOverrideWithConfig(middleware.MethodOverrideConfig{
|
||||
Getter: middleware.MethodFromForm("_method"),
|
||||
}))
|
||||
s.echo.Pre(middleware.RemoveTrailingSlash())
|
||||
s.echo.Pre(middleware.CORS())
|
||||
s.echo.Pre(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
||||
LogURI: true, LogStatus: true, LogMethod: true,
|
||||
LogValuesFunc: func(ctx echo.Context, v middleware.RequestLoggerValues) error {
|
||||
log.Info().Str("uri", v.URI).Int("status", v.Status).Str("method", v.Method).
|
||||
Str("ip", ctx.RealIP()).TimeDiff("duration", time.Now(), v.StartTime).
|
||||
Msg("HTTP")
|
||||
return nil
|
||||
},
|
||||
}))
|
||||
s.echo.Use(middleware.Recover())
|
||||
s.echo.Use(middleware.Secure())
|
||||
s.echo.Use(Middleware(sessionInit).toEcho())
|
||||
|
||||
if !s.ignoreCsrf {
|
||||
s.echo.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
|
||||
TokenLookup: "form:_csrf,header:X-CSRF-Token",
|
||||
CookiePath: "/",
|
||||
CookieHTTPOnly: true,
|
||||
CookieSameSite: http.SameSiteStrictMode,
|
||||
}))
|
||||
s.echo.Use(Middleware(csrfInit).toEcho())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) errorHandler(err error, ctx echo.Context) {
|
||||
var httpErr *echo.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
acceptJson := strings.Contains(ctx.Request().Header.Get("Accept"), "application/json")
|
||||
data := ctx.Request().Context().Value(context.DataKeyStr).(echo.Map)
|
||||
data["error"] = err
|
||||
if acceptJson {
|
||||
if err := ctx.JSON(httpErr.Code, httpErr); err != nil {
|
||||
log.Fatal().Err(err).Send()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctx.Render(httpErr.Code, "error", data); err != nil {
|
||||
log.Fatal().Err(err).Send()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
log.Fatal().Err(err).Send()
|
||||
}
|
||||
|
||||
func dataInit(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
ctx.SetData("loadStartTime", time.Now())
|
||||
|
||||
if err := loadSettings(ctx); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot load settings", err)
|
||||
}
|
||||
|
||||
ctx.SetData("c", config.C)
|
||||
|
||||
ctx.SetData("githubOauth", config.C.GithubClientKey != "" && config.C.GithubSecret != "")
|
||||
ctx.SetData("gitlabOauth", config.C.GitlabClientKey != "" && config.C.GitlabSecret != "")
|
||||
ctx.SetData("giteaOauth", config.C.GiteaClientKey != "" && config.C.GiteaSecret != "")
|
||||
ctx.SetData("oidcOauth", config.C.OIDCClientKey != "" && config.C.OIDCSecret != "" && config.C.OIDCDiscoveryUrl != "")
|
||||
|
||||
httpProtocol := "http"
|
||||
if ctx.Request().TLS != nil || ctx.Request().Header.Get("X-Forwarded-Proto") == "https" {
|
||||
httpProtocol = "https"
|
||||
}
|
||||
ctx.SetData("httpProtocol", strings.ToUpper(httpProtocol))
|
||||
|
||||
var baseHttpUrl string
|
||||
// if a custom external url is set, use it
|
||||
if config.C.ExternalUrl != "" {
|
||||
baseHttpUrl = config.C.ExternalUrl
|
||||
} else {
|
||||
baseHttpUrl = httpProtocol + "://" + ctx.Request().Host
|
||||
}
|
||||
|
||||
ctx.SetData("baseHttpUrl", baseHttpUrl)
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func writePermission(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
gist := ctx.GetData("gist")
|
||||
user := ctx.User
|
||||
if !gist.(*db.Gist).CanWrite(user) {
|
||||
return ctx.RedirectTo("/" + gist.(*db.Gist).User.Username + "/" + gist.(*db.Gist).Identifier())
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func adminPermission(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
if user == nil || !user.IsAdmin {
|
||||
return ctx.NotFound("User not found")
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func logged(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
if user != nil {
|
||||
return next(ctx)
|
||||
}
|
||||
return ctx.RedirectTo("/all")
|
||||
}
|
||||
}
|
||||
|
||||
func inMFASession(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
sess := ctx.GetSession()
|
||||
_, ok := sess.Values["mfaID"].(uint)
|
||||
if !ok {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.not-in-mfa-session"), nil)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func makeCheckRequireLogin(isSingleGistAccess bool) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
if user := ctx.User; user != nil {
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
allow, err := auth.ShouldAllowUnauthenticatedGistAccess(handlers.ContextAuthInfo{Context: ctx}, isSingleGistAccess)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to check if unauthenticated access is allowed")
|
||||
}
|
||||
|
||||
if !allow {
|
||||
ctx.AddFlash(ctx.Tr("flash.auth.must-be-logged-in"), "error")
|
||||
return ctx.RedirectTo("/login")
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func checkRequireLogin(next Handler) Handler {
|
||||
return makeCheckRequireLogin(false)(next)
|
||||
}
|
||||
|
||||
func noRouteFound(ctx *context.Context) error {
|
||||
return ctx.NotFound("Page not found")
|
||||
}
|
||||
|
||||
func locale(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
// Check URL arguments
|
||||
lang := ctx.Request().URL.Query().Get("lang")
|
||||
changeLang := lang != ""
|
||||
|
||||
// Then check cookies
|
||||
if len(lang) == 0 {
|
||||
cookie, _ := ctx.Request().Cookie("lang")
|
||||
if cookie != nil {
|
||||
lang = cookie.Value
|
||||
}
|
||||
}
|
||||
|
||||
// Check again in case someone changes the supported language list.
|
||||
if lang != "" && !i18n.Locales.HasLocale(lang) {
|
||||
lang = ""
|
||||
changeLang = false
|
||||
}
|
||||
|
||||
// 3.Then check from 'Accept-Language' header.
|
||||
if len(lang) == 0 {
|
||||
tags, _, _ := language.ParseAcceptLanguage(ctx.Request().Header.Get("Accept-Language"))
|
||||
lang = i18n.Locales.MatchTag(tags)
|
||||
}
|
||||
|
||||
if changeLang {
|
||||
ctx.SetCookie(&http.Cookie{Name: "lang", Value: lang, Path: "/", MaxAge: 1<<31 - 1})
|
||||
}
|
||||
|
||||
localeUsed, err := i18n.Locales.GetLocale(lang)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get locale", err)
|
||||
}
|
||||
|
||||
ctx.SetData("localeName", localeUsed.Name)
|
||||
ctx.SetData("locale", localeUsed)
|
||||
ctx.SetData("allLocales", i18n.Locales.Locales)
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func sessionInit(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
sess := ctx.GetSession()
|
||||
if sess.Values["user"] != nil {
|
||||
var err error
|
||||
var user *db.User
|
||||
|
||||
if user, err = db.GetUserById(sess.Values["user"].(uint)); err != nil {
|
||||
sess.Values["user"] = nil
|
||||
ctx.SaveSession(sess)
|
||||
ctx.User = nil
|
||||
ctx.SetData("userLogged", nil)
|
||||
return ctx.RedirectTo("/all")
|
||||
}
|
||||
if user != nil {
|
||||
ctx.User = user
|
||||
ctx.SetData("userLogged", user)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
ctx.User = nil
|
||||
ctx.SetData("userLogged", nil)
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func csrfInit(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
var csrf string
|
||||
if csrfToken, ok := ctx.Get("csrf").(string); ok {
|
||||
csrf = csrfToken
|
||||
}
|
||||
ctx.SetData("csrfHtml", template.HTML(`<input type="hidden" name="_csrf" value="`+csrf+`">`))
|
||||
ctx.SetData("csrfHtml", template.HTML(`<input type="hidden" name="_csrf" value="`+csrf+`">`))
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func loadSettings(ctx *context.Context) error {
|
||||
settings, err := db.GetSettings()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for key, value := range settings {
|
||||
s := strings.ReplaceAll(key, "-", " ")
|
||||
s = cases.Title(language.English).String(s)
|
||||
ctx.SetData(strings.ReplaceAll(s, " ", ""), value == "1")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func gistInit(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
currUser := ctx.User
|
||||
|
||||
userName := ctx.Param("user")
|
||||
gistName := ctx.Param("gistname")
|
||||
|
||||
switch filepath.Ext(gistName) {
|
||||
case ".js":
|
||||
ctx.SetData("gistpage", "js")
|
||||
gistName = strings.TrimSuffix(gistName, ".js")
|
||||
case ".json":
|
||||
ctx.SetData("gistpage", "json")
|
||||
gistName = strings.TrimSuffix(gistName, ".json")
|
||||
case ".git":
|
||||
ctx.SetData("gistpage", "git")
|
||||
gistName = strings.TrimSuffix(gistName, ".git")
|
||||
}
|
||||
|
||||
gist, err := db.GetGist(userName, gistName)
|
||||
if err != nil {
|
||||
return ctx.NotFound("Gist not found")
|
||||
}
|
||||
|
||||
if gist.Private == db.PrivateVisibility {
|
||||
if currUser == nil || currUser.ID != gist.UserID {
|
||||
return ctx.NotFound("Gist not found")
|
||||
}
|
||||
}
|
||||
|
||||
ctx.SetData("gist", gist)
|
||||
|
||||
if config.C.SshGit {
|
||||
var sshDomain string
|
||||
|
||||
if config.C.SshExternalDomain != "" {
|
||||
sshDomain = config.C.SshExternalDomain
|
||||
} else {
|
||||
sshDomain = strings.Split(ctx.Request().Host, ":")[0]
|
||||
}
|
||||
|
||||
if config.C.SshPort == "22" {
|
||||
ctx.SetData("sshCloneUrl", sshDomain+":"+userName+"/"+gistName+".git")
|
||||
} else {
|
||||
ctx.SetData("sshCloneUrl", "ssh://"+sshDomain+":"+config.C.SshPort+"/"+userName+"/"+gistName+".git")
|
||||
}
|
||||
}
|
||||
|
||||
baseHttpUrl := ctx.GetData("baseHttpUrl").(string)
|
||||
|
||||
if config.C.HttpGit {
|
||||
ctx.SetData("httpCloneUrl", baseHttpUrl+"/"+userName+"/"+gistName+".git")
|
||||
}
|
||||
|
||||
ctx.SetData("httpCopyUrl", baseHttpUrl+"/"+userName+"/"+gistName)
|
||||
ctx.SetData("currentUrl", template.URL(ctx.Request().URL.Path))
|
||||
ctx.SetData("embedScript", fmt.Sprintf(`<script src="%s"></script>`, baseHttpUrl+"/"+userName+"/"+gistName+".js"))
|
||||
|
||||
nbCommits, err := gist.NbCommits()
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Error fetching number of commits", err)
|
||||
}
|
||||
ctx.SetData("nbCommits", nbCommits)
|
||||
|
||||
if currUser != nil {
|
||||
hasLiked, err := currUser.HasLiked(gist)
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot get user like status", err)
|
||||
}
|
||||
ctx.SetData("hasLiked", hasLiked)
|
||||
}
|
||||
|
||||
if gist.Private > 0 {
|
||||
ctx.SetData("NoIndex", true)
|
||||
}
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// gistSoftInit try to load a gist (same as gistInit) but does not return a 404 if the gist is not found
|
||||
// useful for git clients using HTTP to obfuscate the existence of a private gist
|
||||
func gistSoftInit(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
userName := ctx.Param("user")
|
||||
gistName := ctx.Param("gistname")
|
||||
|
||||
gistName = strings.TrimSuffix(gistName, ".git")
|
||||
|
||||
gist, _ := db.GetGist(userName, gistName)
|
||||
ctx.SetData("gist", gist)
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// gistNewPushSoftInit has the same behavior as gistSoftInit but create a new gist empty instead
|
||||
func gistNewPushSoftInit(next Handler) Handler {
|
||||
return func(ctx *context.Context) error {
|
||||
ctx.SetData("gist", new(db.Gist))
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
213
internal/web/server/renderer.go
Normal file
213
internal/web/server/renderer.go
Normal file
@ -0,0 +1,213 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
gojson "encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/git"
|
||||
"github.com/thomiceli/opengist/internal/index"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers"
|
||||
"github.com/thomiceli/opengist/public"
|
||||
"github.com/thomiceli/opengist/templates"
|
||||
htmlpkg "html"
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Template struct {
|
||||
templates *template.Template
|
||||
}
|
||||
|
||||
func (t *Template) Render(w io.Writer, name string, data interface{}, _ echo.Context) error {
|
||||
return t.templates.ExecuteTemplate(w, name, data)
|
||||
}
|
||||
|
||||
var re = regexp.MustCompile("[^a-z0-9]+")
|
||||
|
||||
func (s *Server) setFuncMap() {
|
||||
fm := template.FuncMap{
|
||||
"split": strings.Split,
|
||||
"indexByte": strings.IndexByte,
|
||||
"toInt": func(i string) int {
|
||||
val, _ := strconv.Atoi(i)
|
||||
return val
|
||||
},
|
||||
"inc": func(i int) int {
|
||||
return i + 1
|
||||
},
|
||||
"splitGit": func(i string) []string {
|
||||
return strings.FieldsFunc(i, func(r rune) bool {
|
||||
return r == ',' || r == ' '
|
||||
})
|
||||
},
|
||||
"lines": func(i string) []string {
|
||||
return strings.Split(i, "\n")
|
||||
},
|
||||
"isMarkdown": func(i string) bool {
|
||||
return strings.ToLower(filepath.Ext(i)) == ".md"
|
||||
},
|
||||
"isCsv": func(i string) bool {
|
||||
return strings.ToLower(filepath.Ext(i)) == ".csv"
|
||||
},
|
||||
"isSvg": func(i string) bool {
|
||||
return strings.ToLower(filepath.Ext(i)) == ".svg"
|
||||
},
|
||||
"csvFile": func(file *git.File) *git.CsvFile {
|
||||
if strings.ToLower(filepath.Ext(file.Filename)) != ".csv" {
|
||||
return nil
|
||||
}
|
||||
|
||||
csvFile, err := git.ParseCsv(file)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return csvFile
|
||||
},
|
||||
"httpStatusText": http.StatusText,
|
||||
"loadedTime": func(startTime time.Time) string {
|
||||
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
|
||||
},
|
||||
"slug": func(s string) string {
|
||||
return strings.Trim(re.ReplaceAllString(strings.ToLower(s), "-"), "-")
|
||||
},
|
||||
"avatarUrl": func(user *db.User, noGravatar bool) string {
|
||||
if user.AvatarURL != "" {
|
||||
return user.AvatarURL
|
||||
}
|
||||
|
||||
if user.MD5Hash != "" && !noGravatar {
|
||||
return "https://www.gravatar.com/avatar/" + user.MD5Hash + "?d=identicon&s=200"
|
||||
}
|
||||
|
||||
if s.dev {
|
||||
return "http://localhost:16157/default.png"
|
||||
}
|
||||
return config.C.ExternalUrl + "/" + context.ManifestEntries["default.png"].File
|
||||
},
|
||||
"asset": func(file string) string {
|
||||
if s.dev {
|
||||
return "http://localhost:16157/" + file
|
||||
}
|
||||
return config.C.ExternalUrl + "/" + context.ManifestEntries[file].File
|
||||
},
|
||||
"custom": func(file string) string {
|
||||
assetpath, err := url.JoinPath("/", "assets", file)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msgf("Failed to join path for custom file %s", file)
|
||||
}
|
||||
return config.C.ExternalUrl + assetpath
|
||||
},
|
||||
"dev": func() bool {
|
||||
return s.dev
|
||||
},
|
||||
"defaultAvatar": func() string {
|
||||
if s.dev {
|
||||
return "http://localhost:16157/default.png"
|
||||
}
|
||||
return config.C.ExternalUrl + "/" + context.ManifestEntries["default.png"].File
|
||||
},
|
||||
"visibilityStr": func(visibility db.Visibility, lowercase bool) string {
|
||||
s := "Public"
|
||||
switch visibility {
|
||||
case 1:
|
||||
s = "Unlisted"
|
||||
case 2:
|
||||
s = "Private"
|
||||
}
|
||||
|
||||
if lowercase {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
return s
|
||||
},
|
||||
"unescape": htmlpkg.UnescapeString,
|
||||
"join": func(s ...string) string {
|
||||
return strings.Join(s, "")
|
||||
},
|
||||
"toStr": func(i interface{}) string {
|
||||
return fmt.Sprint(i)
|
||||
},
|
||||
"safe": func(s string) template.HTML {
|
||||
return template.HTML(s)
|
||||
},
|
||||
"dict": func(values ...interface{}) (map[string]interface{}, error) {
|
||||
if len(values)%2 != 0 {
|
||||
return nil, errors.New("invalid dict call")
|
||||
}
|
||||
dict := make(map[string]interface{})
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].(string)
|
||||
if !ok {
|
||||
return nil, errors.New("dict keys must be strings")
|
||||
}
|
||||
dict[key] = values[i+1]
|
||||
}
|
||||
return dict, nil
|
||||
},
|
||||
"addMetadataToSearchQuery": func(input, key, value string) string {
|
||||
content, metadata := handlers.ParseSearchQueryStr(input)
|
||||
|
||||
metadata[key] = value
|
||||
|
||||
var resultBuilder strings.Builder
|
||||
resultBuilder.WriteString(content)
|
||||
|
||||
for k, v := range metadata {
|
||||
resultBuilder.WriteString(" ")
|
||||
resultBuilder.WriteString(k)
|
||||
resultBuilder.WriteString(":")
|
||||
resultBuilder.WriteString(v)
|
||||
}
|
||||
|
||||
return strings.TrimSpace(resultBuilder.String())
|
||||
},
|
||||
"indexEnabled": index.Enabled,
|
||||
"isUrl": func(s string) bool {
|
||||
_, err := url.ParseRequestURI(s)
|
||||
return err == nil
|
||||
},
|
||||
}
|
||||
|
||||
t := template.Must(template.New("t").Funcs(fm).ParseFS(templates.Files, "*/*.html"))
|
||||
customPattern := filepath.Join(config.GetHomeDir(), "custom", "*.html")
|
||||
matches, err := filepath.Glob(customPattern)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to check for custom templates")
|
||||
}
|
||||
if len(matches) > 0 {
|
||||
t, err = t.ParseGlob(customPattern)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to parse custom templates")
|
||||
}
|
||||
}
|
||||
s.echo.Renderer = &Template{
|
||||
templates: t,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) parseManifestEntries() {
|
||||
file, err := public.Files.Open("manifest.json")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to open manifest.json")
|
||||
}
|
||||
byteValue, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to read manifest.json")
|
||||
}
|
||||
if err = gojson.Unmarshal(byteValue, &context.ManifestEntries); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to unmarshal manifest.json")
|
||||
}
|
||||
}
|
209
internal/web/server/router.go
Normal file
209
internal/web/server/router.go
Normal file
@ -0,0 +1,209 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/index"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers/admin"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers/auth"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers/gist"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers/git"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers/health"
|
||||
"github.com/thomiceli/opengist/internal/web/handlers/settings"
|
||||
"github.com/thomiceli/opengist/public"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Server) registerRoutes() {
|
||||
r := NewRouter(s.echo.Group(""))
|
||||
|
||||
{
|
||||
r.GET("/", gist.Create, logged)
|
||||
r.POST("/", gist.ProcessCreate, logged)
|
||||
r.POST("/preview", gist.Preview, logged)
|
||||
|
||||
r.GET("/healthcheck", health.Healthcheck)
|
||||
r.GET("/metrics", health.Metrics)
|
||||
|
||||
r.GET("/register", auth.Register)
|
||||
r.POST("/register", auth.ProcessRegister)
|
||||
r.GET("/login", auth.Login)
|
||||
r.POST("/login", auth.ProcessLogin)
|
||||
r.GET("/logout", auth.Logout)
|
||||
r.GET("/oauth/:provider", auth.Oauth)
|
||||
r.GET("/oauth/:provider/callback", auth.OauthCallback)
|
||||
r.GET("/oauth/:provider/unlink", auth.OauthUnlink, logged)
|
||||
r.POST("/webauthn/bind", auth.BeginWebAuthnBinding, logged)
|
||||
r.POST("/webauthn/bind/finish", auth.FinishWebAuthnBinding, logged)
|
||||
r.POST("/webauthn/login", auth.BeginWebAuthnLogin)
|
||||
r.POST("/webauthn/login/finish", auth.FinishWebAuthnLogin)
|
||||
r.POST("/webauthn/assertion", auth.BeginWebAuthnAssertion, inMFASession)
|
||||
r.POST("/webauthn/assertion/finish", auth.FinishWebAuthnAssertion, inMFASession)
|
||||
r.GET("/mfa", auth.Mfa, inMFASession)
|
||||
r.POST("/mfa/totp/assertion", auth.AssertTotp, inMFASession)
|
||||
|
||||
sA := r.SubGroup("/settings")
|
||||
{
|
||||
sA.Use(logged)
|
||||
sA.GET("", settings.UserSettings)
|
||||
sA.POST("/email", settings.EmailProcess)
|
||||
sA.DELETE("/account", settings.AccountDeleteProcess)
|
||||
sA.POST("/ssh-keys", settings.SshKeysProcess)
|
||||
sA.DELETE("/ssh-keys/:id", settings.SshKeysDelete)
|
||||
sA.DELETE("/passkeys/:id", settings.PasskeyDelete)
|
||||
sA.PUT("/password", settings.PasswordProcess)
|
||||
sA.PUT("/username", settings.UsernameProcess)
|
||||
sA.GET("/totp/generate", auth.BeginTotp)
|
||||
sA.POST("/totp/generate", auth.FinishTotp)
|
||||
sA.DELETE("/totp", auth.DisableTotp)
|
||||
sA.POST("/totp/regenerate", auth.RegenerateTotpRecoveryCodes)
|
||||
}
|
||||
|
||||
sB := r.SubGroup("/admin-panel")
|
||||
{
|
||||
sB.Use(adminPermission)
|
||||
sB.GET("", admin.AdminIndex)
|
||||
sB.GET("/users", admin.AdminUsers)
|
||||
sB.POST("/users/:user/delete", admin.AdminUserDelete)
|
||||
sB.GET("/gists", admin.AdminGists)
|
||||
sB.POST("/gists/:gist/delete", admin.AdminGistDelete)
|
||||
sB.GET("/invitations", admin.AdminInvitations)
|
||||
sB.POST("/invitations", admin.AdminInvitationsCreate)
|
||||
sB.POST("/invitations/:id/delete", admin.AdminInvitationsDelete)
|
||||
sB.POST("/sync-fs", admin.AdminSyncReposFromFS)
|
||||
sB.POST("/sync-db", admin.AdminSyncReposFromDB)
|
||||
sB.POST("/gc-repos", admin.AdminGcRepos)
|
||||
sB.POST("/sync-previews", admin.AdminSyncGistPreviews)
|
||||
sB.POST("/reset-hooks", admin.AdminResetHooks)
|
||||
sB.POST("/index-gists", admin.AdminIndexGists)
|
||||
sB.GET("/configuration", admin.AdminConfig)
|
||||
sB.PUT("/set-config", admin.AdminSetConfig)
|
||||
}
|
||||
|
||||
if config.C.HttpGit {
|
||||
r.Any("/init/*", git.GitHttp, gistNewPushSoftInit)
|
||||
}
|
||||
|
||||
r.GET("/all", gist.AllGists, checkRequireLogin)
|
||||
|
||||
if index.Enabled() {
|
||||
r.GET("/search", gist.Search, checkRequireLogin)
|
||||
} else {
|
||||
r.GET("/search", gist.AllGists, checkRequireLogin)
|
||||
}
|
||||
|
||||
r.GET("/:user", gist.AllGists, checkRequireLogin)
|
||||
r.GET("/:user/liked", gist.AllGists, checkRequireLogin)
|
||||
r.GET("/:user/forked", gist.AllGists, checkRequireLogin)
|
||||
|
||||
sC := r.SubGroup("/:user/:gistname")
|
||||
{
|
||||
sC.Use(makeCheckRequireLogin(true), gistInit)
|
||||
sC.GET("", gist.GistIndex)
|
||||
sC.GET("/rev/:revision", gist.GistIndex)
|
||||
sC.GET("/revisions", gist.Revisions)
|
||||
sC.GET("/archive/:revision", gist.DownloadZip)
|
||||
sC.POST("/visibility", gist.EditVisibility, logged, writePermission)
|
||||
sC.POST("/delete", gist.DeleteGist, logged, writePermission)
|
||||
sC.GET("/raw/:revision/:file", gist.RawFile)
|
||||
sC.GET("/download/:revision/:file", gist.DownloadFile)
|
||||
sC.GET("/edit", gist.Edit, logged, writePermission)
|
||||
sC.POST("/edit", gist.ProcessCreate, logged, writePermission)
|
||||
sC.POST("/like", gist.Like, logged)
|
||||
sC.GET("/likes", gist.Likes, checkRequireLogin)
|
||||
sC.POST("/fork", gist.Fork, logged)
|
||||
sC.GET("/forks", gist.Forks, checkRequireLogin)
|
||||
sC.PUT("/checkbox", gist.Checkbox, logged, writePermission)
|
||||
}
|
||||
}
|
||||
|
||||
customFs := os.DirFS(filepath.Join(config.GetHomeDir(), "custom"))
|
||||
r.GET("/assets/*", func(ctx *context.Context) error {
|
||||
if _, err := public.Files.Open(path.Join("assets", ctx.Param("*"))); !s.dev && err == nil {
|
||||
ctx.Response().Header().Set("Cache-Control", "public, max-age=31536000")
|
||||
ctx.Response().Header().Set("Expires", time.Now().AddDate(1, 0, 0).Format(http.TimeFormat))
|
||||
|
||||
return echo.WrapHandler(http.FileServer(http.FS(public.Files)))(ctx)
|
||||
}
|
||||
|
||||
// if the custom file is an .html template, render it
|
||||
if strings.HasSuffix(ctx.Param("*"), ".html") {
|
||||
if err := ctx.Html(ctx.Param("*")); err != nil {
|
||||
return ctx.NotFound("Page not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return echo.WrapHandler(http.StripPrefix("/assets/", http.FileServer(http.FS(customFs))))(ctx)
|
||||
})
|
||||
|
||||
// Git HTTP routes
|
||||
if config.C.HttpGit {
|
||||
r.Any("/:user/:gistname/*", git.GitHttp, gistSoftInit)
|
||||
}
|
||||
|
||||
r.Any("/*", noRouteFound)
|
||||
}
|
||||
|
||||
// Router wraps echo.Group to provide custom Handler support
|
||||
type Router struct {
|
||||
*echo.Group
|
||||
}
|
||||
|
||||
func NewRouter(g *echo.Group) *Router {
|
||||
return &Router{Group: g}
|
||||
}
|
||||
|
||||
func (r *Router) SubGroup(prefix string, m ...Middleware) *Router {
|
||||
echoMiddleware := make([]echo.MiddlewareFunc, len(m))
|
||||
for i, mw := range m {
|
||||
mw := mw // capture for closure
|
||||
echoMiddleware[i] = func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return chain(func(c *context.Context) error {
|
||||
return next(c)
|
||||
}, mw).toEchoHandler()
|
||||
}
|
||||
}
|
||||
return NewRouter(r.Group.Group(prefix, echoMiddleware...))
|
||||
}
|
||||
|
||||
func (r *Router) GET(path string, h Handler, m ...Middleware) {
|
||||
r.Group.GET(path, chain(h, m...).toEchoHandler())
|
||||
}
|
||||
|
||||
func (r *Router) POST(path string, h Handler, m ...Middleware) {
|
||||
r.Group.POST(path, chain(h, m...).toEchoHandler())
|
||||
}
|
||||
|
||||
func (r *Router) PUT(path string, h Handler, m ...Middleware) {
|
||||
r.Group.PUT(path, chain(h, m...).toEchoHandler())
|
||||
}
|
||||
|
||||
func (r *Router) DELETE(path string, h Handler, m ...Middleware) {
|
||||
r.Group.DELETE(path, chain(h, m...).toEchoHandler())
|
||||
}
|
||||
|
||||
func (r *Router) PATCH(path string, h Handler, m ...Middleware) {
|
||||
r.Group.PATCH(path, chain(h, m...).toEchoHandler())
|
||||
}
|
||||
|
||||
func (r *Router) Any(path string, h Handler, m ...Middleware) {
|
||||
r.Group.Any(path, chain(h, m...).toEchoHandler())
|
||||
}
|
||||
|
||||
func (r *Router) Use(middleware ...Middleware) {
|
||||
for _, m := range middleware {
|
||||
m := m // capture for closure
|
||||
r.Group.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return chain(func(c *context.Context) error {
|
||||
return next(c)
|
||||
}, m).toEchoHandler()
|
||||
})
|
||||
}
|
||||
}
|
65
internal/web/server/server.go
Normal file
65
internal/web/server/server.go
Normal file
@ -0,0 +1,65 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/thomiceli/opengist/internal/validator"
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/thomiceli/opengist/internal/config"
|
||||
"github.com/thomiceli/opengist/internal/i18n"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
echo *echo.Echo
|
||||
|
||||
dev bool
|
||||
sessionsPath string
|
||||
ignoreCsrf bool
|
||||
}
|
||||
|
||||
func NewServer(isDev bool, sessionsPath string, ignoreCsrf bool) *Server {
|
||||
e := echo.New()
|
||||
e.HideBanner = true
|
||||
e.HidePort = true
|
||||
e.Validator = validator.NewValidator()
|
||||
|
||||
s := &Server{echo: e, dev: isDev, sessionsPath: sessionsPath, ignoreCsrf: ignoreCsrf}
|
||||
|
||||
s.useCustomContext()
|
||||
|
||||
if err := i18n.Locales.LoadAll(); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load locales")
|
||||
}
|
||||
|
||||
s.registerMiddlewares()
|
||||
s.setFuncMap()
|
||||
s.echo.HTTPErrorHandler = s.errorHandler
|
||||
|
||||
if !s.dev {
|
||||
s.parseManifestEntries()
|
||||
}
|
||||
|
||||
s.registerRoutes()
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start() {
|
||||
addr := config.C.HttpHost + ":" + config.C.HttpPort
|
||||
|
||||
log.Info().Msg("Starting HTTP server on http://" + addr)
|
||||
if err := s.echo.Start(addr); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatal().Err(err).Msg("Failed to start HTTP server")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Stop() {
|
||||
if err := s.echo.Close(); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to stop HTTP server")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.echo.ServeHTTP(w, r)
|
||||
}
|
Reference in New Issue
Block a user