From 09bbb4139d88a492d82f832a010c452ae1907411 Mon Sep 17 00:00:00 2001 From: David Shere Date: Fri, 4 Apr 2014 22:49:16 -0700 Subject: [PATCH] Implemented google account login --- src/main.go | 66 ++++++++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/src/main.go b/src/main.go index 5175b44..3c98588 100644 --- a/src/main.go +++ b/src/main.go @@ -6,35 +6,72 @@ import ( "appengine" "appengine/datastore" + "appengine/user" ) -func init() { - http.HandleFunc("/", rootHandler) +// datastore Entity type +type UserData struct { + Value string } -type User struct { - UserID string - Value string +func init() { + http.HandleFunc("/", rootHandler) } func rootHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) - u := User{ - UserID: r.FormValue("userid"), - Value: r.FormValue("value"), + u := user.Current(c) + url, _ := user.LogoutURL(c, "/") + + // Handle user sign in. + if u == nil { + url, _ := user.LoginURL(c, "/") + signInTemplate.Execute(w, url) + return } - k := datastore.NewKey(c, "User", u.UserID, 0, nil) - if u.Value == "" { - datastore.Get(c, k, &u) + // Retrieve or store a value + k := datastore.NewKey(c, "UserData", u.String(), 0, nil) + ud := UserData{ + Value: r.FormValue("value"), + } + if ud.Value == "" { + datastore.Get(c, k, &ud) + if ud.Value == "" { + ud.Value = "null" + } } else { - datastore.Put(c, k, &u) + datastore.Put(c, k, &ud) } - rootTemplate.Execute(w, u.Value) + // Generate the page + rootTemplate.Execute(w, struct { + Value string + SignoutURL string + }{ + Value: ud.Value, + SignoutURL: url, + }) } +// User sign in template +var signInTemplate = template.Must(template.New("signIn").Parse(signInTemplateHTML)) + +const signInTemplateHTML = ` + + + + WebHash Go + + + +
sign in or register
+ + +` + +// Main page displaying user's value var rootTemplate = template.Must(template.New("root").Parse(rootTemplateHTML)) const rootTemplateHTML = ` @@ -45,7 +82,8 @@ const rootTemplateHTML = ` - {{.}} + {{.Value}} +
sign out
` -- 1.9.1