github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/jwt_test.go (about)

     1  package f_test
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/angenalZZZ/gofunc/f"
     6  	"net/http"
     7  	"strings"
     8  	"testing"
     9  	"time"
    10  )
    11  
    12  func TestJwtAuth(t *testing.T) {
    13  	http.HandleFunc("/token", func(res http.ResponseWriter, req *http.Request) {
    14  		claims := map[string]interface{}{"exp": time.Now().Add(time.Hour * 24).Unix()}
    15  		token, err := f.NewJwtToken(claims)
    16  		if err != nil {
    17  			http.Error(res, "Internal Server Error", 500)
    18  			return
    19  		}
    20  		res.Header().Add("Authorization", "Bearer "+token)
    21  		fmt.Fprintf(res, "%s", f.EncodedJson(struct {
    22  			Token string `json:"token"`
    23  			Exp   int    `json:"exp"`
    24  		}{token, 3600 * 24}))
    25  		//res.WriteHeader(http.StatusOK)
    26  	})
    27  
    28  	http.HandleFunc("/auth", func(res http.ResponseWriter, req *http.Request) {
    29  		var userToken string
    30  		if reqVal := req.Header.Get("Authorization"); reqVal != "" {
    31  			userToken = strings.Split(reqVal, " ")[1]
    32  		} else if reqVal := req.URL.Query().Get("token"); reqVal != "" {
    33  			userToken = reqVal
    34  		}
    35  		if m, ok := f.IsJwtToken(userToken); ok {
    36  			fmt.Fprintf(res, "%s", f.EncodedMap(m))
    37  		} else {
    38  			http.Error(res, "Unauthorized", 401)
    39  		}
    40  	})
    41  
    42  	if err := http.ListenAndServe(":8080", nil); err != nil {
    43  		t.Fatal(err)
    44  	}
    45  }