github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/session/middleware.go (about)

     1  package session
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/fragmenta/auth"
     9  	"github.com/fragmenta/server/log"
    10  	"github.com/fragmenta/view"
    11  )
    12  
    13  // Middleware sets a token on every GET request so that it can be
    14  // inserted into the view. It currently ignores requests for files and assets.
    15  func Middleware(h http.HandlerFunc) http.HandlerFunc {
    16  
    17  	return func(w http.ResponseWriter, r *http.Request) {
    18  
    19  		// If a get method, we need to set the token for use in views
    20  		if shouldSetToken(r) {
    21  
    22  			// This sets the token on the encrypted session cookie
    23  			token, err := auth.AuthenticityToken(w, r)
    24  			if err != nil {
    25  				log.Error(log.Values{"msg": "session: problem setting token", "error": err})
    26  			} else {
    27  				// Save the token to the request context for use in views
    28  				ctx := r.Context()
    29  				ctx = context.WithValue(ctx, view.AuthenticityContext, token)
    30  				r = r.WithContext(ctx)
    31  			}
    32  
    33  		}
    34  
    35  		h(w, r)
    36  	}
    37  
    38  }
    39  
    40  // shouldSetToken returns true if this request requires a token set.
    41  func shouldSetToken(r *http.Request) bool {
    42  
    43  	// No tokens on anything but GET requests
    44  	if r.Method != http.MethodGet {
    45  		return false
    46  	}
    47  
    48  	// No tokens on non-html resources
    49  	if strings.HasPrefix(r.URL.Path, "/files") ||
    50  		strings.HasPrefix(r.URL.Path, "/assets") {
    51  		return false
    52  	}
    53  
    54  	return true
    55  }