-
Notifications
You must be signed in to change notification settings - Fork 0
/
doorbell.go
213 lines (177 loc) · 5.07 KB
/
doorbell.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"html/template"
"log"
"net"
"net/http"
"os"
"strings"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"github.com/pusher/pusher-http-go"
"encoding/json"
"io/ioutil"
"google.golang.org/api/option"
)
const (
// PusherConfigPath is the location of the pusher secrets and configuration properties
PusherConfigPath = "./pusher.json"
// FirebaseConfigPath is the location of the firebase authentication secrets and configuration properties.
// Note, the ./templates/entercode.html file also needs to be updated.
FirebaseConfigPath = "./doorbell-520-firebase-adminsdk-mvx33-b87513bbce.json"
)
var formTemplate = loadTemplate("EnterCode", "./templates/entercode.html")
var confirmationTemplate = loadTemplate("Confirmation", "./templates/confirm.html")
type pusherConfig struct {
AppID string
Key string
Secret string
Cluster string
Secure bool
Channel string
Event string
}
var pusherConfigData = loadPusherConfig(PusherConfigPath)
func init() {
http.HandleFunc("/", handleShowForm)
http.HandleFunc("/submitCode", handleSendCode)
http.HandleFunc("/custom_icon.png", handleIcon)
http.HandleFunc("/fav.ico", handleIcon)
}
const customIconPath = "custom_icon.png"
func handleIcon(w http.ResponseWriter, r *http.Request) {
file, err := os.Open(customIconPath)
if err != nil {
log.Printf("Failed to open %s", customIconPath)
return
}
defer file.Close()
data := make([]byte, 512)
for {
i, err := file.Read(data)
if err != nil {
break
}
w.Write(data[0:i])
}
}
func loadTemplate(name, path string) *template.Template {
templateBytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatalf("Can't load template path %s for %s", path, name)
return nil
}
defer log.Printf("Loaded template for %s from %s of length %d", name, path, len(templateBytes))
return template.Must(template.New(name).Parse(string(templateBytes)))
}
func loadPusherConfig(path string) pusherConfig {
log.Println("Loading ", path)
raw, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("Failed to read pusher config:", err)
}
p := pusherConfig{}
if jsonerr := json.Unmarshal(raw, &p); jsonerr != nil {
log.Fatal(jsonerr)
}
log.Print("Loaded app id:", p.AppID)
return p
}
func handleShowForm(w http.ResponseWriter, r *http.Request) {
log.Print("Serving the front page.")
formTemplate.Execute(w, nil)
}
func isAuthorized(r *http.Request) (bool, *auth.UserRecord) {
idToken := r.Form["idToken"]
if len(idToken) != 1 || len(idToken[0]) == 0 {
log.Print("idToken not provided")
return false, nil
}
ctx := r.Context()
opt := option.WithCredentialsFile(FirebaseConfigPath)
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
return false, nil
}
client, err := app.Auth(ctx)
if err != nil {
log.Fatalf("error initializing all client: %v\n", err)
return false, nil
}
token, err := client.VerifyIDToken(ctx, idToken[0])
if err != nil {
log.Fatalf("error verifying ID token: %v. submitted token: %v\n verified: %v\ncontext: %v\n", err, idToken[0], token, ctx)
return false, nil
}
user, err := client.GetUser(ctx, token.UID)
if err != nil || user == nil {
log.Fatalf("Failed to get user verifying ID token: %v\n", err)
return false, nil
}
return true, user
}
func handleSendCode(w http.ResponseWriter, r *http.Request) {
var inputCode string
var ip = r.RemoteAddr
var headers string
for k, v := range r.Header {
headers += k + "->" + strings.Join(v, ",")
}
log.Print(net.SplitHostPort(r.RemoteAddr))
log.Print(r.Header)
r.ParseForm()
log.Print("Serving the front page.")
authorized, userRecord := isAuthorized(r)
if authorized {
log.Print("Logging in with firebase using email:" + userRecord.Email)
inputCode = userRecord.Email
} else if code := r.Form["code"][0]; !strings.ContainsAny(code, ".@-") {
inputCode = code
log.Print("Logging in secret passcode")
authorized = true
} else {
authorized = false
log.Print("Unauthorized access.")
}
if authorized {
data := map[string]string{
"message": inputCode,
"ip": ip,
"header": headers,
"remoteAddr": r.RemoteAddr,
"referrer": r.Referer(),
"uri": r.RequestURI,
}
log.Print("Sending code to pusher app: ", pusherConfigData.AppID, " from ip ", ip)
log.Print(data)
client := pusher.Client{
AppID: pusherConfigData.AppID,
Key: pusherConfigData.Key,
Secret: pusherConfigData.Secret,
Cluster: pusherConfigData.Cluster,
Secure: pusherConfigData.Secure,
HTTPClient: http.DefaultClient,
}
var err = client.Trigger(pusherConfigData.Channel, pusherConfigData.Event, data)
if err != nil {
log.Print("Failed to trigger event :", err)
} else {
log.Print("Tigger send successfully")
}
}
confirmationTemplate.Execute(w, nil)
}
func main() {
// [START setting_port]
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
// [END setting_port]
}