go-ssb-room/web/handlers/http.go

434 lines
12 KiB
Go
Raw Normal View History

// SPDX-FileCopyrightText: 2021 The NGI Pointer Secure-Scuttlebutt Team of 2020/2021
//
2021-02-09 11:53:33 +00:00
// SPDX-License-Identifier: MIT
2021-02-04 10:36:02 +00:00
package handlers
import (
"bytes"
2021-02-04 10:36:02 +00:00
"fmt"
"html/template"
2021-02-04 10:36:02 +00:00
"net/http"
"net/url"
2021-02-16 11:18:01 +00:00
"time"
2021-02-04 10:36:02 +00:00
2021-02-16 10:20:38 +00:00
"github.com/gorilla/csrf"
2021-02-08 11:57:14 +00:00
"github.com/gorilla/sessions"
"github.com/russross/blackfriday/v2"
2021-02-08 11:57:14 +00:00
"go.mindeco.de/http/auth"
2021-02-04 10:36:02 +00:00
"go.mindeco.de/http/render"
"go.mindeco.de/log/level"
"go.mindeco.de/logging"
2021-02-04 10:36:02 +00:00
"github.com/ssbc/go-ssb-room/v2/internal/network"
"github.com/ssbc/go-ssb-room/v2/internal/repo"
"github.com/ssbc/go-ssb-room/v2/internal/signinwithssb"
"github.com/ssbc/go-ssb-room/v2/roomdb"
"github.com/ssbc/go-ssb-room/v2/roomstate"
"github.com/ssbc/go-ssb-room/v2/web"
weberrs "github.com/ssbc/go-ssb-room/v2/web/errors"
"github.com/ssbc/go-ssb-room/v2/web/handlers/admin"
roomsAuth "github.com/ssbc/go-ssb-room/v2/web/handlers/auth"
"github.com/ssbc/go-ssb-room/v2/web/i18n"
"github.com/ssbc/go-ssb-room/v2/web/members"
"github.com/ssbc/go-ssb-room/v2/web/router"
2021-02-04 10:36:02 +00:00
)
2021-02-25 10:14:39 +00:00
var HTMLTemplates = []string{
"landing/index.tmpl",
"alias.tmpl",
2021-05-11 08:16:35 +00:00
"change-member-password.tmpl",
"invite/consumed.tmpl",
"invite/facade.tmpl",
2021-03-30 15:04:07 +00:00
"invite/facade-fallback.tmpl",
"invite/insert-id.tmpl",
2021-02-23 19:23:50 +00:00
"notice/list.tmpl",
"notice/show.tmpl",
"error.tmpl",
}
// Databases is an options stuct for the required databases of the web handlers
type Databases struct {
2021-03-19 10:19:01 +00:00
Aliases roomdb.AliasesService
2021-03-10 15:44:46 +00:00
AuthFallback roomdb.AuthFallbackService
AuthWithSSB roomdb.AuthWithSSBService
Config roomdb.RoomConfig
2021-03-19 13:02:19 +00:00
DeniedKeys roomdb.DeniedKeysService
2021-03-19 10:19:01 +00:00
Invites roomdb.InvitesService
2021-03-10 15:44:46 +00:00
Notices roomdb.NoticesService
2021-03-19 10:19:01 +00:00
Members roomdb.MembersService
2021-03-10 15:44:46 +00:00
PinnedNotices roomdb.PinnedNoticesService
}
2021-02-04 16:21:21 +00:00
// New initializes the whole web stack for rooms, with all the sub-modules and routing.
2021-02-08 11:57:14 +00:00
func New(
logger logging.Interface,
2021-02-08 11:57:14 +00:00
repo repo.Interface,
netInfo network.ServerEndpointDetails,
roomState *roomstate.Manager,
roomEndpoints network.Endpoints,
bridge *signinwithssb.SignalBridge,
dbs Databases,
2021-02-08 11:57:14 +00:00
) (http.Handler, error) {
m := router.CompleteApp()
2021-04-19 07:07:10 +00:00
urlTo := web.NewURLTo(m, netInfo)
2021-02-04 10:36:02 +00:00
locHelper, err := i18n.New(repo, dbs.Config)
if err != nil {
return nil, err
}
2021-04-05 07:12:05 +00:00
cookieCodec, err := web.LoadOrCreateCookieSecrets(repo)
if err != nil {
return nil, err
}
cookieStore := &sessions.CookieStore{
Codecs: cookieCodec,
Options: &sessions.Options{
Path: "/",
MaxAge: 2 * 60 * 60, // two hours in seconds // TODO: configure
},
}
flashHelper := weberrs.NewFlashHelper(cookieStore, locHelper)
eh := weberrs.NewErrorHandler(locHelper, flashHelper)
allTheTemplates := concatTemplates(
HTMLTemplates,
roomsAuth.HTMLTemplates,
admin.HTMLTemplates,
)
2021-04-01 07:04:38 +00:00
renderOpts := []render.Option{
render.SetLogger(logger),
2021-04-01 07:04:38 +00:00
render.BaseTemplates("base.tmpl", "menu.tmpl", "flashes.tmpl"),
render.AddTemplates(allTheTemplates...),
render.SetErrorHandler(eh.Handle),
render.FuncMap(web.TemplateFuncs(m, netInfo)),
2021-05-14 13:11:29 +00:00
render.InjectTemplateFunc("privacy_mode_is", func(r *http.Request) interface{} {
return func(want string) bool {
has, err := dbs.Config.GetPrivacyMode(r.Context())
if err != nil {
return false
}
return has.String() == want
}
}),
render.InjectTemplateFunc("current_page_is", func(r *http.Request) interface{} {
return func(routeName string) bool {
route := m.Get(routeName)
if route == nil {
return false
}
url, err := route.URLPath()
if err != nil {
return false
}
return r.RequestURI == url.Path
}
}),
render.InjectTemplateFunc("language_count", func(r *http.Request) interface{} {
return func() int {
return len(locHelper.ListLanguages())
}
}),
render.InjectTemplateFunc("list_languages", func(r *http.Request) interface{} {
return func(postRoute *url.URL, classList string) (template.HTML, error) {
2021-04-15 08:23:04 +00:00
languages := locHelper.ListLanguages()
var buf bytes.Buffer
for _, entry := range languages {
data := changeLanguageTemplateData{
PostRoute: postRoute.String(),
CSRFElement: csrf.TemplateField(r),
LangTag: entry.Tag,
RedirectPage: r.RequestURI,
Translation: entry.Translation,
ClassList: classList,
}
err = changeLanguageTemplate.Execute(&buf, data)
if err != nil {
return "", fmt.Errorf("Error while executing change language template: %w", err)
}
2021-04-15 08:23:04 +00:00
}
return (template.HTML)(buf.String()), nil
2021-04-15 08:23:04 +00:00
}
}),
render.InjectTemplateFunc("urlToNotice", func(r *http.Request) interface{} {
return func(name string) *url.URL {
2021-03-10 15:44:46 +00:00
noticeName := roomdb.PinnedNoticeName(name)
if !noticeName.Valid() {
return nil
}
notice, err := dbs.PinnedNotices.Get(r.Context(), noticeName, "en-GB")
if err != nil {
return nil
}
2021-04-19 07:07:10 +00:00
return urlTo(router.CompleteNoticeShow, "id", notice.ID)
}
}),
2021-04-01 07:04:38 +00:00
}
2021-04-01 07:04:38 +00:00
renderOpts = append(renderOpts, locHelper.GetRenderFuncs()...)
renderOpts = append(renderOpts, members.TemplateHelpers(dbs.Config)...)
2021-04-01 07:04:38 +00:00
r, err := render.New(web.Templates, renderOpts...)
2021-02-04 10:36:02 +00:00
if err != nil {
return nil, fmt.Errorf("web Handler: failed to create renderer: %w", err)
}
eh.SetRenderer(r)
2021-02-04 10:36:02 +00:00
authWithPassword, err := auth.NewHandler(dbs.AuthFallback,
auth.SetStore(cookieStore),
auth.SetErrorHandler(func(rw http.ResponseWriter, req *http.Request, err error, code int) {
eh.Handle(rw, req, code, err)
}),
auth.SetNotAuthorizedHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
eh.Handle(rw, req, http.StatusForbidden, weberrs.ErrNotAuthorized)
})),
2021-02-16 11:18:01 +00:00
auth.SetLifetime(2*time.Hour), // TODO: configure
2021-02-08 11:57:14 +00:00
)
if err != nil {
return nil, fmt.Errorf("web Handler: failed to init fallback auth system: %w", err)
}
2021-02-16 10:20:38 +00:00
// Cross Site Request Forgery prevention middleware
csrfKey, err := web.LoadOrCreateCSRFSecret(repo)
if err != nil {
return nil, err
}
CSRF := csrf.Protect(csrfKey,
csrf.Path("/"),
2021-02-16 10:20:38 +00:00
csrf.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
err := csrf.FailureReason(req)
// TODO: localize error?
r.Error(w, req, http.StatusForbidden, err)
})),
)
2021-02-11 15:43:19 +00:00
// this router is a bit of a qurik
// TODO: explain problem between gorilla/mux named routers and authentication
mainMux := &http.ServeMux{}
// start hooking up handlers to the router
authWithSSB := roomsAuth.NewWithSSBHandler(
m,
r,
netInfo,
roomEndpoints,
dbs.Aliases,
dbs.Members,
dbs.AuthWithSSB,
cookieStore,
bridge,
)
// auth routes
2021-04-09 10:44:12 +00:00
m.Get(router.AuthLogin).HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if label := req.URL.Query().Get("ssb-http-auth"); label != "" {
authWithSSB.DecideMethod(w, req)
} else {
r.Render(w, req, "auth/decide_method.tmpl", http.StatusOK, nil)
}
})
2021-03-26 15:30:57 +00:00
m.Get(router.AuthFallbackFinalize).HandlerFunc(authWithPassword.Authorize)
m.Get(router.AuthFallbackLogin).Handler(r.HTML("auth/fallback_sign_in.tmpl", func(w http.ResponseWriter, req *http.Request) (interface{}, error) {
2021-04-05 07:12:05 +00:00
pageData := map[string]interface{}{
2021-03-26 15:30:57 +00:00
csrf.TemplateTag: csrf.TemplateField(req),
2021-04-05 07:12:05 +00:00
}
pageData["Flashes"], err = flashHelper.GetAll(w, req)
if err != nil {
return nil, err
}
return pageData, nil
2021-03-26 15:30:57 +00:00
}))
2021-03-25 17:38:21 +00:00
m.Get(router.AuthLogout).HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
err = authWithSSB.Logout(w, req)
if err != nil {
level.Warn(logging.FromContext(req.Context())).Log("err", err)
}
authWithPassword.Logout(w, req)
})
// all the admin routes
adminHandler := admin.Handler(
netInfo,
r,
2021-03-03 12:58:06 +00:00
roomState,
2021-04-01 07:04:38 +00:00
flashHelper,
locHelper,
admin.Databases{
Aliases: dbs.Aliases,
AuthFallback: dbs.AuthFallback,
Config: dbs.Config,
2021-03-19 13:02:19 +00:00
DeniedKeys: dbs.DeniedKeys,
Invites: dbs.Invites,
Notices: dbs.Notices,
2021-03-19 13:02:19 +00:00
Members: dbs.Members,
PinnedNotices: dbs.PinnedNotices,
},
)
mainMux.Handle("/admin/", members.AuthenticateFromContext(r)(adminHandler))
2021-02-04 10:36:02 +00:00
var mh = newMembersHandler(netInfo.Development, r, urlTo, flashHelper, dbs.AuthFallback)
m.Get(router.MembersChangePasswordForm).HandlerFunc(r.HTML("change-member-password.tmpl", mh.changePasswordForm))
m.Get(router.MembersChangePassword).HandlerFunc(mh.changePassword)
2021-05-11 08:16:35 +00:00
2021-04-15 08:23:04 +00:00
// handle setting language
m.Get(router.CompleteSetLanguage).HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
lang := req.FormValue("lang")
previousRoute := req.FormValue("page")
session, err := cookieStore.Get(req, i18n.LanguageCookieName)
if err != nil {
2021-04-20 08:19:19 +00:00
eh.Handle(w, req, http.StatusInternalServerError, err)
2021-04-15 08:23:04 +00:00
return
}
session.Values["lang"] = lang
err = session.Save(req, w)
if err != nil {
err = fmt.Errorf("we failed to save the language session cookie %w\n", err)
eh.Handle(w, req, http.StatusInternalServerError, err)
return
2021-04-15 08:23:04 +00:00
}
2021-04-15 09:00:34 +00:00
http.Redirect(w, req, previousRoute, http.StatusSeeOther)
2021-04-15 08:23:04 +00:00
})
// landing page
m.Get(router.CompleteIndex).Handler(r.HTML("landing/index.tmpl", func(w http.ResponseWriter, req *http.Request) (interface{}, error) {
// TODO: try websocket upgrade (issue #)
2021-03-10 15:44:46 +00:00
notice, err := dbs.PinnedNotices.Get(req.Context(), roomdb.NoticeDescription, "en-GB")
if err != nil {
return nil, fmt.Errorf("failed to find description: %w", err)
}
markdown := blackfriday.Run([]byte(notice.Content), blackfriday.WithNoExtensions())
return noticeShowData{
ID: notice.ID,
Title: notice.Title,
Content: template.HTML(markdown),
Language: notice.Language,
}, nil
}))
2021-02-04 10:36:02 +00:00
// notices (the mini-CMS)
var nh = noticeHandler{
render: r,
flashes: flashHelper,
notices: dbs.Notices,
pinned: dbs.PinnedNotices,
}
m.Get(router.CompleteNoticeList).HandlerFunc(nh.list)
m.Get(router.CompleteNoticeShow).Handler(r.HTML("notice/show.tmpl", nh.show))
// public aliases
2021-03-15 11:25:07 +00:00
var ah = aliasHandler{
r: r,
db: dbs.Aliases,
config: dbs.Config,
2021-03-15 11:25:07 +00:00
roomEndpoint: netInfo,
2021-03-15 11:25:07 +00:00
}
m.Get(router.CompleteAliasResolve).HandlerFunc(ah.resolve)
//public invites
var ih = inviteHandler{
render: r,
2021-04-19 07:07:10 +00:00
urlTo: urlTo,
networkInfo: netInfo,
config: dbs.Config,
pinnedNotices: dbs.PinnedNotices,
invites: dbs.Invites,
deniedKeys: dbs.DeniedKeys,
}
m.Get(router.CompleteInviteFacade).HandlerFunc(ih.presentFacade)
2021-03-30 15:04:07 +00:00
m.Get(router.CompleteInviteFacadeFallback).Handler(r.HTML("invite/facade-fallback.tmpl", ih.presentFacadeFallback))
m.Get(router.CompleteInviteInsertID).Handler(r.HTML("invite/insert-id.tmpl", ih.presentInsert))
m.Get(router.CompleteInviteConsume).HandlerFunc(ih.consume)
m.Get(router.OpenModeCreateInvite).HandlerFunc(ih.createOpenMode)
// static assets
m.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", http.FileServer(web.Assets)))
2021-02-04 16:46:51 +00:00
// TODO: doesnt work because of of mainMux wrapper, see issue #35
m.NotFoundHandler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
eh.Handle(rw, req, http.StatusNotFound, weberrs.PageNotFound{Path: req.URL.Path})
2021-02-04 10:36:02 +00:00
})
// hook up main stdlib mux to the gorrilla/mux with named routes
// TODO: issue #35
2021-02-11 15:43:19 +00:00
mainMux.Handle("/", m)
consumeURL := urlTo(router.CompleteInviteConsume)
openModeCreateInviteURL := urlTo(router.OpenModeCreateInvite)
// apply HTTP middleware
middlewares := []func(http.Handler) http.Handler{
members.ContextInjecter(dbs.Members, authWithPassword, authWithSSB),
CSRF,
// We disable CSRF for certain requests that are done by apps
// only if they already contain some secret (like invite consumption)
func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ct := req.Header.Get("Content-Type")
if req.URL.Path == consumeURL.Path && ct == "application/json" {
next.ServeHTTP(w, csrf.UnsafeSkipCheck(req))
return
}
if req.URL.Path == openModeCreateInviteURL.Path && req.Header.Get("Accept") == "application/json" {
next.ServeHTTP(w, csrf.UnsafeSkipCheck(req))
return
}
next.ServeHTTP(w, req)
})
},
logging.InjectHandler(logger),
logging.RecoveryHandler(),
}
if !web.Production {
middlewares = append(middlewares, r.GetReloader())
}
var finalHandler http.Handler = mainMux
for _, applyMiddleware := range middlewares {
finalHandler = applyMiddleware(finalHandler)
2021-02-08 11:57:14 +00:00
}
return finalHandler, nil
2021-02-04 10:36:02 +00:00
}
2021-02-08 11:57:14 +00:00
// utils
func concatTemplates(lst ...[]string) []string {
var catted []string
for _, tpls := range lst {
for _, t := range tpls {
catted = append(catted, t)
}
}
return catted
}