Commit 09bbb4139d88a492d82f832a010c452ae1907411

Authored by David Shere
1 parent 76c173cb8c
Exists in google-account

Implemented google account login

Showing 1 changed file with 52 additions and 14 deletions Side-by-side Diff

... ... @@ -6,35 +6,72 @@
6 6  
7 7 "appengine"
8 8 "appengine/datastore"
  9 + "appengine/user"
9 10 )
10 11  
  12 +// datastore Entity type
  13 +type UserData struct {
  14 + Value string
  15 +}
  16 +
11 17 func init() {
12 18 http.HandleFunc("/", rootHandler)
13 19 }
14 20  
15   -type User struct {
16   - UserID string
17   - Value string
18   -}
19   -
20 21 func rootHandler(w http.ResponseWriter, r *http.Request) {
21 22 c := appengine.NewContext(r)
22   - u := User{
23   - UserID: r.FormValue("userid"),
24   - Value: r.FormValue("value"),
  23 + u := user.Current(c)
  24 + url, _ := user.LogoutURL(c, "/")
  25 +
  26 + // Handle user sign in.
  27 + if u == nil {
  28 + url, _ := user.LoginURL(c, "/")
  29 + signInTemplate.Execute(w, url)
  30 + return
25 31 }
26   - k := datastore.NewKey(c, "User", u.UserID, 0, nil)
27 32  
28   - if u.Value == "" {
29   - datastore.Get(c, k, &u)
  33 + // Retrieve or store a value
  34 + k := datastore.NewKey(c, "UserData", u.String(), 0, nil)
  35 + ud := UserData{
  36 + Value: r.FormValue("value"),
  37 + }
  38 + if ud.Value == "" {
  39 + datastore.Get(c, k, &ud)
  40 + if ud.Value == "" {
  41 + ud.Value = "null"
  42 + }
30 43 } else {
31   - datastore.Put(c, k, &u)
  44 + datastore.Put(c, k, &ud)
32 45 }
33 46  
34   - rootTemplate.Execute(w, u.Value)
  47 + // Generate the page
  48 + rootTemplate.Execute(w, struct {
  49 + Value string
  50 + SignoutURL string
  51 + }{
  52 + Value: ud.Value,
  53 + SignoutURL: url,
  54 + })
35 55  
36 56 }
37 57  
  58 +// User sign in template
  59 +var signInTemplate = template.Must(template.New("signIn").Parse(signInTemplateHTML))
  60 +
  61 +const signInTemplateHTML = `
  62 +<!DOCTYPE HTML>
  63 +<html>
  64 + <head>
  65 + <title>WebHash Go</title>
  66 + <meta charset="utf-8">
  67 + </head>
  68 + <body>
  69 + <div><a href="{{.}}">sign in or register</a></div>
  70 + </body>
  71 +</html>
  72 +`
  73 +
  74 +// Main page displaying user's value
38 75 var rootTemplate = template.Must(template.New("root").Parse(rootTemplateHTML))
39 76  
40 77 const rootTemplateHTML = `
... ... @@ -45,7 +82,8 @@
45 82 <meta charset="utf-8">
46 83 </head>
47 84 <body>
48   - {{.}}
  85 + {{.Value}}
  86 + <div><a href="{{.SignoutURL}}">sign out</a></div>
49 87 </body>
50 88 </html>
51 89 `