Open platform to collect and prioritize feedback
more of refactor
goenning21b322662534
diff --git a/app/handlers/common.go b/app/handlers/common.gonew file mode 100644index 000000000..661a25248--- /dev/null+++ b/app/handlers/common.go@@ -0,0 +1,20 @@+package handlers++import (+ "net/http"+ "time"++ "github.com/WeCanHearYou/wechy/app/pkg/web"+)++// Logout remove auth cookies+func Logout() web.HandlerFunc {+ return func(c web.Context) error {+ c.SetCookie(&http.Cookie{+ Name: "auth",+ MaxAge: -1,+ Expires: time.Now().Add(-100 * time.Hour),+ })+ return c.Redirect(http.StatusTemporaryRedirect, c.QueryParam("redirect"))+ }+}diff --git a/app/handlers/identity.go b/app/handlers/identity.goindex 97cdd233b..bf5d61cb6 100644--- a/app/handlers/identity.go+++ b/app/handlers/identity.go@@ -4,7 +4,6 @@ import ("net/http""net/url""strings"- "time""github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/models"@@ -117,18 +116,6 @@ func (h OAuthHandlers) Login(provider string) web.HandlerFunc {}}-// Logout remove auth cookies-func (h OAuthHandlers) Logout() web.HandlerFunc {- return func(c web.Context) error {- c.SetCookie(&http.Cookie{- Name: "auth",- MaxAge: -1,- Expires: time.Now().Add(-100 * time.Hour),- })- return c.Redirect(http.StatusTemporaryRedirect, c.QueryParam("redirect"))- }-}-func stripPort(hostport string) string {colon := strings.IndexByte(hostport, ':')if colon == -1 {diff --git a/app/handlers/status.go b/app/handlers/status.goindex 6ecac97d8..17c5a9b7a 100644--- a/app/handlers/status.go+++ b/app/handlers/status.go@@ -12,11 +12,11 @@ import ()type statusHandler struct {- settings *models.WechySettings+ settings *models.WeCHYSettings}// Status creates a new Status HTTP handler-func Status(settings *models.WechySettings) web.HandlerFunc {+func Status(settings *models.WeCHYSettings) web.HandlerFunc {return statusHandler{settings}.get()}diff --git a/app/handlers/status_test.go b/app/handlers/status_test.goindex 42cfe3af7..727d0dbca 100644--- a/app/handlers/status_test.go+++ b/app/handlers/status_test.go@@ -12,7 +12,7 @@ import (func TestStatusHandler(t *testing.T) {RegisterTestingT(t)- settings := &models.WechySettings{+ settings := &models.WeCHYSettings{BuildTime: "today",}diff --git a/app/models/infra.go b/app/models/infra.goindex ec15abf37..970d20345 100644--- a/app/models/infra.go+++ b/app/models/infra.go@@ -1,7 +1,7 @@package models-// WechySettings is an application-wide settings-type WechySettings struct {+// WeCHYSettings is an application-wide settings+type WeCHYSettings struct {BuildTime stringVersion stringAuthEndpoint stringdiff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.gonew file mode 100644index 000000000..8f4c6c5e8--- /dev/null+++ b/app/pkg/web/engine.go@@ -0,0 +1,100 @@+package web++import (+ "net/http"+ "strings"++ "github.com/WeCanHearYou/wechy/app/pkg/env"+ "github.com/labstack/echo"+ "github.com/labstack/echo/middleware"+ "github.com/labstack/gommon/log"+)++//Engine is our web engine wrapper+type Engine struct {+ router *echo.Echo+}++//New creates a new Engine+func New() *Engine {+ router := echo.New()+ router.Use(middleware.Gzip())+ router.Static("/favicon.ico", "favicon.ico")+ router.Logger = createLogger()+ router.Renderer = NewHTMLRenderer(router.Logger)+ router.HTTPErrorHandler = errorHandler+ return &Engine{router: router}+}++//Start an HTTP server.+func (e *Engine) Start(address string) {+ e.router.Logger.Fatal(e.router.Start(address))+}++//Group is our router group wrapper+type Group struct {+ group *echo.Group+}++//Group creates a new router group with prefix and optional group-level middleware+func (e *Engine) Group(preffix string) *Group {+ return &Group{group: e.router.Group(preffix)}+}++//Use add middleware to sub-routes within the Group+func (g *Group) Use(middleware MiddlewareFunc) {+ g.group.Use(wrapMiddleware(middleware))+}++//Static return files from given folder+func (g *Group) Static(prefix, root string) {+ g.group.Static(prefix, root)+}++//Get handles HTTP GET requests+func (g *Group) Get(path string, handler HandlerFunc) {+ g.group.GET(path, wrapFunc(handler))+}++//Post handles HTTP POST requests+func (g *Group) Post(path string, handler HandlerFunc) {+ g.group.POST(path, wrapFunc(handler))+}++func errorHandler(e error, c echo.Context) {+ if strings.Contains(e.Error(), "code=404") {+ c.Logger().Debug(e)+ c.Render(http.StatusNotFound, "404.html", echo.Map{})+ } else {+ c.Logger().Error(e)+ c.Render(http.StatusInternalServerError, "500.html", echo.Map{})+ }+}++func createLogger() echo.Logger {+ logger := log.New("")+ logger.SetHeader(`${level} [${time_rfc3339}]`)++ if env.IsProduction() {+ logger.SetLevel(log.INFO)+ } else {+ logger.SetLevel(log.DEBUG)+ }++ return logger+}++func wrapMiddleware(mw MiddlewareFunc) echo.MiddlewareFunc {+ return func(h echo.HandlerFunc) echo.HandlerFunc {+ return wrapFunc(mw(func(c Context) error {+ return h(c)+ }))+ }+}++func wrapFunc(handler HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ ctx := Context{Context: c}+ return handler(ctx)+ }+}diff --git a/main.go b/main.goindex f3f5d891b..1023de961 100644--- a/main.go+++ b/main.go@@ -41,12 +41,12 @@ func main() {panic(err)}- ctx := &WechyServices{+ ctx := &WeCHYServices{OAuth: &oauth.HTTPService{},Idea: &postgres.IdeaStorage{DB: db},User: &postgres.UserStorage{DB: db},Tenant: &postgres.TenantStorage{DB: db},- Settings: &models.WechySettings{+ Settings: &models.WeCHYSettings{BuildTime: buildtime,Version: version,AuthEndpoint: env.MustGet("AUTH_ENDPOINT"),@@ -54,5 +54,5 @@ func main() {}e := GetMainEngine(ctx)- e.Logger.Fatal(e.Start(":" + env.GetEnvOrDefault("PORT", "3000")))+ e.Start(":" + env.GetEnvOrDefault("PORT", "3000"))}diff --git a/router.go b/router.goindex b6ce23ea6..4dfd969f0 100644--- a/router.go+++ b/router.go@@ -3,8 +3,6 @@ package mainimport ("net/http"- "strings"-"github.com/WeCanHearYou/wechy/app/handlers""github.com/WeCanHearYou/wechy/app/middlewares""github.com/WeCanHearYou/wechy/app/models"@@ -12,136 +10,73 @@ import ("github.com/WeCanHearYou/wechy/app/pkg/oauth""github.com/WeCanHearYou/wechy/app/pkg/web""github.com/WeCanHearYou/wechy/app/storage"- "github.com/labstack/echo"- "github.com/labstack/echo/middleware"- "github.com/labstack/gommon/log")-// WechyServices holds reference to all Wechy services-type WechyServices struct {+// WeCHYServices holds reference to all Wechy services+type WeCHYServices struct {OAuth oauth.ServiceUser storage.UserTenant storage.TenantIdea storage.Idea- Settings *models.WechySettings-}--func errorHandler(e error, c echo.Context) {- if strings.Contains(e.Error(), "code=404") {- c.Logger().Debug(e)- c.Render(http.StatusNotFound, "404.html", echo.Map{})- } else {- c.Logger().Error(e)- c.Render(http.StatusInternalServerError, "500.html", echo.Map{})- }-}--func createLogger() echo.Logger {- logger := log.New("")- logger.SetHeader(`${level} [${time_rfc3339}]`)-- if env.IsProduction() {- logger.SetLevel(log.INFO)- } else {- logger.SetLevel(log.DEBUG)- }-- return logger-}--func wrapFunc(handler web.HandlerFunc) echo.HandlerFunc {- return func(c echo.Context) error {- ctx := web.Context{Context: c}- return handler(ctx)- }-}--func wrapMiddleware(mw web.MiddlewareFunc) echo.MiddlewareFunc {- return func(h echo.HandlerFunc) echo.HandlerFunc {- return wrapFunc(mw(func(c web.Context) error {- return h(c)- }))- }-}--func get(group *echo.Group, path string, handler web.HandlerFunc) {- group.GET(path, wrapFunc(handler))-}--func post(group *echo.Group, path string, handler web.HandlerFunc) {- group.POST(path, wrapFunc(handler))-}--func use(group *echo.Group, mw web.MiddlewareFunc) {- group.Use(wrapMiddleware(mw))-}--func group(router *echo.Echo, name string) *echo.Group {- return router.Group(name)+ Settings *models.WeCHYSettings}// GetMainEngine returns main HTTP engine-func GetMainEngine(ctx *WechyServices) *echo.Echo {- router := echo.New()-- router.Logger = createLogger()- router.Renderer = web.NewHTMLRenderer(router.Logger)- router.HTTPErrorHandler = errorHandler+func GetMainEngine(ctx *WeCHYServices) *web.Engine {+ r := web.New()- router.Use(middleware.Gzip())- router.Static("/favicon.ico", "favicon.ico")- assetsGroup := group(router, "/assets")+ assets := r.Group("/assets"){- use(assetsGroup, middlewares.OneYearCache())- assetsGroup.Static("/", "dist")+ assets.Use(middlewares.OneYearCache())+ assets.Static("/", "dist")}- oauthHandlers := handlers.OAuth(ctx.Tenant, ctx.OAuth, ctx.User)- authGroup := group(router, "/oauth")+ auth := r.Group("/oauth"){- use(authGroup, middlewares.HostChecker(env.MustGet("AUTH_ENDPOINT")))+ authHandlers := handlers.OAuth(ctx.Tenant, ctx.OAuth, ctx.User)+ auth.Use(middlewares.HostChecker(env.MustGet("AUTH_ENDPOINT")))- get(authGroup, "/facebook", oauthHandlers.Login(oauth.FacebookProvider))- get(authGroup, "/facebook/callback", oauthHandlers.Callback(oauth.FacebookProvider))- get(authGroup, "/google", oauthHandlers.Login(oauth.GoogleProvider))- get(authGroup, "/google/callback", oauthHandlers.Callback(oauth.GoogleProvider))+ auth.Get("/facebook", authHandlers.Login(oauth.FacebookProvider))+ auth.Get("/facebook/callback", authHandlers.Callback(oauth.FacebookProvider))+ auth.Get("/google", authHandlers.Login(oauth.GoogleProvider))+ auth.Get("/google/callback", authHandlers.Callback(oauth.GoogleProvider))}- appGroup := group(router, "")+ public := r.Group(""){- use(appGroup, middlewares.MultiTenant(ctx.Tenant))- use(appGroup, middlewares.JwtGetter(ctx.User))- use(appGroup, middlewares.JwtSetter())-- get(appGroup, "/", handlers.Handlers(ctx.Idea).List())- get(appGroup, "/ideas/:number", handlers.Handlers(ctx.Idea).Details())- get(appGroup, "/logout", oauthHandlers.Logout())- get(appGroup, "/api/status", handlers.Status(ctx.Settings))+ public.Use(middlewares.MultiTenant(ctx.Tenant))+ public.Use(middlewares.JwtGetter(ctx.User))+ public.Use(middlewares.JwtSetter())++ public.Get("/", handlers.Handlers(ctx.Idea).List())+ public.Get("/ideas/:number", handlers.Handlers(ctx.Idea).Details())+ public.Get("/logout", handlers.Logout())+ public.Get("/api/status", handlers.Status(ctx.Settings))}- securedGroup := group(router, "/api")+ api := r.Group("/api"){- use(securedGroup, middlewares.MultiTenant(ctx.Tenant))- use(securedGroup, middlewares.JwtGetter(ctx.User))- use(securedGroup, middlewares.JwtSetter())- use(securedGroup, middlewares.IsAuthenticated())+ api.Use(middlewares.MultiTenant(ctx.Tenant))+ api.Use(middlewares.JwtGetter(ctx.User))+ api.Use(middlewares.JwtSetter())+ api.Use(middlewares.IsAuthenticated())- post(securedGroup, "/ideas", handlers.Handlers(ctx.Idea).PostIdea())- post(securedGroup, "/ideas/:id/comments", handlers.Handlers(ctx.Idea).PostComment())+ api.Post("/ideas", handlers.Handlers(ctx.Idea).PostIdea())+ api.Post("/ideas/:id/comments", handlers.Handlers(ctx.Idea).PostComment())}- adminGroup := group(router, "/admin")+ admin := r.Group("/admin"){- use(adminGroup, middlewares.MultiTenant(ctx.Tenant))- use(adminGroup, middlewares.JwtGetter(ctx.User))- use(adminGroup, middlewares.JwtSetter())- use(adminGroup, middlewares.IsAuthenticated())- use(adminGroup, middlewares.IsAuthorized(models.RoleMember, models.RoleAdministrator))+ admin.Use(middlewares.MultiTenant(ctx.Tenant))+ admin.Use(middlewares.JwtGetter(ctx.User))+ admin.Use(middlewares.JwtSetter())+ admin.Use(middlewares.IsAuthenticated())+ admin.Use(middlewares.IsAuthorized(models.RoleMember, models.RoleAdministrator))- get(adminGroup, "", func(ctx web.Context) error {+ admin.Get("", func(ctx web.Context) error {return ctx.HTML(http.StatusOK, "Welcome to Admin Page :)")})}- return router+ return r}diff --git a/router_test.go b/router_test.godeleted file mode 100644index eebc26592..000000000--- a/router_test.go+++ /dev/null@@ -1,15 +0,0 @@-package main--import (- "testing"-- . "github.com/onsi/gomega"-)--func TestRouter(t *testing.T) {- RegisterTestingT(t)-- ctx := &WechyServices{}- r := GetMainEngine(ctx)- Expect(r).ToNot(BeNil())-}