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 Inline Diff

package webhash 1 1 package webhash
2 2
import ( 3 3 import (
"html/template" 4 4 "html/template"
"net/http" 5 5 "net/http"
6 6
"appengine" 7 7 "appengine"
"appengine/datastore" 8 8 "appengine/datastore"
9 "appengine/user"
) 9 10 )
10 11
12 // datastore Entity type
13 type UserData struct {
14 Value string
15 }
16
func init() { 11 17 func init() {
http.HandleFunc("/", rootHandler) 12 18 http.HandleFunc("/", rootHandler)
} 13 19 }
14 20
type User struct { 15
UserID string 16
Value string 17
} 18
19
func rootHandler(w http.ResponseWriter, r *http.Request) { 20 21 func rootHandler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r) 21 22 c := appengine.NewContext(r)
u := User{ 22 23 u := user.Current(c)
UserID: r.FormValue("userid"), 23 24 url, _ := user.LogoutURL(c, "/")
Value: r.FormValue("value"), 24 25
26 // Handle user sign in.
27 if u == nil {
28 url, _ := user.LoginURL(c, "/")
29 signInTemplate.Execute(w, url)
30 return
} 25 31 }
k := datastore.NewKey(c, "User", u.UserID, 0, nil) 26
27 32
if u.Value == "" { 28 33 // Retrieve or store a value
datastore.Get(c, k, &u) 29 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 }
} else { 30 43 } else {
datastore.Put(c, k, &u) 31 44 datastore.Put(c, k, &ud)
} 32 45 }
33 46
rootTemplate.Execute(w, u.Value) 34 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
var rootTemplate = template.Must(template.New("root").Parse(rootTemplateHTML)) 38 75 var rootTemplate = template.Must(template.New("root").Parse(rootTemplateHTML))
39 76
const rootTemplateHTML = ` 40 77 const rootTemplateHTML = `
<!DOCTYPE HTML> 41 78 <!DOCTYPE HTML>
<html> 42 79 <html>
<head> 43 80 <head>
<title>WebHash Go</title> 44 81 <title>WebHash Go</title>
<meta charset="utf-8"> 45 82 <meta charset="utf-8">
</head> 46 83 </head>
<body> 47 84 <body>
{{.}} 48 85 {{.Value}}
86 <div><a href="{{.SignoutURL}}">sign out</a></div>
</body> 49 87 </body>