From 6d7ec04974045147b21febd399db09e9b632e672 Mon Sep 17 00:00:00 2001 From: Max Schmitt Date: Sun, 5 Nov 2017 00:24:54 +0100 Subject: [PATCH] Added #11 --- handlers/auth.go | 26 ++++++++++++++++++++++++++ handlers/handlers.go | 6 ++++-- static/src/App/App.js | 11 +++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/handlers/auth.go b/handlers/auth.go index 4568182..574914e 100644 --- a/handlers/auth.go +++ b/handlers/auth.go @@ -60,6 +60,32 @@ func (h *Handler) handleGoogleRedirect(c *gin.Context) { c.Redirect(http.StatusTemporaryRedirect, h.oAuthConf.AuthCodeURL(state)) } +func (h *Handler) authMiddleware(c *gin.Context) { + authHeader := c.GetHeader("Authorization") + if authHeader == "" { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ + "error": "'authorization' header not set", + }) + return + } + token, err := jwt.ParseWithClaims(authHeader, &jwtClaims{}, func(token *jwt.Token) (interface{}, error) { + return h.config.Secret, nil + }) + if err != nil { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ + "error": fmt.Sprintf("could not parse token: %v", err), + }) + return + } + if !token.Valid { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ + "error": "token is not valid", + }) + return + } + c.Next() +} + func (h *Handler) handleGoogleCheck(c *gin.Context) { var data struct { Token string `binding:"required"` diff --git a/handlers/handlers.go b/handlers/handlers.go index 0c9aa69..decea4a 100644 --- a/handlers/handlers.go +++ b/handlers/handlers.go @@ -54,8 +54,10 @@ func (h *Handler) setHandlers() { if !h.config.EnableGinDebugMode { gin.SetMode(gin.ReleaseMode) } - h.engine.POST("/api/v1/create", h.handleCreate) - h.engine.POST("/api/v1/info", h.handleInfo) + protected := h.engine.Group("/api/v1/protected") + protected.Use(h.authMiddleware) + protected.POST("/create", h.handleCreate) + protected.POST("/info", h.handleInfo) // h.engine.Static("/static", "static/src") h.engine.NoRoute(h.handleAccess) h.engine.LoadHTMLGlob("templates/*") diff --git a/static/src/App/App.js b/static/src/App/App.js index 6ece408..2eec63e 100644 --- a/static/src/App/App.js +++ b/static/src/App/App.js @@ -6,6 +6,17 @@ class AppComponent extends Component { handleURLChange = (e, { value }) => this.url = value handleURLSubmit = () => { console.log("handle Submit", "URL:", this.url) + fetch("/api/v1/protected/create", { + method: "POST", + body: JSON.stringify({ + URL: this.url + }), + headers: { + "Authorization": window.localStorage.getItem("token"), + 'Content-Type': 'application/json' + } + }).then(res => res.ok ? res.json() : Promise.reject(res.json())) + .then(d => console.log(d)) } componentWillMount() {