github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/appengine/login/gitkit1/handlers.go (about)

     1  package gitkit1
     2  
     3  import (
     4  	"fmt"
     5  	"html/template"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"net/url"
     9  
    10  	"github.com/gorilla/sessions"
    11  	"github.com/pbberlin/tools/net/http/tplx"
    12  
    13  	"google.golang.org/appengine"
    14  	aelog "google.golang.org/appengine/log"
    15  )
    16  
    17  func handleHome(w http.ResponseWriter, r *http.Request) {
    18  	// HandleHomeVari(w, r, successLandingURL, signoutLandingURL)
    19  	HandleHomeVari(w, r, signinLandingDefaultURL, signoutLandingDefaultURL)
    20  }
    21  
    22  func HandleHomeVari(w http.ResponseWriter, r *http.Request, successLandingURL, signoutLandingURL string) {
    23  
    24  	format := `
    25  		<a href='%v?mode=select'>Signin with Redirect (Widget)</a><br><br> 
    26  
    27  		<a href='%v'>Signin Success Landing</a><br><br> 
    28  		<a href='%v'>Signout </a><br><br>
    29  
    30  		<a href='%v'>Signout Landing</a><br> 
    31  		<a href='%v'>Branding for Account Chooser</a><br> 
    32  	`
    33  
    34  	str := fmt.Sprintf(format,
    35  		WidgetSigninAuthorizedRedirectURL,
    36  		successLandingURL,
    37  		signOutURL,
    38  
    39  		signoutLandingURL,
    40  		accountChooserBrandingURL,
    41  	)
    42  
    43  	bstpl := tplx.TemplateFromHugoPage(w, r) // the jQuery irritates
    44  	fmt.Fprintf(w, tplx.ExecTplHelper(bstpl, map[string]interface{}{
    45  		"HtmlTitle":       "Google Identity Toolkit Overview",
    46  		"HtmlDescription": "", // reminder
    47  		"HtmlContent":     template.HTML(str),
    48  	}))
    49  
    50  }
    51  
    52  func handleWidget(w http.ResponseWriter, r *http.Request) {
    53  
    54  	// param "red"  for redirect
    55  	// must correspond with the widget param queryParameterForSignInSuccessUrl
    56  	// It comes back with the encoded answer params - "source" and "state"
    57  	// But it's only
    58  	red := signinLandingDefaultURL
    59  
    60  	if r.FormValue("red") != "" {
    61  		red = r.FormValue("red") // This is not even necessary
    62  		red = signinLandingDefaultURL
    63  	}
    64  
    65  	// log.Printf("\n-----------------------------------")
    66  	// for key, v := range r.Form {
    67  	// 	log.Printf("%10v is %#v", key, v)
    68  	// }
    69  
    70  	HandleVariWidget(w, r, red)
    71  }
    72  
    73  func HandleVariWidget(w http.ResponseWriter, r *http.Request, successLandingURL string) {
    74  
    75  	defer r.Body.Close()
    76  	// Extract the POST body if any.
    77  	b, _ := ioutil.ReadAll(r.Body)
    78  	body, _ := url.QueryUnescape(string(b))
    79  
    80  	gitkitTemplate := GetWidgetTpl(w, r, siteName+" Identity Toolkit")
    81  
    82  	gitkitTemplate.Execute(w, map[string]interface{}{
    83  		"BrandingURL":         getConfig(siteName, "protocDomain") + accountChooserBrandingURL,
    84  		"FaviconURL":          getConfig(siteName, "protocDomain") + "/favicon.ico",
    85  		"BrowserAPIKey":       getConfig(siteName, "browserAPIKey"),
    86  		"SignInSuccessURLTRY": template.URL(`/harcoded/ use queryParameterForSignInSuccessUrl=red insteads`),
    87  		"SignInSuccessURL":    template.URL(successLandingURL), // widget
    88  		"SignOutURL":          signOutURL,
    89  		"OOBActionURL":        oobActionURL, // unnecessary, since we don't offer "home account", but kept
    90  		"SiteName":            siteName,
    91  		"POSTBody":            body,
    92  	})
    93  
    94  }
    95  
    96  func handleSigninSuccessLanding(w http.ResponseWriter, r *http.Request) {
    97  	HandleVariSuccess(w, r,
    98  		siteName+" member home",
    99  		UserInfoHTML+"<br><br>"+IDCardHTML+"<br><br>",
   100  	)
   101  }
   102  
   103  func HandleVariSuccess(w http.ResponseWriter, r *http.Request, title, body string) {
   104  
   105  	u := CurrentUser(r)
   106  
   107  	if ok := IsSignedIn(r); !ok {
   108  		u = nil
   109  	}
   110  
   111  	if u == nil {
   112  		http.Redirect(w, r, WidgetSigninAuthorizedRedirectURL+"?mode=select&user=wasNil", http.StatusFound)
   113  	}
   114  
   115  	saveCurrentUser(r, w, u)
   116  
   117  	//
   118  	homeTemplate := GetHomeTpl(w, r, title, body)
   119  
   120  	homeTemplate.Execute(w, map[string]interface{}{
   121  		"WidgetURL":  WidgetSigninAuthorizedRedirectURL,
   122  		"SignOutURL": signOutURL,
   123  		"User":       u,
   124  		// "CookieDump": template.HTML(htmlfrag.CookieDump(r)),
   125  	})
   126  }
   127  
   128  func handleSignOut(w http.ResponseWriter, r *http.Request) {
   129  	HandleVariSignOut(w, r, signoutLandingDefaultURL)
   130  }
   131  
   132  func HandleVariSignOut(w http.ResponseWriter, r *http.Request, signoutLandingURL string) {
   133  
   134  	sess, _ := cookieStore.Get(r, sessionName)
   135  	sess.Options = &sessions.Options{MaxAge: -1} // MaxAge<0 means delete session cookie.
   136  	err := sess.Save(r, w)
   137  	if err != nil {
   138  		aelog.Errorf(appengine.NewContext(r), "Cannot save session: %s", err)
   139  	}
   140  	// Impossible to delete SESSIONID cookie
   141  
   142  	// Also clear identity toolkit token.
   143  	http.SetCookie(w, &http.Cookie{Name: gtokenCookieName, MaxAge: -1})
   144  
   145  	// Redirect to home page for sign in again.
   146  	http.Redirect(w, r, signoutLandingURL+"?logout=true", http.StatusFound)
   147  	// w.Write([]byte("<a href='" + signoutLandingURL + "'>Home<a>"))
   148  
   149  }
   150  
   151  func handleSignOutLanding(w http.ResponseWriter, r *http.Request) {
   152  
   153  	format := `
   154  		Signed out<br>
   155  		<a href='%v'>Home</a><br> 
   156  	`
   157  
   158  	str := fmt.Sprintf(format, homeURL)
   159  
   160  	bstpl := tplx.TemplateFromHugoPage(w, r) // the jQuery irritates
   161  	fmt.Fprintf(w, tplx.ExecTplHelper(bstpl, map[string]interface{}{
   162  		"HtmlTitle":       "Google Identity Toolkit Overview",
   163  		"HtmlDescription": "", // reminder
   164  		"HtmlContent":     template.HTML(str),
   165  	}))
   166  
   167  }
   168  
   169  // Is called by AccountChooser to retrieve some layout.
   170  // Dynamic execution required because of Access-Control header ...
   171  func accountChooserBranding(w http.ResponseWriter, r *http.Request) {
   172  	w.Header().Set("Access-Control-Allow-Origin", "*")
   173  
   174  	str := `<!DOCTYPE html>
   175  <html>
   176    <head>
   177      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   178    </head>
   179    <body>
   180      <div style="width:256px;margin:auto">
   181        <img src="%v" 
   182        	style="display:block;height:120px;margin:auto">
   183        <p style="font-size:14px;opacity:.54;margin-top:20px;text-align:center">
   184          %v.
   185        </p>
   186      </div>
   187    </body>
   188  </html>`
   189  
   190  	str = fmt.Sprintf(str, getConfig(siteName, "accountChooserImg"), getConfig(siteName, "accountChooserHeadline"))
   191  
   192  	w.Write([]byte(str))
   193  
   194  }