github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume3/section4/gopherface/middleware/gated.go (about)

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  
     8  	"github.com/EngineerKamesh/gofullstack/volume3/section4/gopherface/common/authenticate"
     9  )
    10  
    11  func GatedContentHandler(next http.HandlerFunc) http.Handler {
    12  
    13  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    14  
    15  		shouldRedirectToLogin := false
    16  
    17  		secureCookieMap, err := authenticate.ReadSecureCookieValues(w, r)
    18  		if err != nil {
    19  			log.Print(err)
    20  		}
    21  
    22  		//fmt.Printf("secure cookie contents: %+v\n", secureCookieMap)
    23  
    24  		// Check if the sid key which is used to store the session id value
    25  		// has been populated in the map using the comma ok idiom
    26  		if _, ok := secureCookieMap["sid"]; ok == true {
    27  
    28  			gfSession, err := authenticate.SessionStore.Get(r, "gopherface-session")
    29  
    30  			fmt.Printf("gopherface session values: %+v\n", gfSession.Values)
    31  			if err != nil {
    32  				log.Print(err)
    33  				return
    34  			}
    35  
    36  			// Check if the session id stored in the secure cookie matches
    37  			// the id and username on the server-side session
    38  			if gfSession.Values["sessionID"] == secureCookieMap["sid"] && gfSession.Values["username"] == secureCookieMap["username"] {
    39  				next(w, r)
    40  			} else {
    41  				shouldRedirectToLogin = true
    42  			}
    43  
    44  		} else {
    45  			shouldRedirectToLogin = true
    46  
    47  		}
    48  
    49  		if shouldRedirectToLogin == true {
    50  			http.Redirect(w, r, "/login", 302)
    51  		}
    52  
    53  	})
    54  
    55  }