github.com/iron-io/functions@v0.0.0-20180820112432-d59d7d1c40b2/api/server/middlewares.go (about)

     1  package server
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  	"time"
     9  
    10  	"github.com/iron-io/functions/api/models"
    11  	"github.com/iron-io/functions/common"
    12  	"github.com/spf13/viper"
    13  )
    14  
    15  func SetupJwtAuth(funcServer *Server) {
    16  	// Add default JWT AUTH if env variable set
    17  	if jwtAuthKey := viper.GetString("jwt_auth_key"); jwtAuthKey != "" {
    18  		funcServer.AddMiddlewareFunc(func(ctx MiddlewareContext, w http.ResponseWriter, r *http.Request, app *models.App) error {
    19  			start := time.Now()
    20  			fmt.Println("JwtAuthMiddlewareFunc called at:", start)
    21  			ctx.Next()
    22  			fmt.Println("Duration:", (time.Now().Sub(start)))
    23  			return nil
    24  		})
    25  		funcServer.AddMiddleware(&JwtAuthMiddleware{})
    26  	}
    27  }
    28  
    29  type JwtAuthMiddleware struct {
    30  }
    31  
    32  func (h *JwtAuthMiddleware) Serve(ctx MiddlewareContext, w http.ResponseWriter, r *http.Request, app *models.App) error {
    33  	fmt.Println("JwtAuthMiddleware called")
    34  	jwtAuthKey := viper.GetString("jwt_auth_key")
    35  
    36  	if err := common.AuthJwt(jwtAuthKey, r); err != nil {
    37  		w.WriteHeader(http.StatusUnauthorized)
    38  		m := map[string]string{"error": "Invalid API Authorization token."}
    39  		json.NewEncoder(w).Encode(m)
    40  		return errors.New("Invalid API authorization token.")
    41  	}
    42  
    43  	fmt.Println("auth succeeded!")
    44  	return nil
    45  }