Open platform to collect and prioritize feedback
major refactor on backend
goenning420c8207cb8f
diff --git a/app/identity/const.go b/app/const.gosimilarity index 87%rename from app/identity/const.gorename to app/const.goindex 5f0687386..12ff0e9c8 100644--- a/app/identity/const.go+++ b/app/const.go@@ -1,4 +1,4 @@-package identity+package appimport "errors"diff --git a/app/context.go b/app/context.gonew file mode 100644index 000000000..22e148d93--- /dev/null+++ b/app/context.go@@ -0,0 +1,52 @@+package app++import (+ "net/http"+ "strconv"++ "github.com/labstack/echo"+)++//Context wraps echo.context to provide userful WeCHY information+type Context struct {+ echo.Context+}++//Tenant returns current tenant+func (ctx *Context) Tenant() *Tenant {+ tenant, ok := ctx.Get("Tenant").(*Tenant)+ if ok {+ return tenant+ }+ return nil+}++//IsAuthenticated returns true if user is authenticated+func (ctx *Context) IsAuthenticated() bool {+ return ctx.Get("Claims") != nil+}++//Failure returns a 500 response+func (ctx *Context) Failure(err error) error {+ return echo.NewHTTPError(http.StatusInternalServerError, err)+}++//Claims returns authenticated user claims+func (ctx *Context) Claims() *WechyClaims {+ return ctx.Get("Claims").(*WechyClaims)+}++//ParamAsInt64 returns parameter as int64+func (ctx *Context) ParamAsInt64(name string) (int64, error) {+ val, err := strconv.Atoi(ctx.Param(name))+ if err != nil {+ return 0, err+ }+ return int64(val), nil+}++//HandlerFunc represents an HTTP handler+type HandlerFunc func(Context) error++//MiddlewareFunc represents an HTTP middleware+type MiddlewareFunc func(HandlerFunc) HandlerFuncdiff --git a/app/feedback/handler.go b/app/feedback/handler.goindex d684b4aa8..e0f2e5813 100644--- a/app/feedback/handler.go+++ b/app/feedback/handler.go@@ -5,7 +5,7 @@ import ("strconv"- "github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app""github.com/labstack/echo")@@ -20,17 +20,15 @@ func Index(ideaService IdeaService) IndexHandlder {}// List all tenant ideas-func (h IndexHandlder) List() echo.HandlerFunc {- return func(c echo.Context) error {- tenant := c.Get("Tenant").(*identity.Tenant)- ideas, err := h.ideaService.GetAll(tenant.ID)+func (h IndexHandlder) List() app.HandlerFunc {+ return func(c app.Context) error {+ ideas, err := h.ideaService.GetAll(c.Tenant().ID)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, err)+ return c.Failure(err)}return c.Render(200, "index.html", echo.Map{- "Tenant": tenant,- "Ideas": ideas,+ "Ideas": ideas,})}}@@ -41,15 +39,12 @@ type newIdeaInput struct {}// Post creates a new idea on current tenant-func (h IndexHandlder) Post() echo.HandlerFunc {- return func(c echo.Context) error {+func (h IndexHandlder) Post() app.HandlerFunc {+ return func(c app.Context) error {input := new(newIdeaInput)c.Bind(input)- tenant := c.Get("Tenant").(*identity.Tenant)- claims := c.Get("Claims").(*identity.WechyClaims)-- idea, err := h.ideaService.Save(tenant.ID, claims.UserID, input.Title, input.Description)+ idea, err := h.ideaService.Save(c.Tenant().ID, c.Claims().UserID, input.Title, input.Description)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, err)}@@ -61,15 +56,14 @@ func (h IndexHandlder) Post() echo.HandlerFunc {}// Details shows details of given Idea by id-func (h IndexHandlder) Details() echo.HandlerFunc {- return func(c echo.Context) error {- tenant := c.Get("Tenant").(*identity.Tenant)+func (h IndexHandlder) Details() app.HandlerFunc {+ return func(c app.Context) error {+ tenant := c.Tenant()ideaID, _ := strconv.Atoi(c.Param("id"))idea, _ := h.ideaService.GetByID(tenant.ID, int64(ideaID))comments, _ := h.ideaService.GetCommentsByIdeaID(tenant.ID, idea.ID)return c.Render(200, "idea.html", echo.Map{- "Tenant": tenant,"Comments": comments,"Idea": idea,})@@ -81,17 +75,16 @@ type newCommentInput struct {}// PostComment creates a new comment on given idea-func (h IndexHandlder) PostComment() echo.HandlerFunc {- return func(c echo.Context) error {+func (h IndexHandlder) PostComment() app.HandlerFunc {+ return func(c app.Context) error {input := new(newCommentInput)c.Bind(input)- ideaID, _ := strconv.Atoi(c.Param("id"))- claims := c.Get("Claims").(*identity.WechyClaims)+ ideaID, _ := c.ParamAsInt64("id")- id, err := h.ideaService.AddComment(claims.UserID, int64(ideaID), input.Content)+ id, err := h.ideaService.AddComment(c.Claims().UserID, ideaID, input.Content)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, err)+ return c.Failure(err)}return c.JSON(200, echo.Map{diff --git a/app/feedback/handler_test.go b/app/feedback/handler_test.goindex 7de1f9c5b..08bcccd46 100644--- a/app/feedback/handler_test.go+++ b/app/feedback/handler_test.go@@ -3,8 +3,8 @@ package feedback_testimport ("testing"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/feedback"- "github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/mock". "github.com/onsi/gomega")@@ -35,7 +35,7 @@ func TestIndexHandler(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- server.Context.Set("Tenant", &identity.Tenant{ID: 2, Name: "Any Tenant"})+ server.Context.Set("Tenant", &app.Tenant{ID: 2, Name: "Any Tenant"})code, _ := server.Execute(feedback.Index(&mockIdeaService{}).List())Expect(code).To(Equal(200))diff --git a/app/feedback/model.go b/app/feedback/model.goindex e1254ee77..ed6d42b8d 100644--- a/app/feedback/model.go+++ b/app/feedback/model.go@@ -3,22 +3,22 @@ package feedbackimport ("time"- "github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app")//Idea represents an idea on a tenant boardtype Idea struct {- ID int64 `json:"id"`- Title string `json:"title"`- Description string `json:"description"`- CreatedOn time.Time `json:"createdOn"`- User identity.User `json:"user"`+ ID int64 `json:"id"`+ Title string `json:"title"`+ Description string `json:"description"`+ CreatedOn time.Time `json:"createdOn"`+ User app.User `json:"user"`}//Comment represents an user comment on an ideatype Comment struct {- ID int64 `json:"id"`- Content string `json:"content"`- CreatedOn time.Time `json:"createdOn"`- User identity.User `json:"user"`+ ID int64 `json:"id"`+ Content string `json:"content"`+ CreatedOn time.Time `json:"createdOn"`+ User app.User `json:"user"`}diff --git a/app/identity/handler.go b/app/identity/handler.goindex ff5897609..7432addfc 100644--- a/app/identity/handler.go+++ b/app/identity/handler.go@@ -5,6 +5,7 @@ import ("net/url""time"+ "github.com/WeCanHearYou/wechy/app""github.com/labstack/echo")@@ -26,8 +27,8 @@ func OAuth(oauthService OAuthService, userService UserService) OAuthHandlers {}// Callback handles OAuth callbacks-func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {- return func(c echo.Context) error {+func (h OAuthHandlers) Callback(provider string) app.HandlerFunc {+ return func(c app.Context) error {var redirectURL *url.URLvar err error@@ -49,12 +50,12 @@ func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {user, err := h.userService.GetByEmail(oauthUser.Email)if err != nil {- if err == ErrNotFound {- user = &User{+ if err == app.ErrNotFound {+ user = &app.User{Name: oauthUser.Name,Email: oauthUser.Email,- Providers: []*UserProvider{- &UserProvider{+ Providers: []*app.UserProvider{+ &app.UserProvider{UID: oauthUser.ID,Name: provider,},@@ -70,7 +71,7 @@ func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {}}- claims := &WechyClaims{+ claims := &app.WechyClaims{UserID: user.ID,UserName: user.Name,UserEmail: user.Email,@@ -90,16 +91,16 @@ func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {}// Login handles OAuth logins-func (h OAuthHandlers) Login(provider string) echo.HandlerFunc {- return func(c echo.Context) error {+func (h OAuthHandlers) Login(provider string) app.HandlerFunc {+ return func(c app.Context) error {authURL := h.oauthService.GetAuthURL(provider, c.QueryParam("redirect"))return c.Redirect(http.StatusTemporaryRedirect, authURL)}}// Logout remove auth cookies-func (h OAuthHandlers) Logout() echo.HandlerFunc {- return func(c echo.Context) error {+func (h OAuthHandlers) Logout() app.HandlerFunc {+ return func(c app.Context) error {c.SetCookie(&http.Cookie{Name: "auth",MaxAge: -1,diff --git a/app/identity/jwt.go b/app/identity/jwt.goindex 1d5af3d8d..3026d7d04 100644--- a/app/identity/jwt.go+++ b/app/identity/jwt.go@@ -1,29 +1,22 @@package identityimport (+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/toolbox/env"jwt "github.com/dgrijalva/jwt-go")-//WechyClaims represents what goes into JWT tokens-type WechyClaims struct {- UserID int64 `json:"user/id"`- UserName string `json:"user/name"`- UserEmail string `json:"user/email"`- jwt.StandardClaims-}-var jwtSecret = env.MustGet("JWT_SECRET")//Encode creates new JWT tokens with given claims-func Encode(claims *WechyClaims) (string, error) {+func Encode(claims *app.WechyClaims) (string, error) {jwtToken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)return jwtToken.SignedString([]byte(jwtSecret))}//Decode extract claims from JWT tokens-func Decode(token string) (*WechyClaims, error) {- claims := &WechyClaims{}+func Decode(token string) (*app.WechyClaims, error) {+ claims := &app.WechyClaims{}jwtToken, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {return []byte(jwtSecret), nil})diff --git a/app/identity/jwt_test.go b/app/identity/jwt_test.goindex f595fbb78..19a540fae 100644--- a/app/identity/jwt_test.go+++ b/app/identity/jwt_test.go@@ -3,6 +3,7 @@ package identity_testimport ("testing"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/identity". "github.com/onsi/gomega")@@ -10,7 +11,7 @@ import (func TestJWT_Encode(t *testing.T) {RegisterTestingT(t)- claims := &identity.WechyClaims{+ claims := &app.WechyClaims{UserID: 424,UserName: "Jon Snow",UserEmail: "[email protected]",@@ -24,7 +25,7 @@ func TestJWT_Encode(t *testing.T) {func TestJWT_Decode(t *testing.T) {RegisterTestingT(t)- claims := &identity.WechyClaims{+ claims := &app.WechyClaims{UserID: 424,UserName: "Jon Snow",UserEmail: "[email protected]",diff --git a/app/identity/middleware.go b/app/identity/middleware.goindex 8021fcb92..d7fcaca73 100644--- a/app/identity/middleware.go+++ b/app/identity/middleware.go@@ -5,13 +5,13 @@ import ("net/url""strings"- "github.com/labstack/echo"+ "github.com/WeCanHearYou/wechy/app")// MultiTenant extract tenant information from hostname and inject it into current context-func MultiTenant(tenantService TenantService) echo.MiddlewareFunc {- return func(next echo.HandlerFunc) echo.HandlerFunc {- return func(c echo.Context) error {+func MultiTenant(tenantService TenantService) app.MiddlewareFunc {+ return func(next app.HandlerFunc) app.HandlerFunc {+ return func(c app.Context) error {hostname := stripPort(c.Request().Host)tenant, err := tenantService.GetByDomain(hostname)if err == nil {@@ -26,9 +26,9 @@ func MultiTenant(tenantService TenantService) echo.MiddlewareFunc {}// JwtGetter gets JWT token from cookie and add into context-func JwtGetter() echo.MiddlewareFunc {- return func(next echo.HandlerFunc) echo.HandlerFunc {- return func(c echo.Context) error {+func JwtGetter() app.MiddlewareFunc {+ return func(next app.HandlerFunc) app.HandlerFunc {+ return func(c app.Context) error {if cookie, err := c.Cookie("auth"); err == nil {if claims, err := Decode(cookie.Value); err == nil {@@ -44,9 +44,9 @@ func JwtGetter() echo.MiddlewareFunc {}// JwtSetter sets JWT token into cookie-func JwtSetter() echo.MiddlewareFunc {- return func(next echo.HandlerFunc) echo.HandlerFunc {- return func(c echo.Context) error {+func JwtSetter() app.MiddlewareFunc {+ return func(next app.HandlerFunc) app.HandlerFunc {+ return func(c app.Context) error {query := c.Request().URL.Query()@@ -81,9 +81,9 @@ func JwtSetter() echo.MiddlewareFunc {}// HostChecker checks for a specific host-func HostChecker(baseURL string) echo.MiddlewareFunc {- return func(next echo.HandlerFunc) echo.HandlerFunc {- return func(c echo.Context) error {+func HostChecker(baseURL string) app.MiddlewareFunc {+ return func(next app.HandlerFunc) app.HandlerFunc {+ return func(c app.Context) error {u, _ := url.Parse(baseURL)if c.Request().Host != u.Host {diff --git a/app/identity/middleware_test.go b/app/identity/middleware_test.goindex d17b08735..fa6965cc3 100644--- a/app/identity/middleware_test.go+++ b/app/identity/middleware_test.go@@ -5,19 +5,21 @@ import ("net/http/httptest""testing"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app/mock""github.com/labstack/echo". "github.com/onsi/gomega")var testCases = []struct {domain string- tenant *identity.Tenant+ tenant *app.Tenanthosts []string}{{"orange.test.canhearyou.com",- &identity.Tenant{Name: "The Orange Inc."},+ &app.Tenant{Name: "The Orange Inc."},[]string{"orange.test.canhearyou.com","orange.test.canhearyou.com:3000",@@ -25,7 +27,7 @@ var testCases = []struct {},{"trishop.test.canhearyou.com",- &identity.Tenant{Name: "The Triathlon Shop"},+ &app.Tenant{Name: "The Triathlon Shop"},[]string{"trishop.test.canhearyou.com","trishop.test.canhearyou.com:1231",@@ -36,13 +38,13 @@ var testCases = []struct {type mockTenantService struct{}-func (svc mockTenantService) GetByDomain(domain string) (*identity.Tenant, error) {+func (svc mockTenantService) GetByDomain(domain string) (*app.Tenant, error) {for _, testCase := range testCases {if testCase.domain == domain {return testCase.tenant, nil}}- return nil, identity.ErrNotFound+ return nil, app.ErrNotFound}func TestMultiTenant(t *testing.T) {@@ -51,16 +53,16 @@ func TestMultiTenant(t *testing.T) {for _, testCase := range testCases {for _, host := range testCase.hosts {- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = hostmw := identity.MultiTenant(&mockTenantService{})- mw(echo.HandlerFunc(func(c echo.Context) error {- return c.String(http.StatusOK, c.Get("Tenant").(*identity.Tenant).Name)- }))(c)+ mw(func(c app.Context) error {+ return c.String(http.StatusOK, c.Tenant().Name)+ })(c)Expect(rec.Code).To(Equal(200))Expect(rec.Body.String()).To(Equal(testCase.tenant.Name))@@ -71,16 +73,16 @@ func TestMultiTenant(t *testing.T) {func TestMultiTenant_UnknownDomain(t *testing.T) {RegisterTestingT(t)- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = "somedomain.com"mw := identity.MultiTenant(&mockTenantService{})- mw(echo.HandlerFunc(func(c echo.Context) error {- return c.String(http.StatusOK, c.Get("Tenant").(*identity.Tenant).Name)- }))(c)+ mw(func(c app.Context) error {+ return c.String(http.StatusOK, c.Get("Tenant").(*app.Tenant).Name)+ })(c)Expect(rec.Code).To(Equal(404))}@@ -88,19 +90,19 @@ func TestMultiTenant_UnknownDomain(t *testing.T) {func TestJwtGetter_NoCookie(t *testing.T) {RegisterTestingT(t)- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)mw := identity.JwtGetter()- mw(echo.HandlerFunc(func(c echo.Context) error {- if c.Get("Claims") == nil {- return c.NoContent(http.StatusNoContent)- } else {+ mw(func(c app.Context) error {+ if c.IsAuthenticated() {return c.NoContent(http.StatusOK)+ } else {+ return c.NoContent(http.StatusNoContent)}- }))(c)+ })(c)Expect(rec.Code).To(Equal(http.StatusNoContent))}@@ -108,24 +110,23 @@ func TestJwtGetter_NoCookie(t *testing.T) {func TestJwtGetter_WithCookie(t *testing.T) {RegisterTestingT(t)- token, _ := identity.Encode(&identity.WechyClaims{+ token, _ := identity.Encode(&app.WechyClaims{UserName: "Jon Snow",})- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().AddCookie(&http.Cookie{Name: "auth",Value: token,})mw := identity.JwtGetter()- mw(echo.HandlerFunc(func(c echo.Context) error {- claims := c.Get("Claims").(*identity.WechyClaims)- return c.String(http.StatusOK, claims.UserName)- }))(c)+ mw(func(c app.Context) error {+ return c.String(http.StatusOK, c.Claims().UserName)+ })(c)Expect(rec.Code).To(Equal(http.StatusOK))Expect(rec.Body.String()).To(Equal("Jon Snow"))@@ -134,16 +135,16 @@ func TestJwtGetter_WithCookie(t *testing.T) {func TestJwtSetter_WithoutJwt(t *testing.T) {RegisterTestingT(t)- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/abc", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = "orange.test.canhearyou.com"mw := identity.JwtSetter()- mw(echo.HandlerFunc(func(c echo.Context) error {+ mw(func(c app.Context) error {return c.NoContent(http.StatusOK)- }))(c)+ })(c)Expect(rec.Code).To(Equal(http.StatusOK))}@@ -151,20 +152,20 @@ func TestJwtSetter_WithoutJwt(t *testing.T) {func TestJwtSetter_WithJwt_WithoutParameter(t *testing.T) {RegisterTestingT(t)- token, _ := identity.Encode(&identity.WechyClaims{+ token, _ := identity.Encode(&app.WechyClaims{UserName: "Jon Snow",})- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token, nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = "orange.test.canhearyou.com"mw := identity.JwtSetter()- mw(echo.HandlerFunc(func(c echo.Context) error {+ mw(func(c app.Context) error {return c.NoContent(http.StatusOK)- }))(c)+ })(c)Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc"))@@ -173,20 +174,20 @@ func TestJwtSetter_WithJwt_WithoutParameter(t *testing.T) {func TestJwtSetter_WithJwt_WithParameter(t *testing.T) {RegisterTestingT(t)- token, _ := identity.Encode(&identity.WechyClaims{+ token, _ := identity.Encode(&app.WechyClaims{UserName: "Jon Snow",})- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token+"&foo=bar", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = "orange.test.canhearyou.com"mw := identity.JwtSetter()- mw(echo.HandlerFunc(func(c echo.Context) error {+ mw(func(c app.Context) error {return c.NoContent(http.StatusOK)- }))(c)+ })(c)Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc?foo=bar"))@@ -195,16 +196,16 @@ func TestJwtSetter_WithJwt_WithParameter(t *testing.T) {func TestHostChecker(t *testing.T) {RegisterTestingT(t)- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = "login.test.canhearyou.com"mw := identity.HostChecker("http://login.test.canhearyou.com")- mw(echo.HandlerFunc(func(c echo.Context) error {+ mw(func(c app.Context) error {return c.NoContent(http.StatusOK)- }))(c)+ })(c)Expect(rec.Code).To(Equal(http.StatusOK))}@@ -212,14 +213,14 @@ func TestHostChecker(t *testing.T) {func TestHostChecker_DifferentHost(t *testing.T) {RegisterTestingT(t)- e := echo.New()+ server := mock.NewServer()req, _ := http.NewRequest(echo.GET, "/", nil)rec := httptest.NewRecorder()- c := e.NewContext(req, rec)+ c := server.NewContext(req, rec)c.Request().Host = "orange.test.canhearyou.com"mw := identity.HostChecker("login.test.canhearyou.com")- mw(echo.HandlerFunc(func(c echo.Context) error {+ mw(app.HandlerFunc(func(c app.Context) error {return c.NoContent(http.StatusOK)}))(c)diff --git a/app/identity/service.go b/app/identity/service.goindex 199a7864d..4aae228f9 100644--- a/app/identity/service.go+++ b/app/identity/service.go@@ -1,12 +1,14 @@package identity+import "github.com/WeCanHearYou/wechy/app"+// UserService is used for user operationstype UserService interface {- GetByEmail(email string) (*User, error)- Register(user *User) error+ GetByEmail(email string) (*app.User, error)+ Register(user *app.User) error}// TenantService contains read and write operations for tenantstype TenantService interface {- GetByDomain(domain string) (*Tenant, error)+ GetByDomain(domain string) (*app.Tenant, error)}diff --git a/app/handler.go b/app/infra/handler.gosimilarity index 81%rename from app/handler.gorename to app/infra/handler.goindex 0c6af735f..d41c6fb6b 100644--- a/app/handler.go+++ b/app/infra/handler.go@@ -1,10 +1,11 @@-package app+package infraimport ("net/http""runtime""time"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/toolbox/env""github.com/labstack/echo")@@ -15,12 +16,12 @@ type statusHandler struct {}// Status creates a new Status HTTP handler-func Status(healthService HealthCheckService, settings *WechySettings) echo.HandlerFunc {+func Status(healthService HealthCheckService, settings *WechySettings) app.HandlerFunc {return statusHandler{healthService, settings}.get()}-func (h statusHandler) get() echo.HandlerFunc {- return func(c echo.Context) error {+func (h statusHandler) get() app.HandlerFunc {+ return func(c app.Context) error {return c.JSON(http.StatusOK, echo.Map{"build": h.settings.BuildTime,"version": h.settings.Version,diff --git a/app/handler_test.go b/app/infra/handler_test.gosimilarity index 75%rename from app/handler_test.gorename to app/infra/handler_test.goindex e3512abec..bdc91adce 100644--- a/app/handler_test.go+++ b/app/infra/handler_test.go@@ -1,9 +1,9 @@-package app_test+package infra_testimport ("testing"- "github.com/WeCanHearYou/wechy/app"+ "github.com/WeCanHearYou/wechy/app/infra""github.com/WeCanHearYou/wechy/app/mock". "github.com/onsi/gomega")@@ -18,12 +18,12 @@ func TestStatusHandler(t *testing.T) {RegisterTestingT(t)service := &falsyHealthCheckService{}- settings := &app.WechySettings{+ settings := &infra.WechySettings{BuildTime: "today",}server := mock.NewServer()- status, query := server.Execute(app.Status(service, settings))+ status, query := server.Execute(infra.Status(service, settings))Expect(query.String("build")).To(Equal("today"))Expect(query.Bool("healthy", "database")).To(Equal(false))diff --git a/app/infra/model.go b/app/infra/model.gonew file mode 100644index 000000000..908fab33b--- /dev/null+++ b/app/infra/model.go@@ -0,0 +1,8 @@+package infra++// WechySettings is an application-wide settings+type WechySettings struct {+ BuildTime string+ Version string+ AuthEndpoint string+}diff --git a/app/service.go b/app/infra/service.gosimilarity index 90%rename from app/service.gorename to app/infra/service.goindex 70ae91272..c7619a9dc 100644--- a/app/service.go+++ b/app/infra/service.go@@ -1,4 +1,4 @@-package app+package infra// HealthCheckService is a simple general purpose health check servicetype HealthCheckService interface {diff --git a/app/mock/server.go b/app/mock/server.goindex 272718dc8..2d767b385 100644--- a/app/mock/server.go+++ b/app/mock/server.go@@ -36,9 +36,16 @@ func NewServer() *Server {}}+// NewContext creates a new HTTP context+func (s *Server) NewContext(req *http.Request, w http.ResponseWriter) app.Context {+ c := s.engine.NewContext(req, w)+ return app.Context{Context: c}+}+// Execute given handler and return response as JSON-func (s *Server) Execute(handler echo.HandlerFunc) (int, *jsonq.JsonQuery) {- handler(s.Context)+func (s *Server) Execute(handler app.HandlerFunc) (int, *jsonq.JsonQuery) {+ ctx := app.Context{Context: s.Context}+ handler(ctx)if s.recorder.Code == 200 && hasJSON(s.recorder) {var data interface{}@@ -52,8 +59,10 @@ func (s *Server) Execute(handler echo.HandlerFunc) (int, *jsonq.JsonQuery) {}// ExecuteRaw executes given handler and return raw response-func (s *Server) ExecuteRaw(handler echo.HandlerFunc) (int, *http.Response) {- handler(s.Context)+func (s *Server) ExecuteRaw(handler app.HandlerFunc) (int, *http.Response) {+ ctx := app.Context{Context: s.Context}+ handler(ctx)+return s.recorder.Code, s.recorder.Result()}diff --git a/app/identity/model.go b/app/model.gosimilarity index 67%rename from app/identity/model.gorename to app/model.goindex f97b5d21b..e795c0075 100644--- a/app/identity/model.go+++ b/app/model.go@@ -1,4 +1,6 @@-package identity+package app++import jwt "github.com/dgrijalva/jwt-go"//Tenant represents a tenanttype Tenant struct {@@ -20,3 +22,11 @@ type UserProvider struct {Name string `json:"name"`UID string `json:"uid"`}++//WechyClaims represents what goes into JWT tokens+type WechyClaims struct {+ UserID int64 `json:"user/id"`+ UserName string `json:"user/name"`+ UserEmail string `json:"user/email"`+ jwt.StandardClaims+}diff --git a/app/postgres/feedback.go b/app/postgres/feedback.goindex b2e8837e2..5963472d9 100644--- a/app/postgres/feedback.go+++ b/app/postgres/feedback.go@@ -5,8 +5,8 @@ import ("time"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/feedback"- "github.com/WeCanHearYou/wechy/app/identity")// IdeaService contains read and write operations for ideas@@ -54,7 +54,7 @@ func (svc IdeaService) GetByID(tenantID, ideaID int64) (*feedback.Idea, error) {rows.Scan(&idea.ID, &idea.Title, &idea.Description, &idea.CreatedOn, &idea.User.ID, &idea.User.Name, &idea.User.Email)return idea, nil}- return nil, identity.ErrNotFound+ return nil, app.ErrNotFound}// GetCommentsByIdeaID returns all coments from given ideadiff --git a/app/postgres/feedback_test.go b/app/postgres/feedback_test.goindex 5147ae23a..d627c2068 100644--- a/app/postgres/feedback_test.go+++ b/app/postgres/feedback_test.go@@ -7,8 +7,8 @@ import (sqlmock "gopkg.in/DATA-DOG/go-sqlmock.v1"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/feedback"- "github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/postgres". "github.com/onsi/gomega")@@ -50,7 +50,7 @@ func TestIdeaService_GetAll(t *testing.T) {Title: "Idea #1",Description: "Description #1",CreatedOn: now,- User: identity.User{+ User: app.User{ID: 1,Name: "Jon Snow",Email: "[email protected]",@@ -61,7 +61,7 @@ func TestIdeaService_GetAll(t *testing.T) {Title: "Idea #2",Description: "Description #2",CreatedOn: now,- User: identity.User{+ User: app.User{ID: 2,Name: "Arya Start",Email: "[email protected]",diff --git a/app/postgres/identity.go b/app/postgres/identity.goindex 5d76dac36..206704666 100644--- a/app/postgres/identity.go+++ b/app/postgres/identity.go@@ -5,7 +5,7 @@ import ("strings""time"- "github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/toolbox/env")@@ -15,19 +15,19 @@ type UserService struct {}// GetByEmail returns a user based on given email-func (svc UserService) GetByEmail(email string) (*identity.User, error) {- user := &identity.User{}+func (svc UserService) GetByEmail(email string) (*app.User, error) {+ user := &app.User{}row := svc.DB.QueryRow("SELECT id, name, email FROM users WHERE email = $1", email)if err := row.Scan(&user.ID, &user.Name, &user.Email); err != nil {- return nil, identity.ErrNotFound+ return nil, app.ErrNotFound}return user, nil}// Register creates a new user based on given information-func (svc UserService) Register(user *identity.User) error {+func (svc UserService) Register(user *app.User) error {tx, err := svc.DB.Begin()if err != nil {return err@@ -54,13 +54,13 @@ type TenantService struct {}// GetByDomain returns a tenant based on its domain-func (svc TenantService) GetByDomain(domain string) (*identity.Tenant, error) {- tenant := &identity.Tenant{}+func (svc TenantService) GetByDomain(domain string) (*app.Tenant, error) {+ tenant := &app.Tenant{}row := svc.DB.QueryRow("SELECT id, name, subdomain FROM tenants WHERE subdomain = $1 OR cname = $2", extractSubdomain(domain), domain)err := row.Scan(&tenant.ID, &tenant.Name, &tenant.Domain)if err != nil {- return nil, identity.ErrNotFound+ return nil, app.ErrNotFound}tenant.Domain = tenant.Domain + "." + env.GetCurrentDomain()diff --git a/app/postgres/identity_test.go b/app/postgres/identity_test.goindex 2e5f6cc27..0535fd83b 100644--- a/app/postgres/identity_test.go+++ b/app/postgres/identity_test.go@@ -7,6 +7,7 @@ import (sqlmock "gopkg.in/DATA-DOG/go-sqlmock.v1"+ "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/postgres". "github.com/onsi/gomega"@@ -68,10 +69,10 @@ func TestUserService_Register(t *testing.T) {mock.ExpectCommit()svc := &postgres.UserService{DB: db}- user := &identity.User{+ user := &app.User{Name: "Jon Snow",Email: "[email protected]",- Providers: []*identity.UserProvider{+ Providers: []*app.UserProvider{{UID: "123123123",Name: identity.OAuthFacebookProvider,@@ -107,10 +108,10 @@ func TestUserService_Register_MultipleProviders(t *testing.T) {mock.ExpectCommit()svc := &postgres.UserService{DB: db}- user := &identity.User{+ user := &app.User{Name: "Jon Snow",Email: "[email protected]",- Providers: []*identity.UserProvider{+ Providers: []*app.UserProvider{{UID: "123123123",Name: identity.OAuthFacebookProvider,diff --git a/app/postgres/app.go b/app/postgres/infra.gosimilarity index 100%rename from app/postgres/app.gorename to app/postgres/infra.godiff --git a/app/postgres/app_test.go b/app/postgres/infra_test.gosimilarity index 100%rename from app/postgres/app_test.gorename to app/postgres/infra_test.godiff --git a/app/renderer.go b/app/renderer.goindex 01e50918f..6f90bae47 100644--- a/app/renderer.go+++ b/app/renderer.go@@ -9,7 +9,6 @@ import ("io/ioutil"- "github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/toolbox/env""github.com/labstack/echo")@@ -54,6 +53,7 @@ func (r *HTMLRenderer) add(name string) *template.Template {//Render a template based on parametersfunc (r *HTMLRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {+ ctx := Context{Context: c}tmpl, ok := r.templates[name]if !ok {panic(fmt.Errorf("The template '%s' does not exist", name))@@ -66,10 +66,11 @@ func (r *HTMLRenderer) Render(w io.Writer, name string, data interface{}, c echo//TODO: refactor (and move somewhere else?)m := data.(echo.Map)m["AuthEndpoint"] = os.Getenv("AUTH_ENDPOINT")+ m["Tenant"] = ctx.Tenant()- claims, ok := c.Get("Claims").(*identity.WechyClaims)- if ok {- m["User"] = &identity.User{+ if ctx.IsAuthenticated() {+ claims := ctx.Claims()+ m["User"] = &User{ID: claims.UserID,Name: claims.UserName,Email: claims.UserEmail,diff --git a/app/router.go b/app/router.godeleted file mode 100644index 04aab70e3..000000000--- a/app/router.go+++ /dev/null@@ -1,90 +0,0 @@-package app--import (- "net/http"-- "strings"-- "github.com/WeCanHearYou/wechy/app/feedback"- "github.com/WeCanHearYou/wechy/app/identity"- "github.com/WeCanHearYou/wechy/app/toolbox/env"- "github.com/labstack/echo"- "github.com/labstack/gommon/log"-)--// WechySettings is an application-wide settings-type WechySettings struct {- BuildTime string- Version string- AuthEndpoint string-}--// WechyServices holds reference to all Wechy services-type WechyServices struct {- OAuth identity.OAuthService- User identity.UserService- Tenant identity.TenantService- Idea feedback.IdeaService- Health HealthCheckService- Settings *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-}--// GetMainEngine returns main HTTP engine-func GetMainEngine(ctx *WechyServices) *echo.Echo {- router := echo.New()-- router.Logger = createLogger()- router.Renderer = NewHTMLRenderer(router.Logger)- router.HTTPErrorHandler = errorHandler-- router.Static("/favicon.ico", "favicon.ico")- router.Static("/assets", "dist")-- authGroup := router.Group("", identity.HostChecker(env.MustGet("AUTH_ENDPOINT")))- {- authGroup.GET("/oauth/facebook", identity.OAuth(ctx.OAuth, ctx.User).Login(identity.OAuthFacebookProvider))- authGroup.GET("/oauth/facebook/callback", identity.OAuth(ctx.OAuth, ctx.User).Callback(identity.OAuthFacebookProvider))- authGroup.GET("/oauth/google", identity.OAuth(ctx.OAuth, ctx.User).Login(identity.OAuthGoogleProvider))- authGroup.GET("/oauth/google/callback", identity.OAuth(ctx.OAuth, ctx.User).Callback(identity.OAuthGoogleProvider))- }-- appGroup := router.Group("")- {- appGroup.Use(identity.JwtGetter())- appGroup.Use(identity.JwtSetter())- appGroup.Use(identity.MultiTenant(ctx.Tenant))-- appGroup.GET("/", feedback.Index(ctx.Idea).List())- appGroup.GET("/ideas/:id", feedback.Index(ctx.Idea).Details())- appGroup.GET("/logout", identity.OAuth(ctx.OAuth, ctx.User).Logout())-- appGroup.GET("/api/status", Status(ctx.Health, ctx.Settings))- appGroup.POST("/api/ideas", feedback.Index(ctx.Idea).Post())- appGroup.POST("/api/ideas/:id/comments", feedback.Index(ctx.Idea).PostComment())- }-- return router-}diff --git a/main.go b/main.goindex 2de66591f..269dd24b3 100644--- a/main.go+++ b/main.go@@ -3,8 +3,8 @@ package mainimport ("database/sql"- "github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app/infra""github.com/WeCanHearYou/wechy/app/postgres""github.com/WeCanHearYou/wechy/app/toolbox/env"_ "github.com/lib/pq"@@ -46,19 +46,19 @@ func main() {panic(err)}- ctx := &app.WechyServices{+ ctx := &WechyServices{OAuth: &identity.HTTPOAuthService{},Health: &postgres.HealthCheckService{DB: db},Idea: &postgres.IdeaService{DB: db},User: &postgres.UserService{DB: db},Tenant: &postgres.TenantService{DB: db},- Settings: &app.WechySettings{+ Settings: &infra.WechySettings{BuildTime: buildtime,Version: version,AuthEndpoint: env.MustGet("AUTH_ENDPOINT"),},}- e := app.GetMainEngine(ctx)+ e := GetMainEngine(ctx)e.Logger.Fatal(e.Start(":" + env.GetEnvOrDefault("PORT", "3000")))}diff --git a/router.go b/router.gonew file mode 100644index 000000000..c1cf62923--- /dev/null+++ b/router.go@@ -0,0 +1,121 @@+package main++import (+ "net/http"++ "strings"++ "github.com/WeCanHearYou/wechy/app"+ "github.com/WeCanHearYou/wechy/app/feedback"+ "github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app/infra"+ "github.com/WeCanHearYou/wechy/app/toolbox/env"+ "github.com/labstack/echo"+ "github.com/labstack/gommon/log"+)++// WechyServices holds reference to all Wechy services+type WechyServices struct {+ OAuth identity.OAuthService+ User identity.UserService+ Tenant identity.TenantService+ Idea feedback.IdeaService+ Health infra.HealthCheckService+ Settings *infra.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 app.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ ctx := app.Context{Context: c}+ return handler(ctx)+ }+}++func wrapMiddleware(mw app.MiddlewareFunc) echo.MiddlewareFunc {+ return func(h echo.HandlerFunc) echo.HandlerFunc {+ return wrapFunc(mw(func(c app.Context) error {+ return h(c)+ }))+ }+}++func get(group *echo.Group, path string, handler app.HandlerFunc) {+ group.GET(path, wrapFunc(handler))+}++func post(group *echo.Group, path string, handler app.HandlerFunc) {+ group.POST(path, wrapFunc(handler))+}++func use(group *echo.Group, mw app.MiddlewareFunc) {+ group.Use(wrapMiddleware(mw))+}++func group(router *echo.Echo, name string, middlewares ...app.MiddlewareFunc) *echo.Group {+ var mw []echo.MiddlewareFunc+ for _, m := range middlewares {+ mw = append(mw, wrapMiddleware(m))+ }+ return router.Group(name, mw...)+}++// GetMainEngine returns main HTTP engine+func GetMainEngine(ctx *WechyServices) *echo.Echo {+ router := echo.New()++ router.Logger = createLogger()+ router.Renderer = app.NewHTMLRenderer(router.Logger)+ router.HTTPErrorHandler = errorHandler++ router.Static("/favicon.ico", "favicon.ico")+ router.Static("/assets", "dist")++ hostChecker := identity.HostChecker(env.MustGet("AUTH_ENDPOINT"))+ authGroup := group(router, "", hostChecker)+ {+ get(authGroup, "/oauth/facebook", identity.OAuth(ctx.OAuth, ctx.User).Login(identity.OAuthFacebookProvider))+ get(authGroup, "/oauth/facebook/callback", identity.OAuth(ctx.OAuth, ctx.User).Callback(identity.OAuthFacebookProvider))+ get(authGroup, "/oauth/google", identity.OAuth(ctx.OAuth, ctx.User).Login(identity.OAuthGoogleProvider))+ get(authGroup, "/oauth/google/callback", identity.OAuth(ctx.OAuth, ctx.User).Callback(identity.OAuthGoogleProvider))+ }++ appGroup := group(router, "")+ {+ use(appGroup, identity.JwtGetter())+ use(appGroup, identity.JwtSetter())+ use(appGroup, identity.MultiTenant(ctx.Tenant))++ get(appGroup, "/", feedback.Index(ctx.Idea).List())+ get(appGroup, "/ideas/:id", feedback.Index(ctx.Idea).Details())+ get(appGroup, "/logout", identity.OAuth(ctx.OAuth, ctx.User).Logout())++ get(appGroup, "/api/status", infra.Status(ctx.Health, ctx.Settings))+ post(appGroup, "/api/ideas", feedback.Index(ctx.Idea).Post())+ post(appGroup, "/api/ideas/:id/comments", feedback.Index(ctx.Idea).PostComment())+ }++ return router+}diff --git a/app/router_test.go b/router_test.gosimilarity index 54%rename from app/router_test.gorename to router_test.goindex 6772b1e75..eebc26592 100644--- a/app/router_test.go+++ b/router_test.go@@ -1,16 +1,15 @@-package app_test+package mainimport ("testing"- "github.com/WeCanHearYou/wechy/app". "github.com/onsi/gomega")func TestRouter(t *testing.T) {RegisterTestingT(t)- ctx := &app.WechyServices{}- r := app.GetMainEngine(ctx)+ ctx := &WechyServices{}+ r := GetMainEngine(ctx)Expect(r).ToNot(BeNil())}