Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

added jwt tokens and social buttons

goenning0b31c8fe2489
diff --git a/auth/service.go b/auth/service.go
index 871af92d7..84e122459 100644
--- a/auth/service.go
+++ b/auth/service.go
@@ -3,6 +3,8 @@ package auth
import (
"database/sql"
"errors"
+
+ jwt "github.com/dgrijalva/jwt-go"
)
const (
@@ -20,6 +22,14 @@ 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 2a7792fe1..e23d7542f 100644
--- a/handler/oauth.go
+++ b/handler/oauth.go
@@ -14,6 +14,7 @@ import (
"github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/context"
+ jwt "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
)
@@ -30,6 +31,7 @@ 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 {
@@ -96,14 +98,14 @@ func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {
//Because the user can deny access to it
settings := oauthSettings[provider]
- token, err := settings.config.Exchange(oauth2.NoContext, code)
+ oauthToken, err := settings.config.Exchange(oauth2.NoContext, code)
if 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
}
oauthUser := &oauthUserProfile{}
- if err = doGet(settings.profileURL(token), oauthUser); err != nil {
+ if err = doGet(settings.profileURL(oauthToken), oauthUser); err != nil {
c.Logger().Errorf("HTTP Get profile for %s failed with %s", provider, err)
return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
}
@@ -130,9 +132,28 @@ func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {
}
}
- c.Logger().Infof("Logged in as %s", user)
+ jwtToken := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), jwt.MapClaims{
+ "UserID": user.ID,
+ "UserName": user.Name,
+ "UserEmail": user.Email,
+ })
- return c.Redirect(http.StatusTemporaryRedirect, redirect)
+ var token string
+ if token, err = jwtToken.SignedString([]byte(jwtSecret)); 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
+ }
+
+ var redirectURL *url.URL
+ if redirectURL, err = url.Parse(redirect); err != nil {
+ c.Logger().Errorf("Could not parse url %s", redirect)
+ return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
+ }
+
+ var query = redirectURL.Query()
+ query.Add("jwt", token)
+ redirectURL.RawQuery = query.Encode()
+ return c.Redirect(http.StatusTemporaryRedirect, redirectURL.String())
}
}
diff --git a/router/jwt.go b/router/jwt.go
new file mode 100644
index 000000000..1224ff121
--- /dev/null
+++ b/router/jwt.go
@@ -0,0 +1,64 @@
+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/renderer.go b/router/renderer.go
index b3321c74d..6a3fd4c70 100644
--- a/router/renderer.go
+++ b/router/renderer.go
@@ -60,8 +60,10 @@ func (r *HTMLRenderer) Render(w io.Writer, name string, data interface{}, c echo
protocol = "https://"
}
+ //TODO: refactor (and move somewhere else?)
m := data.(echo.Map)
m["AuthEndpoint"] = os.Getenv("AUTH_ENDPOINT")
+ m["Claims"] = c.Get("Claims")
m["CurrentUrl"] = protocol + c.Request().Host + c.Request().URL.String()
return tmpl.Execute(w, m)
diff --git a/router/router.go b/router/router.go
index d29f28f40..2335d57f8 100644
--- a/router/router.go
+++ b/router/router.go
@@ -56,8 +56,12 @@ func GetMainEngine(ctx *context.WchyContext) *echo.Echo {
authGroup.GET("/oauth/google/callback", handler.OAuth(ctx).Callback(auth.OAuthGoogleProvider))
}
- app := router.Group("", MultiTenant(ctx))
+ app := router.Group("")
{
+ app.Use(JwtGetter())
+ app.Use(JwtSetter())
+ app.Use(MultiTenant(ctx))
+
app.GET("/", handler.Index(ctx))
api := app.Group("/api")
diff --git a/vendor/vendor.json b/vendor/vendor.json
index c0cc20c3a..f80f5e480 100644
--- a/vendor/vendor.json
+++ b/vendor/vendor.json
@@ -146,6 +146,12 @@
"revision": "346938d642f2ec3594ed81d874461961cd0faa76",
"revisionTime": "2016-10-29T20:57:26Z"
},
+ {
+ "checksumSHA1": "2Fy1Y6Z3lRRX1891WF/+HT4XS2I=",
+ "path": "github.com/dgrijalva/jwt-go",
+ "revision": "2268707a8f0843315e2004ee4f1d021dc08baedf",
+ "revisionTime": "2017-02-01T22:58:49Z"
+ },
{
"checksumSHA1": "zYnPsNAVm1/ViwCkN++dX2JQhBo=",
"path": "github.com/edsrzf/mmap-go",
diff --git a/views/index.html b/views/index.html
index 3aa546197..0e0a8cab1 100644
--- a/views/index.html
+++ b/views/index.html
@@ -8,11 +8,18 @@
<div class="header item">
{{ .Tenant.Name }}
</div>
- <a class="item right signin">
- <img class="ui avatar image" src="https://www.gravatar.com/avatar/">
- Sign in
- <i class="dropdown icon"></i>
- </a>
+ {{if not .Claims }}
+ <a class="item right signin">
+ <img class="ui avatar image" src="https://www.gravatar.com/avatar/">
+ Sign in {{ .Claims }}
+ <i class="dropdown icon"></i>
+ </a>
+ {{ else }}
+ <a class="item right">
+ <img class="ui avatar image" src="https://www.gravatar.com/avatar/">
+ {{ .Claims.UserName }}
+ </a>
+ {{ end }}
</div>
</div>