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

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