Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactoring

Oenning8e9e150777df
diff --git a/.gitignore b/.gitignore
index ffd991d4d..81ede87b8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,4 +8,5 @@ wchy
wchy.exe
gin-bin
gin-bin.exe
+gin-bin.exe~
.env
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 2eedf5bff..f7240faea 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -8,10 +8,12 @@
"data": true,
"gin-bin": true,
"gin-bin.exe": true,
+ "gin-bin.exe~": true,
"wchy": true,
"wchy.exe": true,
"tmp": true,
- "vendor": true
+ "vendor": true,
+ "node_modules": true
},
"vsicons.presets.angular": true
}
\ No newline at end of file
diff --git a/auth/jwt.go b/auth/jwt.go
new file mode 100644
index 000000000..5d3770bc3
--- /dev/null
+++ b/auth/jwt.go
@@ -0,0 +1,37 @@
+package auth
+
+import (
+ "os"
+
+ jwt "github.com/dgrijalva/jwt-go"
+)
+
+//WchyClaims represents what goes into JWT tokens
+type WchyClaims struct {
+ UserID int64 `json:"user/id"`
+ UserName string `json:"user/name"`
+ UserEmail string `json:"user/email"`
+ jwt.StandardClaims
+}
+
+var jwtSecret = os.Getenv("JWT_SECRET")
+
+//Encode creates new JWT tokens with given claims
+func Encode(claims *WchyClaims) (string, error) {
+ jwtToken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
+ return jwtToken.SignedString([]byte(jwtSecret))
+}
+
+//Decode extract claims from JWT tokens
+func Decode(token string) (*WchyClaims, error) {
+ claims := &WchyClaims{}
+ jwtToken, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {
+ return []byte(jwtSecret), nil
+ })
+
+ if err == nil && jwtToken.Valid {
+ return claims, nil
+ }
+
+ return nil, err
+}
diff --git a/auth/jwt_test.go b/auth/jwt_test.go
new file mode 100644
index 000000000..2d55320d6
--- /dev/null
+++ b/auth/jwt_test.go
@@ -0,0 +1,40 @@
+package auth_test
+
+import (
+ "testing"
+
+ "github.com/WeCanHearYou/wchy/auth"
+ . "github.com/onsi/gomega"
+)
+
+func TestJWT_Encode(t *testing.T) {
+ RegisterTestingT(t)
+
+ claims := &auth.WchyClaims{
+ UserID: 424,
+ UserName: "Jon Snow",
+ UserEmail: "[email protected]",
+ }
+
+ token, err := auth.Encode(claims)
+ Expect(token).NotTo(BeNil())
+ Expect(err).To(BeNil())
+}
+
+func TestJWT_Decode(t *testing.T) {
+ RegisterTestingT(t)
+
+ claims := &auth.WchyClaims{
+ UserID: 424,
+ UserName: "Jon Snow",
+ UserEmail: "[email protected]",
+ }
+
+ token, _ := auth.Encode(claims)
+
+ decoded, err := auth.Decode(token)
+ Expect(err).To(BeNil())
+ Expect(decoded.UserID).To(Equal(claims.UserID))
+ Expect(decoded.UserName).To(Equal(claims.UserName))
+ Expect(decoded.UserEmail).To(Equal(claims.UserEmail))
+}
diff --git a/auth/service.go b/auth/service.go
index 84e122459..871af92d7 100644
--- a/auth/service.go
+++ b/auth/service.go
@@ -3,8 +3,6 @@ package auth
import (
"database/sql"
"errors"
-
- jwt "github.com/dgrijalva/jwt-go"
)
const (
@@ -22,14 +20,6 @@ type User struct {
Providers []*UserProvider
}
-//WchyClaims represents what goes into JWT tokens
-type WchyClaims struct {
- UserID int64 `json:"userid"`
- UserName string `json:"username"`
- UserEmail string `json:"useremail"`
- jwt.StandardClaims
-}
-
//UserProvider represents the relashionship between an User and an Authentication provide
type UserProvider struct {
Name string
diff --git a/handler/oauth.go b/handler/oauth.go
index e23d7542f..ad9e7006d 100644
--- a/handler/oauth.go
+++ b/handler/oauth.go
@@ -14,7 +14,6 @@ import (
"github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/context"
- jwt "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
)
@@ -31,7 +30,6 @@ type oauthProviderSettings struct {
var (
authEndpoint = os.Getenv("AUTH_ENDPOINT")
- jwtSecret = os.Getenv("JWT_SECRET")
oauthSettings = map[string]*oauthProviderSettings{
auth.OAuthFacebookProvider: &oauthProviderSettings{
profileURL: func(token *oauth2.Token) string {
@@ -132,14 +130,14 @@ func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {
}
}
- jwtToken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), jwt.MapClaims{
- "UserID": user.ID,
- "UserName": user.Name,
- "UserEmail": user.Email,
- })
+ claims := &auth.WchyClaims{
+ UserID: user.ID,
+ UserName: user.Name,
+ UserEmail: user.Email,
+ }
var token string
- if token, err = jwtToken.SignedString([]byte(jwtSecret)); err != nil {
+ if token, err = auth.Encode(claims); err != nil {
c.Logger().Errorf("%s oauthConfig.Exchange() failed with %s", provider, err)
return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
}
diff --git a/router/hostchecker.go b/router/hostchecker.go
deleted file mode 100644
index d3835a933..000000000
--- a/router/hostchecker.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package router
-
-import (
- "net/http"
- "strings"
-
- "github.com/labstack/echo"
-)
-
-// 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 {
-
- scheme := "http"
- if c.Request().TLS != nil {
- scheme = "https"
- }
- url := scheme + "://" + c.Request().Host
-
- if strings.Index(url, baseURL) < 0 {
- c.Logger().Errorf("%s is not valid for this operation", url)
- return c.NoContent(http.StatusBadRequest)
- }
- return next(c)
- }
- }
-}
diff --git a/router/jwt.go b/router/jwt.go
deleted file mode 100644
index 1224ff121..000000000
--- a/router/jwt.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package router
-
-import (
- "net/http"
- "os"
-
- "github.com/WeCanHearYou/wchy/auth"
- jwt "github.com/dgrijalva/jwt-go"
- "github.com/labstack/echo"
-)
-
-var jwtSecret = os.Getenv("JWT_SECRET")
-
-// 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 {
-
- if cookie, err := c.Cookie("auth"); err == nil {
- claims := &auth.WchyClaims{}
- token, err := jwt.ParseWithClaims(cookie.Value, claims, func(t *jwt.Token) (interface{}, error) {
- return []byte(jwtSecret), nil
- })
-
- if err == nil && token.Valid {
- c.Set("Claims", claims)
- }
- }
-
- return next(c)
- }
- }
-}
-
-// JwtSetter sets JWT token into cookie
-func JwtSetter() echo.MiddlewareFunc {
- return func(next echo.HandlerFunc) echo.HandlerFunc {
- return func(c echo.Context) error {
-
- query := c.Request().URL.Query()
-
- jwt := query.Get("jwt")
- if jwt != "" {
- c.SetCookie(&http.Cookie{
- Name: "auth",
- Value: jwt,
- HttpOnly: true,
- })
-
- scheme := "http"
- if c.Request().TLS != nil {
- scheme = "https"
- }
-
- query.Del("jwt")
-
- url := scheme + "://" + c.Request().Host + c.Request().URL.Path + "?" + query.Encode()
- return c.Redirect(http.StatusTemporaryRedirect, url)
- }
-
- return next(c)
- }
- }
-}
diff --git a/router/middlewares.go b/router/middlewares.go
new file mode 100644
index 000000000..196e0aa36
--- /dev/null
+++ b/router/middlewares.go
@@ -0,0 +1,99 @@
+package router
+
+import (
+ "net/http"
+ "strings"
+
+ "fmt"
+
+ "github.com/WeCanHearYou/wchy/auth"
+ "github.com/WeCanHearYou/wchy/context"
+ "github.com/WeCanHearYou/wchy/util"
+ "github.com/labstack/echo"
+)
+
+// MultiTenant extract tenant information from hostname and inject it into current context
+func MultiTenant(ctx *context.WchyContext) echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ hostname := util.StripPort(c.Request().Host)
+ tenant, err := ctx.Tenant.GetByDomain(hostname)
+ if err == nil {
+ c.Set("Tenant", tenant)
+ return next(c)
+ }
+
+ fmt.Printf("Tenant not found for %s.\n", hostname)
+ return c.NoContent(http.StatusNotFound)
+ }
+ }
+}
+
+// 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 {
+
+ scheme := "http"
+ if c.Request().TLS != nil {
+ scheme = "https"
+ }
+ url := scheme + "://" + c.Request().Host
+
+ if strings.Index(url, baseURL) < 0 {
+ c.Logger().Errorf("%s is not valid for this operation", url)
+ return c.NoContent(http.StatusBadRequest)
+ }
+ return next(c)
+ }
+ }
+}
+
+// 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 {
+
+ if cookie, err := c.Cookie("auth"); err == nil {
+ if claims, err := auth.Decode(cookie.Value); err == nil {
+ c.Set("Claims", claims)
+ } else {
+ c.Logger().Error(err)
+ }
+ }
+
+ return next(c)
+ }
+ }
+}
+
+// JwtSetter sets JWT token into cookie
+func JwtSetter() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+
+ query := c.Request().URL.Query()
+
+ jwt := query.Get("jwt")
+ if jwt != "" {
+ c.SetCookie(&http.Cookie{
+ Name: "auth",
+ Value: jwt,
+ HttpOnly: true,
+ })
+
+ scheme := "http"
+ if c.Request().TLS != nil {
+ scheme = "https"
+ }
+
+ query.Del("jwt")
+
+ url := scheme + "://" + c.Request().Host + c.Request().URL.Path + "?" + query.Encode()
+ return c.Redirect(http.StatusTemporaryRedirect, url)
+ }
+
+ return next(c)
+ }
+ }
+}
diff --git a/router/multitenant_test.go b/router/middlewares_test.go
similarity index 100%
rename from router/multitenant_test.go
rename to router/middlewares_test.go
diff --git a/router/multitenant.go b/router/multitenant.go
deleted file mode 100644
index c5fd6209e..000000000
--- a/router/multitenant.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package router
-
-import (
- "net/http"
- "strings"
-
- "fmt"
-
- "github.com/WeCanHearYou/wchy/context"
- "github.com/labstack/echo"
-)
-
-// MultiTenant extract tenant information from hostname and inject it into current context
-func MultiTenant(ctx *context.WchyContext) echo.MiddlewareFunc {
- return func(next echo.HandlerFunc) echo.HandlerFunc {
- return func(c echo.Context) error {
- hostname := stripPort(c.Request().Host)
- tenant, err := ctx.Tenant.GetByDomain(hostname)
- if err == nil {
- c.Set("Tenant", tenant)
- return next(c)
- }
-
- fmt.Printf("Tenant not found for %s.\n", hostname)
- return c.NoContent(http.StatusNotFound)
- }
- }
-}
-
-func stripPort(hostport string) string {
- colon := strings.IndexByte(hostport, ':')
- if colon == -1 {
- return hostport
- }
- return hostport[:colon]
-}
diff --git a/run.sh b/run.sh
new file mode 100644
index 000000000..f6b1b7f5d
--- /dev/null
+++ b/run.sh
@@ -0,0 +1 @@
+ gin --buildArgs "-ldflags='-X main.buildtime=${BUILD_TIME}'"
\ No newline at end of file
diff --git a/test.sh b/test.sh
new file mode 100644
index 000000000..4fc5783d5
--- /dev/null
+++ b/test.sh
@@ -0,0 +1,3 @@
+AUTH_ENDPOINT=http://login.test.canhearyou.com:3000 \
+GO_ENV=test \
+go test $(go list ./... | grep -v /vendor/) -cover
\ No newline at end of file
diff --git a/util/http.go b/util/http.go
new file mode 100644
index 000000000..d9f911abf
--- /dev/null
+++ b/util/http.go
@@ -0,0 +1,12 @@
+package util
+
+import "strings"
+
+//StripPort removes port from host and returns it
+func StripPort(hostport string) string {
+ colon := strings.IndexByte(hostport, ':')
+ if colon == -1 {
+ return hostport
+ }
+ return hostport[:colon]
+}