Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

removed tenant from jwt token

goenningf696110c88df
diff --git a/app/identity/handler.go b/app/identity/handler.go
index 7ab6c220a..9987649e8 100644
--- a/app/identity/handler.go
+++ b/app/identity/handler.go
@@ -89,7 +89,6 @@ func (h OAuthHandlers) Callback(provider string) app.HandlerFunc {
UserID: user.ID,
UserName: user.Name,
UserEmail: user.Email,
- TenantID: tenant.ID,
}
var token string
diff --git a/app/identity/handler_test.go b/app/identity/handler_test.go
index d5e657564..956c8d396 100644
--- a/app/identity/handler_test.go
+++ b/app/identity/handler_test.go
@@ -7,10 +7,8 @@ import (
"net/url"
- "github.com/WeCanHearYou/wechy/app/dbx"
"github.com/WeCanHearYou/wechy/app/identity"
"github.com/WeCanHearYou/wechy/app/mock"
- "github.com/WeCanHearYou/wechy/app/postgres"
. "github.com/onsi/gomega"
)
@@ -51,15 +49,9 @@ func (p OAuthService) GetProfile(provider string, code string) (*identity.OAuthU
return nil, nil
}
-var db *dbx.Database
-
func handlers() identity.OAuthHandlers {
- db, _ = dbx.New()
-
- oauth := &OAuthService{}
- tenant := &postgres.TenantService{DB: db}
- user := &postgres.UserService{DB: db}
- return identity.OAuth(tenant, oauth, user)
+ setup()
+ return identity.OAuth(tenantService, oauthService, userService)
}
func TestLoginHandler(t *testing.T) {
@@ -103,7 +95,7 @@ func TestCallbackHandler_ExistingUserAndProvider(t *testing.T) {
Expect(db.Count("SELECT id FROM users WHERE email = '[email protected]'")).To(Equal(1))
Expect(code).To(Equal(http.StatusTemporaryRedirect))
- Expect(response.Header.Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20iLCJ0ZW5hbnQvaWQiOjMwMH0.0sbeKMVxJ5zjm2SIS7UotDi1rsFgpEpTEe20Z3t7aNE"))
+ Expect(response.Header.Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20ifQ.6_dLZrulH37ymBtqy-l7bhCti9hBv0lgEhH8tLm07CI"))
}
func TestCallbackHandler_NewUser(t *testing.T) {
@@ -117,7 +109,7 @@ func TestCallbackHandler_NewUser(t *testing.T) {
Expect(db.Exists("SELECT * FROM user_providers WHERE provider_uid = 'FB5678'")).To(BeTrue())
Expect(code).To(Equal(http.StatusTemporaryRedirect))
- Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiJzb21lLmd1eUBmYWNlYm9vay5jb20iLCJ0ZW5hbnQvaWQiOjQwMH0.iWkpvh11QrUDJQnTk9PtqW6m48DnaHbsj-lbl6feK-Q"))
+ Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiJzb21lLmd1eUBmYWNlYm9vay5jb20ifQ.PGavs5a6HRotRozfXfNP39JPb0vSus_8LL9MAOeLGDs"))
}
func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
@@ -132,5 +124,5 @@ func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
Expect(db.QueryString("SELECT provider_uid FROM user_providers WHERE user_id = 300 and provider = 'google'")).To(Equal("GO1234"))
Expect(code).To(Equal(http.StatusTemporaryRedirect))
- Expect(response.Header.Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20iLCJ0ZW5hbnQvaWQiOjMwMH0.0sbeKMVxJ5zjm2SIS7UotDi1rsFgpEpTEe20Z3t7aNE"))
+ Expect(response.Header.Get("Location")).To(Equal("http://demo.test.canhearyou.com?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozMDAsInVzZXIvbmFtZSI6IkpvbiBTbm93IiwidXNlci9lbWFpbCI6Impvbi5zbm93QGdvdC5jb20ifQ.6_dLZrulH37ymBtqy-l7bhCti9hBv0lgEhH8tLm07CI"))
}
diff --git a/app/identity/middleware.go b/app/identity/middleware.go
index 77aeaf880..59d169b50 100644
--- a/app/identity/middleware.go
+++ b/app/identity/middleware.go
@@ -4,6 +4,7 @@ import (
"net/http"
"github.com/WeCanHearYou/wechy/app"
+ "github.com/WeCanHearYou/wechy/app/infra"
)
// MultiTenant extract tenant information from hostname and inject it into current context
@@ -22,3 +23,62 @@ func MultiTenant(tenantService TenantService) app.MiddlewareFunc {
}
}
}
+
+// JwtGetter gets JWT token from cookie and add into context
+func JwtGetter(userService UserService) 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 := infra.Decode(cookie.Value); err == nil {
+ if user, err := userService.GetByID(claims.UserID); err == nil {
+ if user.Tenant.ID == c.Tenant().ID {
+ c.SetClaims(claims)
+ }
+ }
+ } else {
+ c.Logger().Error(err)
+ }
+ }
+
+ return next(c)
+ }
+ }
+}
+
+// JwtSetter sets JWT token into cookie
+func JwtSetter() app.MiddlewareFunc {
+ return func(next app.HandlerFunc) app.HandlerFunc {
+ return func(c app.Context) error {
+
+ query := c.Request().URL.Query()
+
+ jwt := query.Get("jwt")
+ if jwt != "" {
+ c.SetCookie(&http.Cookie{
+ Name: "auth",
+ Value: jwt,
+ HttpOnly: true,
+ Path: "/",
+ })
+
+ scheme := "http"
+ if c.Request().TLS != nil {
+ scheme = "https"
+ }
+
+ query.Del("jwt")
+
+ url := scheme + "://" + c.Request().Host + c.Request().URL.Path
+ querystring := query.Encode()
+ if querystring != "" {
+ url += "?" + querystring
+ }
+
+ return c.Redirect(http.StatusTemporaryRedirect, url)
+ }
+
+ return next(c)
+ }
+ }
+}
diff --git a/app/identity/middleware_test.go b/app/identity/middleware_test.go
index 3b2be0a08..abcd35eac 100644
--- a/app/identity/middleware_test.go
+++ b/app/identity/middleware_test.go
@@ -7,6 +7,7 @@ import (
"github.com/WeCanHearYou/wechy/app"
"github.com/WeCanHearYou/wechy/app/identity"
+ "github.com/WeCanHearYou/wechy/app/infra"
"github.com/WeCanHearYou/wechy/app/mock"
"github.com/labstack/echo"
. "github.com/onsi/gomega"
@@ -86,3 +87,143 @@ func TestMultiTenant_UnknownDomain(t *testing.T) {
Expect(rec.Code).To(Equal(404))
}
+
+func TestJwtGetter_NoCookie(t *testing.T) {
+ RegisterTestingT(t)
+ setup()
+
+ server := mock.NewServer()
+ req, _ := http.NewRequest(echo.GET, "/", nil)
+ rec := httptest.NewRecorder()
+ c := server.NewContext(req, rec)
+
+ mw := identity.JwtGetter(userService)
+ mw(func(c app.Context) error {
+ if c.IsAuthenticated() {
+ return c.NoContent(http.StatusOK)
+ } else {
+ return c.NoContent(http.StatusNoContent)
+ }
+ })(c)
+
+ Expect(rec.Code).To(Equal(http.StatusNoContent))
+}
+
+func TestJwtGetter_WithCookie(t *testing.T) {
+ RegisterTestingT(t)
+ setup()
+
+ token, _ := infra.Encode(&app.WechyClaims{
+ UserID: 300,
+ UserName: "Jon Snow",
+ })
+
+ server := mock.NewServer()
+ req, _ := http.NewRequest(echo.GET, "/", nil)
+ rec := httptest.NewRecorder()
+ c := server.NewContext(req, rec)
+ c.SetTenant(&app.Tenant{ID: 300})
+ c.Request().AddCookie(&http.Cookie{
+ Name: "auth",
+ Value: token,
+ })
+
+ mw := identity.JwtGetter(userService)
+ 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"))
+}
+
+func TestJwtGetter_WithCookie_DifferentTenant(t *testing.T) {
+ RegisterTestingT(t)
+ setup()
+
+ token, _ := infra.Encode(&app.WechyClaims{
+ UserID: 300,
+ UserName: "Jon Snow",
+ })
+
+ server := mock.NewServer()
+ req, _ := http.NewRequest(echo.GET, "/", nil)
+ rec := httptest.NewRecorder()
+ c := server.NewContext(req, rec)
+ c.SetTenant(&app.Tenant{ID: 400})
+ c.Request().AddCookie(&http.Cookie{
+ Name: "auth",
+ Value: token,
+ })
+
+ mw := identity.JwtGetter(userService)
+ mw(func(c app.Context) error {
+ if c.Claims() == nil {
+ return c.NoContent(http.StatusNoContent)
+ }
+ return c.NoContent(http.StatusOK)
+ })(c)
+
+ Expect(rec.Code).To(Equal(http.StatusNoContent))
+}
+
+func TestJwtSetter_WithoutJwt(t *testing.T) {
+ RegisterTestingT(t)
+
+ server := mock.NewServer()
+ req, _ := http.NewRequest(echo.GET, "/abc", nil)
+ rec := httptest.NewRecorder()
+ c := server.NewContext(req, rec)
+ c.Request().Host = "orange.test.canhearyou.com"
+
+ mw := identity.JwtSetter()
+ mw(func(c app.Context) error {
+ return c.NoContent(http.StatusOK)
+ })(c)
+
+ Expect(rec.Code).To(Equal(http.StatusOK))
+}
+
+func TestJwtSetter_WithJwt_WithoutParameter(t *testing.T) {
+ RegisterTestingT(t)
+
+ token, _ := infra.Encode(&app.WechyClaims{
+ UserName: "Jon Snow",
+ })
+
+ server := mock.NewServer()
+ req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token, nil)
+ rec := httptest.NewRecorder()
+ c := server.NewContext(req, rec)
+ c.Request().Host = "orange.test.canhearyou.com"
+
+ mw := identity.JwtSetter()
+ mw(func(c app.Context) error {
+ return c.NoContent(http.StatusOK)
+ })(c)
+
+ Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc"))
+}
+
+func TestJwtSetter_WithJwt_WithParameter(t *testing.T) {
+ RegisterTestingT(t)
+
+ token, _ := infra.Encode(&app.WechyClaims{
+ UserName: "Jon Snow",
+ })
+
+ server := mock.NewServer()
+ req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token+"&foo=bar", nil)
+ rec := httptest.NewRecorder()
+ c := server.NewContext(req, rec)
+ c.Request().Host = "orange.test.canhearyou.com"
+
+ mw := identity.JwtSetter()
+ mw(func(c app.Context) error {
+ return c.NoContent(http.StatusOK)
+ })(c)
+
+ Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc?foo=bar"))
+}
diff --git a/app/identity/service.go b/app/identity/service.go
index 1acba5a96..f63930a52 100644
--- a/app/identity/service.go
+++ b/app/identity/service.go
@@ -4,6 +4,7 @@ import "github.com/WeCanHearYou/wechy/app"
// UserService is used for user operations
type UserService interface {
+ GetByID(userID int) (*app.User, error)
GetByEmail(tenantID int, email string) (*app.User, error)
Register(user *app.User) error
RegisterProvider(userID int, provider *app.UserProvider) error
diff --git a/app/identity/setup_test.go b/app/identity/setup_test.go
new file mode 100644
index 000000000..e3c7f9c47
--- /dev/null
+++ b/app/identity/setup_test.go
@@ -0,0 +1,21 @@
+package identity_test
+
+import (
+ "github.com/WeCanHearYou/wechy/app/dbx"
+ "github.com/WeCanHearYou/wechy/app/postgres"
+)
+
+var (
+ db *dbx.Database
+ oauthService *OAuthService
+ tenantService *postgres.TenantService
+ userService *postgres.UserService
+)
+
+func setup() {
+ db, _ = dbx.New()
+
+ oauthService = &OAuthService{}
+ tenantService = &postgres.TenantService{DB: db}
+ userService = &postgres.UserService{DB: db}
+}
diff --git a/app/infra/jwt_test.go b/app/infra/jwt_test.go
index 0a95656a6..9c06fd406 100644
--- a/app/infra/jwt_test.go
+++ b/app/infra/jwt_test.go
@@ -29,7 +29,6 @@ func TestJWT_Decode(t *testing.T) {
UserID: 424,
UserName: "Jon Snow",
UserEmail: "[email protected]",
- TenantID: 2,
}
token, _ := infra.Encode(claims)
@@ -39,5 +38,4 @@ func TestJWT_Decode(t *testing.T) {
Expect(decoded.UserID).To(Equal(claims.UserID))
Expect(decoded.UserName).To(Equal(claims.UserName))
Expect(decoded.UserEmail).To(Equal(claims.UserEmail))
- Expect(decoded.TenantID).To(Equal(claims.TenantID))
}
diff --git a/app/infra/middleware.go b/app/infra/middleware.go
index 77d64f04d..63d7a7dbb 100644
--- a/app/infra/middleware.go
+++ b/app/infra/middleware.go
@@ -11,8 +11,7 @@ import (
func IsAuthenticated() app.MiddlewareFunc {
return func(next app.HandlerFunc) app.HandlerFunc {
return func(c app.Context) error {
- claims := c.Claims()
- if claims == nil {
+ if c.Claims() == nil {
return c.NoContent(http.StatusForbidden)
}
return next(c)
@@ -20,63 +19,6 @@ func IsAuthenticated() app.MiddlewareFunc {
}
}
-// JwtGetter gets JWT token from cookie and add into context
-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 {
- if claims.TenantID == c.Tenant().ID {
- c.SetClaims(claims)
- }
- } else {
- c.Logger().Error(err)
- }
- }
-
- return next(c)
- }
- }
-}
-
-// JwtSetter sets JWT token into cookie
-func JwtSetter() app.MiddlewareFunc {
- return func(next app.HandlerFunc) app.HandlerFunc {
- return func(c app.Context) error {
-
- query := c.Request().URL.Query()
-
- jwt := query.Get("jwt")
- if jwt != "" {
- c.SetCookie(&http.Cookie{
- Name: "auth",
- Value: jwt,
- HttpOnly: true,
- Path: "/",
- })
-
- scheme := "http"
- if c.Request().TLS != nil {
- scheme = "https"
- }
-
- query.Del("jwt")
-
- url := scheme + "://" + c.Request().Host + c.Request().URL.Path
- querystring := query.Encode()
- if querystring != "" {
- url += "?" + querystring
- }
-
- return c.Redirect(http.StatusTemporaryRedirect, url)
- }
-
- return next(c)
- }
- }
-}
-
// HostChecker checks for a specific host
func HostChecker(baseURL string) app.MiddlewareFunc {
return func(next app.HandlerFunc) app.HandlerFunc {
diff --git a/app/infra/middleware_test.go b/app/infra/middleware_test.go
index 255e17fb1..9f1be8895 100644
--- a/app/infra/middleware_test.go
+++ b/app/infra/middleware_test.go
@@ -47,143 +47,6 @@ func TestIsAuthenticated_WithoutClaims(t *testing.T) {
Expect(rec.Code).To(Equal(http.StatusForbidden))
}
-func TestJwtGetter_NoCookie(t *testing.T) {
- RegisterTestingT(t)
-
- server := mock.NewServer()
- req, _ := http.NewRequest(echo.GET, "/", nil)
- rec := httptest.NewRecorder()
- c := server.NewContext(req, rec)
-
- mw := infra.JwtGetter()
- mw(func(c app.Context) error {
- if c.IsAuthenticated() {
- return c.NoContent(http.StatusOK)
- } else {
- return c.NoContent(http.StatusNoContent)
- }
- })(c)
-
- Expect(rec.Code).To(Equal(http.StatusNoContent))
-}
-
-func TestJwtGetter_WithCookie(t *testing.T) {
- RegisterTestingT(t)
-
- token, _ := infra.Encode(&app.WechyClaims{
- UserName: "Jon Snow",
- TenantID: 2,
- })
-
- server := mock.NewServer()
- req, _ := http.NewRequest(echo.GET, "/", nil)
- rec := httptest.NewRecorder()
- c := server.NewContext(req, rec)
- c.SetTenant(&app.Tenant{ID: 2})
- c.Request().AddCookie(&http.Cookie{
- Name: "auth",
- Value: token,
- })
-
- mw := infra.JwtGetter()
- 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"))
-}
-
-func TestJwtGetter_WithCookie_DifferentTenant(t *testing.T) {
- RegisterTestingT(t)
-
- token, _ := infra.Encode(&app.WechyClaims{
- UserName: "Jon Snow",
- TenantID: 3,
- })
-
- server := mock.NewServer()
- req, _ := http.NewRequest(echo.GET, "/", nil)
- rec := httptest.NewRecorder()
- c := server.NewContext(req, rec)
- c.SetTenant(&app.Tenant{ID: 2})
- c.Request().AddCookie(&http.Cookie{
- Name: "auth",
- Value: token,
- })
-
- mw := infra.JwtGetter()
- mw(func(c app.Context) error {
- if c.Claims() == nil {
- return c.NoContent(http.StatusNoContent)
- }
- return c.NoContent(http.StatusOK)
- })(c)
-
- Expect(rec.Code).To(Equal(http.StatusNoContent))
-}
-
-func TestJwtSetter_WithoutJwt(t *testing.T) {
- RegisterTestingT(t)
-
- server := mock.NewServer()
- req, _ := http.NewRequest(echo.GET, "/abc", nil)
- rec := httptest.NewRecorder()
- c := server.NewContext(req, rec)
- c.Request().Host = "orange.test.canhearyou.com"
-
- mw := infra.JwtSetter()
- mw(func(c app.Context) error {
- return c.NoContent(http.StatusOK)
- })(c)
-
- Expect(rec.Code).To(Equal(http.StatusOK))
-}
-
-func TestJwtSetter_WithJwt_WithoutParameter(t *testing.T) {
- RegisterTestingT(t)
-
- token, _ := infra.Encode(&app.WechyClaims{
- UserName: "Jon Snow",
- })
-
- server := mock.NewServer()
- req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token, nil)
- rec := httptest.NewRecorder()
- c := server.NewContext(req, rec)
- c.Request().Host = "orange.test.canhearyou.com"
-
- mw := infra.JwtSetter()
- mw(func(c app.Context) error {
- return c.NoContent(http.StatusOK)
- })(c)
-
- Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))
- Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc"))
-}
-
-func TestJwtSetter_WithJwt_WithParameter(t *testing.T) {
- RegisterTestingT(t)
-
- token, _ := infra.Encode(&app.WechyClaims{
- UserName: "Jon Snow",
- })
-
- server := mock.NewServer()
- req, _ := http.NewRequest(echo.GET, "/abc?jwt="+token+"&foo=bar", nil)
- rec := httptest.NewRecorder()
- c := server.NewContext(req, rec)
- c.Request().Host = "orange.test.canhearyou.com"
-
- mw := infra.JwtSetter()
- mw(func(c app.Context) error {
- return c.NoContent(http.StatusOK)
- })(c)
-
- Expect(rec.Code).To(Equal(http.StatusTemporaryRedirect))
- Expect(rec.Header().Get("Location")).To(Equal("http://orange.test.canhearyou.com/abc?foo=bar"))
-}
-
func TestHostChecker(t *testing.T) {
RegisterTestingT(t)
diff --git a/app/model.go b/app/model.go
index 322a5714e..48142fdee 100644
--- a/app/model.go
+++ b/app/model.go
@@ -19,7 +19,7 @@ type User struct {
}
//HasProvider returns true if current user has given provider registered
-func (u User) HasProvider(provider string) bool {
+func (u *User) HasProvider(provider string) bool {
for _, p := range u.Providers {
if p.Name == provider {
return true
@@ -39,6 +39,5 @@ type WechyClaims struct {
UserID int `json:"user/id"`
UserName string `json:"user/name"`
UserEmail string `json:"user/email"`
- TenantID int `json:"tenant/id"`
jwt.StandardClaims
}
diff --git a/app/postgres/feedback.go b/app/postgres/feedback.go
index 35c4c0664..25c3d1b4b 100644
--- a/app/postgres/feedback.go
+++ b/app/postgres/feedback.go
@@ -14,7 +14,7 @@ type IdeaService struct {
}
// GetAll returns all tenant ideas
-func (svc IdeaService) GetAll(tenantID int) ([]*feedback.Idea, error) {
+func (svc *IdeaService) GetAll(tenantID int) ([]*feedback.Idea, error) {
rows, err := svc.DB.Query(`SELECT i.id, i.number, i.title, i.description, i.created_on, u.id, u.name, u.email
FROM ideas i
INNER JOIN users u
@@ -37,7 +37,7 @@ func (svc IdeaService) GetAll(tenantID int) ([]*feedback.Idea, error) {
}
// GetByID returns idea by given id
-func (svc IdeaService) GetByID(tenantID, ideaID int) (*feedback.Idea, error) {
+func (svc *IdeaService) GetByID(tenantID, ideaID int) (*feedback.Idea, error) {
rows, err := svc.DB.Query(`SELECT i.id, i.number, i.title, i.description, i.created_on, u.id, u.name, u.email
FROM ideas i
INNER JOIN users u
@@ -59,7 +59,7 @@ func (svc IdeaService) GetByID(tenantID, ideaID int) (*feedback.Idea, error) {
}
// GetByNumber returns idea by tenant and number
-func (svc IdeaService) GetByNumber(tenantID, number int) (*feedback.Idea, error) {
+func (svc *IdeaService) GetByNumber(tenantID, number int) (*feedback.Idea, error) {
rows, err := svc.DB.Query(`SELECT i.id, i.number, i.title, i.description, i.created_on, u.id, u.name, u.email
FROM ideas i
INNER JOIN users u
@@ -81,7 +81,7 @@ func (svc IdeaService) GetByNumber(tenantID, number int) (*feedback.Idea, error)
}
// GetCommentsByIdeaID returns all coments from given idea
-func (svc IdeaService) GetCommentsByIdeaID(tenantID, ideaID int) ([]*feedback.Comment, error) {
+func (svc *IdeaService) GetCommentsByIdeaID(tenantID, ideaID int) ([]*feedback.Comment, error) {
rows, err := svc.DB.Query(`SELECT c.id, c.content, c.created_on, u.id, u.name, u.email
FROM comments c
INNER JOIN ideas i
@@ -107,7 +107,7 @@ func (svc IdeaService) GetCommentsByIdeaID(tenantID, ideaID int) ([]*feedback.Co
}
// Save a new idea in the database
-func (svc IdeaService) Save(tenantID, userID int, title, description string) (*feedback.Idea, error) {
+func (svc *IdeaService) Save(tenantID, userID int, title, description string) (*feedback.Idea, error) {
tx, err := svc.DB.Begin()
if err != nil {
return nil, err
@@ -129,7 +129,7 @@ func (svc IdeaService) Save(tenantID, userID int, title, description string) (*f
}
// AddComment places a new comment on an idea
-func (svc IdeaService) AddComment(userID, ideaID int, content string) (int, error) {
+func (svc *IdeaService) AddComment(userID, ideaID int, content string) (int, error) {
tx, err := svc.DB.Begin()
if err != nil {
return 0, err
diff --git a/app/postgres/identity.go b/app/postgres/identity.go
index 0f0d609c7..23f5c7ae7 100644
--- a/app/postgres/identity.go
+++ b/app/postgres/identity.go
@@ -14,12 +14,38 @@ type UserService struct {
DB *dbx.Database
}
+// GetByID returns a user based on given id
+func (svc *UserService) GetByID(userID int) (*app.User, error) {
+ user := &app.User{}
+ user.Tenant = &app.Tenant{}
+ row := svc.DB.QueryRow("SELECT id, name, email, tenant_id FROM users WHERE id = $1", userID)
+
+ if err := row.Scan(&user.ID, &user.Name, &user.Email, &user.Tenant.ID); err != nil {
+ return nil, app.ErrNotFound
+ }
+
+ rows, err := svc.DB.Query("SELECT provider_uid, provider FROM user_providers WHERE user_id = $1", user.ID)
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+ for rows.Next() {
+ p := &app.UserProvider{}
+ rows.Scan(&p.UID, &p.Name)
+ user.Providers = append(user.Providers, p)
+ }
+
+ return user, nil
+}
+
// GetByEmail returns a user based on given email
-func (svc UserService) GetByEmail(tenantID int, email string) (*app.User, error) {
+func (svc *UserService) GetByEmail(tenantID int, email string) (*app.User, error) {
user := &app.User{}
- row := svc.DB.QueryRow("SELECT id, name, email FROM users WHERE email = $1 AND tenant_id = $2", email, tenantID)
+ user.Tenant = &app.Tenant{}
+ row := svc.DB.QueryRow("SELECT id, name, email, tenant_id FROM users WHERE email = $1 AND tenant_id = $2", email, tenantID)
- if err := row.Scan(&user.ID, &user.Name, &user.Email); err != nil {
+ if err := row.Scan(&user.ID, &user.Name, &user.Email, &user.Tenant.ID); err != nil {
return nil, app.ErrNotFound
}
@@ -39,7 +65,7 @@ func (svc UserService) GetByEmail(tenantID int, email string) (*app.User, error)
}
// Register creates a new user based on given information
-func (svc UserService) Register(user *app.User) error {
+func (svc *UserService) Register(user *app.User) error {
tx, err := svc.DB.Begin()
if err != nil {
return err
@@ -63,7 +89,7 @@ func (svc UserService) Register(user *app.User) error {
}
// RegisterProvider adds given provider to userID
-func (svc UserService) RegisterProvider(userID int, provider *app.UserProvider) error {
+func (svc *UserService) RegisterProvider(userID int, provider *app.UserProvider) error {
now := time.Now()
return svc.DB.Execute("INSERT INTO user_providers (user_id, provider, provider_uid, created_on) VALUES ($1, $2, $3, $4)", userID, provider.Name, provider.UID, now)
}
@@ -74,7 +100,7 @@ type TenantService struct {
}
// GetByDomain returns a tenant based on its domain
-func (svc TenantService) GetByDomain(domain string) (*app.Tenant, error) {
+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)
diff --git a/app/postgres/identity_test.go b/app/postgres/identity_test.go
index 2458825af..e8786d960 100644
--- a/app/postgres/identity_test.go
+++ b/app/postgres/identity_test.go
@@ -10,6 +10,24 @@ import (
. "github.com/onsi/gomega"
)
+func TestUserService_GetByID(t *testing.T) {
+ RegisterTestingT(t)
+ db, _ := dbx.New()
+ defer db.Close()
+
+ svc := &postgres.UserService{DB: db}
+ user, err := svc.GetByID(300)
+
+ Expect(err).To(BeNil())
+ Expect(user.ID).To(Equal(int(300)))
+ Expect(user.Name).To(Equal("Jon Snow"))
+ Expect(user.Email).To(Equal("[email protected]"))
+ Expect(len(user.Providers)).To(Equal(1))
+ Expect(user.Providers[0].UID).To(Equal("FB1234"))
+ Expect(user.Providers[0].Name).To(Equal("facebook"))
+ Expect(user.Tenant.ID).To(Equal(300))
+}
+
func TestUserService_GetByEmail_Error(t *testing.T) {
RegisterTestingT(t)
db, _ := dbx.New()
@@ -37,6 +55,7 @@ func TestUserService_GetByEmail(t *testing.T) {
Expect(len(user.Providers)).To(Equal(1))
Expect(user.Providers[0].UID).To(Equal("FB1234"))
Expect(user.Providers[0].Name).To(Equal("facebook"))
+ Expect(user.Tenant.ID).To(Equal(300))
}
func TestUserService_GetByEmail_WrongTenant(t *testing.T) {
diff --git a/app/postgres/infra.go b/app/postgres/infra.go
index c7d3452d1..a5a44ce05 100644
--- a/app/postgres/infra.go
+++ b/app/postgres/infra.go
@@ -8,7 +8,7 @@ type HealthCheckService struct {
}
// IsDatabaseOnline checks if database is online
-func (svc HealthCheckService) IsDatabaseOnline() bool {
+func (svc *HealthCheckService) IsDatabaseOnline() bool {
rows, err := svc.DB.Query("SELECT now()")
if err != nil {
return false
diff --git a/router.go b/router.go
index 9a9c67dd3..4d3a20e16 100644
--- a/router.go
+++ b/router.go
@@ -110,8 +110,8 @@ func GetMainEngine(ctx *WechyServices) *echo.Echo {
appGroup := group(router, "")
{
use(appGroup, identity.MultiTenant(ctx.Tenant))
- use(appGroup, infra.JwtGetter())
- use(appGroup, infra.JwtSetter())
+ use(appGroup, identity.JwtGetter(ctx.User))
+ use(appGroup, identity.JwtSetter())
get(appGroup, "/", feedback.Handlers(ctx.Idea).List())
get(appGroup, "/ideas/:number", feedback.Handlers(ctx.Idea).Details())
@@ -122,8 +122,8 @@ func GetMainEngine(ctx *WechyServices) *echo.Echo {
securedGroup := group(router, "")
{
use(securedGroup, identity.MultiTenant(ctx.Tenant))
- use(securedGroup, infra.JwtGetter())
- use(securedGroup, infra.JwtSetter())
+ use(securedGroup, identity.JwtGetter(ctx.User))
+ use(securedGroup, identity.JwtSetter())
use(securedGroup, infra.IsAuthenticated())
post(securedGroup, "/api/ideas", feedback.Handlers(ctx.Idea).PostIdea())