package api import ( "context" "fmt" "net/http" "smm2_gameserver/orm" "strconv" "time" "github.com/dgrijalva/jwt-go" ) // Define a function to create a new JWT token func createToken(userID orm.BigInt) (string, error) { // Create the claims for the token claims := jwt.MapClaims{ "sub": userID, "exp": time.Now().Add(time.Hour * 24 * 14).Unix(), // Token will expire in 2 weeks } // Create the token object with claims and sign it with the secret key token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) signedToken, err := token.SignedString(jwtSecret) if err != nil { return "", err } return signedToken, nil } func JwtMiddleware(next http.Handler) http.Handler { return jwtMiddleware(next) } func readAuthHeaders(r *http.Request) (*http.Request, error) { // Get the token from the Authorization header authHeader := r.Header.Get("Authorization") if authHeader == "" { return nil, fmt.Errorf("empty auth header") } // Parse the token and verify it with the secret key tokenString := authHeader[len("Bearer "):] token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return jwtSecret, nil }) if err != nil { return nil, err } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { return nil, fmt.Errorf("invalid token") } // Extract the userID from the token claims and set it in the request context userID, err := strconv.ParseInt(claims["sub"].(string), 10, 64) if err != nil { return nil, fmt.Errorf("invalid format for user id") } ctx := context.WithValue(r.Context(), "userID", userID) return r.WithContext(ctx), nil } // Define a middleware function to verify the JWT token and set the user in the request context func jwtMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { newReq, err := readAuthHeaders(r) if err != nil { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, newReq) }) } func getUserId(r *http.Request) int64 { return r.Context().Value("userID").(int64) } // // Define a handler function that requires a valid JWT token to be present // func myHandler(w http.ResponseWriter, r *http.Request) { // // Get the userID from the request context // userID := r.Context().Value("userID").(string) // // // Do something with the userID // // ... // }