Browse Source

Store user information in JWT string

Sasan Torabkheslat 5 years ago
parent
commit
f5d8745d68
3 changed files with 53 additions and 47 deletions
  1. 44 43
      handler.go
  2. 1 1
      main.go
  3. 8 3
      token.go

+ 44 - 43
handler.go

@@ -95,11 +95,11 @@ func (h *handler) login(c echo.Context) error {
 	res, err := client.Do(req)
 	cockie := res.Cookies()
 	defer res.Body.Close()
-	fmt.Println(res.StatusCode)
+	//fmt.Println(res.StatusCode)
 	if res.StatusCode == 200 {
 		user := getUserInfo(cockie, username)
-		fmt.Println(user.Result.Value)
-		tokens, err := generateTokenPair()
+		//fmt.Println(user.Result.Value)
+		tokens, err := generateTokenPair(user)
 		if err != nil {
 			return err
 		}
@@ -145,52 +145,53 @@ func getUserInfo(cockie []*http.Cookie, username string) userInfo {
 	user := userInfo{}
 	json.Unmarshal(body, &user)
 	//fmt.Println(user.Result.Value)
+	//fmt.Println(user.Result.Result.MemberofGroup)
 	return user
 }
 
 // This is the api to refresh tokens
 // Most of the code is taken from the jwt-go package's sample codes
 // https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac
-func (h *handler) token(c echo.Context) error {
-	type tokenReqBody struct {
-		RefreshToken string `json:"refresh_token"`
-	}
-	tokenReq := tokenReqBody{}
-	c.Bind(&tokenReq)
-
-	// Parse takes the token string and a function for looking up the key.
-	// The latter is especially useful if you use multiple keys for your application.
-	// The standard is to use 'kid' in the head of the token to identify
-	// which key to use, but the parsed token (head and claims) is provided
-	// to the callback, providing flexibility.
-	token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
-		// Don't forget to validate the alg is what you expect:
-		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
-			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
-		}
-
-		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
-		return []byte("secret"), nil
-	})
-
-	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
-		// Get the user record from database or
-		// run through your business logic to verify if the user can log in
-		if int(claims["sub"].(float64)) == 1 {
-
-			newTokenPair, err := generateTokenPair()
-			if err != nil {
-				return err
-			}
-
-			return c.JSON(http.StatusOK, newTokenPair)
-		}
-
-		return echo.ErrUnauthorized
-	}
-
-	return err
-}
+//func (h *handler) token(c echo.Context) error {
+//	type tokenReqBody struct {
+//		RefreshToken string `json:"refresh_token"`
+//	}
+//	tokenReq := tokenReqBody{}
+//	c.Bind(&tokenReq)
+//
+//	// Parse takes the token string and a function for looking up the key.
+//	// The latter is especially useful if you use multiple keys for your application.
+//	// The standard is to use 'kid' in the head of the token to identify
+//	// which key to use, but the parsed token (head and claims) is provided
+//	// to the callback, providing flexibility.
+//	token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
+//		// Don't forget to validate the alg is what you expect:
+//		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
+//			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
+//		}
+//
+//		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
+//		return []byte("secret"), nil
+//	})
+//
+//	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
+//		// Get the user record from database or
+//		// run through your business logic to verify if the user can log in
+//		if int(claims["sub"].(float64)) == 1 {
+//
+//			newTokenPair, err := generateTokenPair()
+//			if err != nil {
+//				return err
+//			}
+//
+//			return c.JSON(http.StatusOK, newTokenPair)
+//		}
+//
+//		return echo.ErrUnauthorized
+//	}
+//
+//	return err
+//}
 
 // Most of the code is taken from the echo guide
 // https://echo.labstack.com/cookbook/jwt

+ 1 - 1
main.go

@@ -52,7 +52,7 @@ func main() {
 
 	echoHandler.GET("/admin", h.private, isLoggedIn, isAdmin)
 
-	echoHandler.POST("/token", h.token)
+	//echoHandler.POST("/token", h.token)
 
 	echoHandler.Logger.Fatal(echoHandler.Start(os.Args[1] + ":" + os.Args[2]))
 }

+ 8 - 3
token.go

@@ -6,7 +6,7 @@ import (
 	"github.com/dgrijalva/jwt-go"
 )
 
-func generateTokenPair() (map[string]string, error) {
+func generateTokenPair(user userInfo) (map[string]string, error) {
 	// Create token
 	token := jwt.New(jwt.SigningMethodHS256)
 
@@ -14,9 +14,14 @@ func generateTokenPair() (map[string]string, error) {
 	// This is the information which frontend can use
 	// The backend can also decode the token and get admin etc.
 	claims := token.Claims.(jwt.MapClaims)
+	claims["admin"] = false
+	for _, v := range user.Result.Result.MemberofGroup {
+		if v == "admins" {
+			claims["admin"] = true
+		}
+	}
 	claims["sub"] = 1
-	claims["name"] = "Jon Doe"
-	claims["admin"] = true
+	claims["name"] = user.Result.Value
 	claims["exp"] = time.Now().Add(time.Minute * 15).Unix()
 
 	// Generate encoded token and send it as response.