From f4f1fc4213f5a706d00954abe02912396bde1ed7 Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Thu, 6 Jul 2017 09:31:07 +0100 Subject: [PATCH] Don't send password hash to front-end Former-commit-id: 8063326551ef444c718284c0307acd646c28921d [formerly 222b0e273b26617e86c624f54e39db3743c2bff4] [formerly b75a02d333e94460ac83a305d062dc17bacf705e [formerly 43115f44f2941e92c41b1c8270d57f800ded93fa]] Former-commit-id: b2bc236aacbca7a2ede89809fd728b70291335f9 [formerly 332d8886620d00420c4ef9bf786464acaebb807e] Former-commit-id: 4bf173a4143a85a7f8fbba9cd5b7a4673ef64062 --- auth.go | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/auth.go b/auth.go index 450634dd..ed0d3f21 100644 --- a/auth.go +++ b/auth.go @@ -12,11 +12,6 @@ import ( "github.com/dgrijalva/jwt-go/request" ) -type claims struct { - *User - jwt.StandardClaims -} - // authHandler proccesses the authentication for the user. func authHandler(c *requestContext, w http.ResponseWriter, r *http.Request) (int, error) { // Receive the credentials from the request and unmarshal them. @@ -41,23 +36,8 @@ func authHandler(c *requestContext, w http.ResponseWriter, r *http.Request) (int return http.StatusForbidden, nil } - claims := claims{ - c.fm.Users["admin"], - jwt.StandardClaims{ - ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), - Issuer: "File Manager", - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - string, err := token.SignedString(c.fm.key) - - if err != nil { - return http.StatusInternalServerError, err - } - - w.Write([]byte(string)) - return 0, nil + c.us = u + return printToken(c, w) } // renewAuthHandler is used when the front-end already has a JWT token @@ -68,6 +48,25 @@ func renewAuthHandler(c *requestContext, w http.ResponseWriter, r *http.Request) return http.StatusForbidden, nil } + c.us = u + return printToken(c, w) +} + +// claims is the JWT claims. +type claims struct { + User + jwt.StandardClaims +} + +// printToken prints the final JWT token to the user. +func printToken(c *requestContext, w http.ResponseWriter) (int, error) { + // Creates a copy of the user and removes it password + // hash so it never arrives to the user. + u := User{} + u = *c.us + u.Password = "" + + // Builds the claims. claims := claims{ u, jwt.StandardClaims{ @@ -76,12 +75,15 @@ func renewAuthHandler(c *requestContext, w http.ResponseWriter, r *http.Request) }, } + // Creates the token and signs it. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) string, err := token.SignedString(c.fm.key) + if err != nil { return http.StatusInternalServerError, err } + // Writes the token. w.Write([]byte(string)) return 0, nil }