forked from GoogleCloudPlatform/golang-samples
/
main.go
149 lines (128 loc) · 4 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Copyright 2018 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"html/template"
"net/http"
"time"
// [START imports]
firebase "firebase.google.com/go"
// [END imports]
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
)
// [START new_variable]
var (
firebaseConfig = &firebase.Config{
DatabaseURL: "https://console.firebase.google.com > Overview > Add Firebase to your web app",
ProjectID: "https://console.firebase.google.com > Overview > Add Firebase to your web app",
StorageBucket: "https://console.firebase.google.com > Overview > Add Firebase to your web app",
}
indexTemplate = template.Must(template.ParseFiles("index.html"))
)
// [END new_variable]
type Post struct {
Author string
// [START new_post_field]
UserID string
// [END new_post_field]
Message string
Posted time.Time
}
type templateParams struct {
Notice string
Name string
Message string
Posts []Post
}
func main() {
http.HandleFunc("/", indexHandler)
appengine.Main()
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Redirect(w, r, "/", http.StatusFound)
return
}
ctx := appengine.NewContext(r)
params := templateParams{}
q := datastore.NewQuery("Post").Order("-Posted").Limit(20)
if _, err := q.GetAll(ctx, ¶ms.Posts); err != nil {
log.Errorf(ctx, "Getting posts: %v", err)
w.WriteHeader(http.StatusInternalServerError)
params.Notice = "Couldn't get latest posts. Refresh?"
indexTemplate.Execute(w, params)
return
}
if r.Method == "GET" {
indexTemplate.Execute(w, params)
return
}
// It's a POST request, so handle the form submission.
// [START firebase_token]
message := r.FormValue("message")
// Create a new Firebase App.
app, err := firebase.NewApp(ctx, firebaseConfig)
if err != nil {
params.Notice = "Couldn't authenticate. Try logging in again?"
params.Message = message // Preserve their message so they can try again.
indexTemplate.Execute(w, params)
return
}
// Create a new authenticator for the app.
auth, err := app.Auth(ctx)
if err != nil {
params.Notice = "Couldn't authenticate. Try logging in again?"
params.Message = message // Preserve their message so they can try again.
indexTemplate.Execute(w, params)
return
}
// Verify the token passed in by the user is valid.
tok, err := auth.VerifyIDTokenAndCheckRevoked(ctx, r.FormValue("token"))
if err != nil {
params.Notice = "Couldn't authenticate. Try logging in again?"
params.Message = message // Preserve their message so they can try again.
indexTemplate.Execute(w, params)
return
}
// Use the validated token to get the user's information.
user, err := auth.GetUser(ctx, tok.UID)
if err != nil {
params.Notice = "Couldn't authenticate. Try logging in again?"
params.Message = message // Preserve their message so they can try again.
indexTemplate.Execute(w, params)
return
}
// [END firebase_token]
// [START logged_in_post]
post := Post{
UserID: user.UID, // Include UserID in case Author isn't unique.
Author: user.DisplayName,
Message: message,
Posted: time.Now(),
}
// [END logged_in_post]
params.Name = post.Author
if post.Message == "" {
w.WriteHeader(http.StatusBadRequest)
params.Notice = "No message provided"
indexTemplate.Execute(w, params)
return
}
key := datastore.NewIncompleteKey(ctx, "Post", nil)
if _, err := datastore.Put(ctx, key, &post); err != nil {
log.Errorf(ctx, "datastore.Put: %v", err)
w.WriteHeader(http.StatusInternalServerError)
params.Notice = "Couldn't add new post. Try again?"
params.Message = post.Message // Preserve their message so they can try again.
indexTemplate.Execute(w, params)
return
}
// Prepend the post that was just added.
params.Posts = append([]Post{post}, params.Posts...)
params.Notice = fmt.Sprintf("Thank you for your submission, %s!", post.Author)
indexTemplate.Execute(w, params)
}